json.hpp 856 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659
  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 <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <functional> // hash, less
  34. #include <initializer_list> // initializer_list
  35. #include <iosfwd> // istream, ostream
  36. #include <iterator> // random_access_iterator_tag
  37. #include <memory> // unique_ptr
  38. #include <numeric> // accumulate
  39. #include <string> // string, stoi, to_string
  40. #include <utility> // declval, forward, move, pair, swap
  41. #include <vector> // vector
  42. // #include <nlohmann/adl_serializer.hpp>
  43. #include <utility>
  44. // #include <nlohmann/detail/conversions/from_json.hpp>
  45. #include <algorithm> // transform
  46. #include <array> // array
  47. #include <forward_list> // forward_list
  48. #include <iterator> // inserter, front_inserter, end
  49. #include <map> // map
  50. #include <string> // string
  51. #include <tuple> // tuple, make_tuple
  52. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  53. #include <unordered_map> // unordered_map
  54. #include <utility> // pair, declval
  55. #include <valarray> // valarray
  56. // #include <nlohmann/detail/boolean_operators.hpp>
  57. // Header <ciso646> is removed in C++20.
  58. // See <https://github.com/nlohmann/json/issues/2089> for more information.
  59. #if __cplusplus <= 201703L
  60. #include <ciso646> // and, not, or
  61. #endif
  62. // #include <nlohmann/detail/exceptions.hpp>
  63. #include <exception> // exception
  64. #include <stdexcept> // runtime_error
  65. #include <string> // to_string
  66. // #include <nlohmann/detail/input/position_t.hpp>
  67. #include <cstddef> // size_t
  68. namespace nlohmann
  69. {
  70. namespace detail
  71. {
  72. /// struct to capture the start position of the current token
  73. struct position_t
  74. {
  75. /// the total number of characters read
  76. std::size_t chars_read_total = 0;
  77. /// the number of characters read in the current line
  78. std::size_t chars_read_current_line = 0;
  79. /// the number of lines read
  80. std::size_t lines_read = 0;
  81. /// conversion to size_t to preserve SAX interface
  82. constexpr operator size_t() const
  83. {
  84. return chars_read_total;
  85. }
  86. };
  87. } // namespace detail
  88. } // namespace nlohmann
  89. // #include <nlohmann/detail/macro_scope.hpp>
  90. #include <utility> // pair
  91. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  92. /* Hedley - https://nemequ.github.io/hedley
  93. * Created by Evan Nemerson <evan@nemerson.com>
  94. *
  95. * To the extent possible under law, the author(s) have dedicated all
  96. * copyright and related and neighboring rights to this software to
  97. * the public domain worldwide. This software is distributed without
  98. * any warranty.
  99. *
  100. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  101. * SPDX-License-Identifier: CC0-1.0
  102. */
  103. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 13)
  104. #if defined(JSON_HEDLEY_VERSION)
  105. #undef JSON_HEDLEY_VERSION
  106. #endif
  107. #define JSON_HEDLEY_VERSION 13
  108. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  109. #undef JSON_HEDLEY_STRINGIFY_EX
  110. #endif
  111. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  112. #if defined(JSON_HEDLEY_STRINGIFY)
  113. #undef JSON_HEDLEY_STRINGIFY
  114. #endif
  115. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  116. #if defined(JSON_HEDLEY_CONCAT_EX)
  117. #undef JSON_HEDLEY_CONCAT_EX
  118. #endif
  119. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  120. #if defined(JSON_HEDLEY_CONCAT)
  121. #undef JSON_HEDLEY_CONCAT
  122. #endif
  123. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  124. #if defined(JSON_HEDLEY_CONCAT3_EX)
  125. #undef JSON_HEDLEY_CONCAT3_EX
  126. #endif
  127. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  128. #if defined(JSON_HEDLEY_CONCAT3)
  129. #undef JSON_HEDLEY_CONCAT3
  130. #endif
  131. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  132. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  133. #undef JSON_HEDLEY_VERSION_ENCODE
  134. #endif
  135. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  136. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  137. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  138. #endif
  139. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  140. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  141. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  142. #endif
  143. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  144. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  145. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  146. #endif
  147. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  148. #if defined(JSON_HEDLEY_GNUC_VERSION)
  149. #undef JSON_HEDLEY_GNUC_VERSION
  150. #endif
  151. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  152. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  153. #elif defined(__GNUC__)
  154. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  155. #endif
  156. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  157. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  158. #endif
  159. #if defined(JSON_HEDLEY_GNUC_VERSION)
  160. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  161. #else
  162. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  163. #endif
  164. #if defined(JSON_HEDLEY_MSVC_VERSION)
  165. #undef JSON_HEDLEY_MSVC_VERSION
  166. #endif
  167. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  168. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  169. #elif defined(_MSC_FULL_VER)
  170. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  171. #elif defined(_MSC_VER)
  172. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  173. #endif
  174. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  175. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  176. #endif
  177. #if !defined(_MSC_VER)
  178. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  179. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  180. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  181. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  182. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  183. #else
  184. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  185. #endif
  186. #if defined(JSON_HEDLEY_INTEL_VERSION)
  187. #undef JSON_HEDLEY_INTEL_VERSION
  188. #endif
  189. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  190. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  191. #elif defined(__INTEL_COMPILER)
  192. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  193. #endif
  194. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  195. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  196. #endif
  197. #if defined(JSON_HEDLEY_INTEL_VERSION)
  198. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  199. #else
  200. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  201. #endif
  202. #if defined(JSON_HEDLEY_PGI_VERSION)
  203. #undef JSON_HEDLEY_PGI_VERSION
  204. #endif
  205. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  206. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  207. #endif
  208. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  209. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  210. #endif
  211. #if defined(JSON_HEDLEY_PGI_VERSION)
  212. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  213. #else
  214. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  215. #endif
  216. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  217. #undef JSON_HEDLEY_SUNPRO_VERSION
  218. #endif
  219. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  220. #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)
  221. #elif defined(__SUNPRO_C)
  222. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  223. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  224. #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)
  225. #elif defined(__SUNPRO_CC)
  226. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  227. #endif
  228. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  229. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  230. #endif
  231. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  232. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  233. #else
  234. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  235. #endif
  236. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  237. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  238. #endif
  239. #if defined(__EMSCRIPTEN__)
  240. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  241. #endif
  242. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  243. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  244. #endif
  245. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  246. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  247. #else
  248. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  249. #endif
  250. #if defined(JSON_HEDLEY_ARM_VERSION)
  251. #undef JSON_HEDLEY_ARM_VERSION
  252. #endif
  253. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  254. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  255. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  256. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  257. #endif
  258. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  259. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  260. #endif
  261. #if defined(JSON_HEDLEY_ARM_VERSION)
  262. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  263. #else
  264. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  265. #endif
  266. #if defined(JSON_HEDLEY_IBM_VERSION)
  267. #undef JSON_HEDLEY_IBM_VERSION
  268. #endif
  269. #if defined(__ibmxl__)
  270. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  271. #elif defined(__xlC__) && defined(__xlC_ver__)
  272. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  273. #elif defined(__xlC__)
  274. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  275. #endif
  276. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  277. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  278. #endif
  279. #if defined(JSON_HEDLEY_IBM_VERSION)
  280. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  281. #else
  282. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  283. #endif
  284. #if defined(JSON_HEDLEY_TI_VERSION)
  285. #undef JSON_HEDLEY_TI_VERSION
  286. #endif
  287. #if \
  288. defined(__TI_COMPILER_VERSION__) && \
  289. ( \
  290. defined(__TMS470__) || defined(__TI_ARM__) || \
  291. defined(__MSP430__) || \
  292. defined(__TMS320C2000__) \
  293. )
  294. #if (__TI_COMPILER_VERSION__ >= 16000000)
  295. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  296. #endif
  297. #endif
  298. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  299. #undef JSON_HEDLEY_TI_VERSION_CHECK
  300. #endif
  301. #if defined(JSON_HEDLEY_TI_VERSION)
  302. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  303. #else
  304. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  305. #endif
  306. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  307. #undef JSON_HEDLEY_TI_CL2000_VERSION
  308. #endif
  309. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  310. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  311. #endif
  312. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  313. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  314. #endif
  315. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  316. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  317. #else
  318. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  319. #endif
  320. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  321. #undef JSON_HEDLEY_TI_CL430_VERSION
  322. #endif
  323. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  324. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  325. #endif
  326. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  327. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  328. #endif
  329. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  330. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  331. #else
  332. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  333. #endif
  334. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  335. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  336. #endif
  337. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  338. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  339. #endif
  340. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  341. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  342. #endif
  343. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  344. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  345. #else
  346. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  347. #endif
  348. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  349. #undef JSON_HEDLEY_TI_CL6X_VERSION
  350. #endif
  351. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  352. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  353. #endif
  354. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  355. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  356. #endif
  357. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  358. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  359. #else
  360. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  361. #endif
  362. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  363. #undef JSON_HEDLEY_TI_CL7X_VERSION
  364. #endif
  365. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  366. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  367. #endif
  368. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  369. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  370. #endif
  371. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  372. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  373. #else
  374. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  375. #endif
  376. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  377. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  378. #endif
  379. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  380. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  381. #endif
  382. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  383. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  384. #endif
  385. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  386. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  387. #else
  388. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  389. #endif
  390. #if defined(JSON_HEDLEY_CRAY_VERSION)
  391. #undef JSON_HEDLEY_CRAY_VERSION
  392. #endif
  393. #if defined(_CRAYC)
  394. #if defined(_RELEASE_PATCHLEVEL)
  395. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  396. #else
  397. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  398. #endif
  399. #endif
  400. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  401. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  402. #endif
  403. #if defined(JSON_HEDLEY_CRAY_VERSION)
  404. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  405. #else
  406. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  407. #endif
  408. #if defined(JSON_HEDLEY_IAR_VERSION)
  409. #undef JSON_HEDLEY_IAR_VERSION
  410. #endif
  411. #if defined(__IAR_SYSTEMS_ICC__)
  412. #if __VER__ > 1000
  413. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  414. #else
  415. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  416. #endif
  417. #endif
  418. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  419. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  420. #endif
  421. #if defined(JSON_HEDLEY_IAR_VERSION)
  422. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  423. #else
  424. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  425. #endif
  426. #if defined(JSON_HEDLEY_TINYC_VERSION)
  427. #undef JSON_HEDLEY_TINYC_VERSION
  428. #endif
  429. #if defined(__TINYC__)
  430. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  431. #endif
  432. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  433. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  434. #endif
  435. #if defined(JSON_HEDLEY_TINYC_VERSION)
  436. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  437. #else
  438. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  439. #endif
  440. #if defined(JSON_HEDLEY_DMC_VERSION)
  441. #undef JSON_HEDLEY_DMC_VERSION
  442. #endif
  443. #if defined(__DMC__)
  444. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  445. #endif
  446. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  447. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  448. #endif
  449. #if defined(JSON_HEDLEY_DMC_VERSION)
  450. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  451. #else
  452. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  453. #endif
  454. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  455. #undef JSON_HEDLEY_COMPCERT_VERSION
  456. #endif
  457. #if defined(__COMPCERT_VERSION__)
  458. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  459. #endif
  460. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  461. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  462. #endif
  463. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  464. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  465. #else
  466. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  467. #endif
  468. #if defined(JSON_HEDLEY_PELLES_VERSION)
  469. #undef JSON_HEDLEY_PELLES_VERSION
  470. #endif
  471. #if defined(__POCC__)
  472. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  473. #endif
  474. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  475. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  476. #endif
  477. #if defined(JSON_HEDLEY_PELLES_VERSION)
  478. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  479. #else
  480. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  481. #endif
  482. #if defined(JSON_HEDLEY_GCC_VERSION)
  483. #undef JSON_HEDLEY_GCC_VERSION
  484. #endif
  485. #if \
  486. defined(JSON_HEDLEY_GNUC_VERSION) && \
  487. !defined(__clang__) && \
  488. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  489. !defined(JSON_HEDLEY_PGI_VERSION) && \
  490. !defined(JSON_HEDLEY_ARM_VERSION) && \
  491. !defined(JSON_HEDLEY_TI_VERSION) && \
  492. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  493. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  494. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  495. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  496. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  497. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  498. !defined(__COMPCERT__)
  499. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  500. #endif
  501. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  502. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  503. #endif
  504. #if defined(JSON_HEDLEY_GCC_VERSION)
  505. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  506. #else
  507. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  508. #endif
  509. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  510. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  511. #endif
  512. #if defined(__has_attribute)
  513. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  514. #else
  515. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  516. #endif
  517. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  518. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  519. #endif
  520. #if defined(__has_attribute)
  521. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  522. #else
  523. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  524. #endif
  525. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  526. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  527. #endif
  528. #if defined(__has_attribute)
  529. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  530. #else
  531. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  532. #endif
  533. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  534. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  535. #endif
  536. #if \
  537. defined(__has_cpp_attribute) && \
  538. defined(__cplusplus) && \
  539. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  540. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  541. #else
  542. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  543. #endif
  544. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  545. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  546. #endif
  547. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  548. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  549. #elif \
  550. !defined(JSON_HEDLEY_PGI_VERSION) && \
  551. !defined(JSON_HEDLEY_IAR_VERSION) && \
  552. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  553. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  554. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  555. #else
  556. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  557. #endif
  558. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  559. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  560. #endif
  561. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  562. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  563. #else
  564. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  565. #endif
  566. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  567. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  568. #endif
  569. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  570. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  571. #else
  572. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  573. #endif
  574. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  575. #undef JSON_HEDLEY_HAS_BUILTIN
  576. #endif
  577. #if defined(__has_builtin)
  578. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  579. #else
  580. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  581. #endif
  582. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  583. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  584. #endif
  585. #if defined(__has_builtin)
  586. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  587. #else
  588. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  589. #endif
  590. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  591. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  592. #endif
  593. #if defined(__has_builtin)
  594. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  595. #else
  596. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  597. #endif
  598. #if defined(JSON_HEDLEY_HAS_FEATURE)
  599. #undef JSON_HEDLEY_HAS_FEATURE
  600. #endif
  601. #if defined(__has_feature)
  602. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  603. #else
  604. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  605. #endif
  606. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  607. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  608. #endif
  609. #if defined(__has_feature)
  610. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  611. #else
  612. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  613. #endif
  614. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  615. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  616. #endif
  617. #if defined(__has_feature)
  618. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  619. #else
  620. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  621. #endif
  622. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  623. #undef JSON_HEDLEY_HAS_EXTENSION
  624. #endif
  625. #if defined(__has_extension)
  626. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  627. #else
  628. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  629. #endif
  630. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  631. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  632. #endif
  633. #if defined(__has_extension)
  634. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  635. #else
  636. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  637. #endif
  638. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  639. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  640. #endif
  641. #if defined(__has_extension)
  642. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  643. #else
  644. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  645. #endif
  646. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  647. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  648. #endif
  649. #if defined(__has_declspec_attribute)
  650. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  651. #else
  652. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  653. #endif
  654. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  655. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  656. #endif
  657. #if defined(__has_declspec_attribute)
  658. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  659. #else
  660. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  661. #endif
  662. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  663. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  664. #endif
  665. #if defined(__has_declspec_attribute)
  666. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  667. #else
  668. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  669. #endif
  670. #if defined(JSON_HEDLEY_HAS_WARNING)
  671. #undef JSON_HEDLEY_HAS_WARNING
  672. #endif
  673. #if defined(__has_warning)
  674. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  675. #else
  676. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  677. #endif
  678. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  679. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  680. #endif
  681. #if defined(__has_warning)
  682. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  683. #else
  684. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  685. #endif
  686. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  687. #undef JSON_HEDLEY_GCC_HAS_WARNING
  688. #endif
  689. #if defined(__has_warning)
  690. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  691. #else
  692. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  693. #endif
  694. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  695. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  696. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  697. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  698. #endif
  699. #if defined(__cplusplus)
  700. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  701. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  702. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  703. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  704. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  705. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  706. xpr \
  707. JSON_HEDLEY_DIAGNOSTIC_POP
  708. # else
  709. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  710. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  711. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  712. xpr \
  713. JSON_HEDLEY_DIAGNOSTIC_POP
  714. # endif
  715. # endif
  716. #endif
  717. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  718. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  719. #endif
  720. #if defined(JSON_HEDLEY_CONST_CAST)
  721. #undef JSON_HEDLEY_CONST_CAST
  722. #endif
  723. #if defined(__cplusplus)
  724. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  725. #elif \
  726. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  727. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  728. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  729. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  730. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  731. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  732. ((T) (expr)); \
  733. JSON_HEDLEY_DIAGNOSTIC_POP \
  734. }))
  735. #else
  736. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  737. #endif
  738. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  739. #undef JSON_HEDLEY_REINTERPRET_CAST
  740. #endif
  741. #if defined(__cplusplus)
  742. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  743. #else
  744. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  745. #endif
  746. #if defined(JSON_HEDLEY_STATIC_CAST)
  747. #undef JSON_HEDLEY_STATIC_CAST
  748. #endif
  749. #if defined(__cplusplus)
  750. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  751. #else
  752. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  753. #endif
  754. #if defined(JSON_HEDLEY_CPP_CAST)
  755. #undef JSON_HEDLEY_CPP_CAST
  756. #endif
  757. #if defined(__cplusplus)
  758. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  759. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  760. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  761. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  762. ((T) (expr)) \
  763. JSON_HEDLEY_DIAGNOSTIC_POP
  764. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  765. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  766. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  767. _Pragma("diag_suppress=Pe137") \
  768. JSON_HEDLEY_DIAGNOSTIC_POP \
  769. # else
  770. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  771. # endif
  772. #else
  773. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  774. #endif
  775. #if \
  776. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  777. defined(__clang__) || \
  778. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  779. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  780. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  781. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  782. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  783. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  784. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  785. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  786. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  787. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  788. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  789. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  790. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  791. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  792. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  793. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  794. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  795. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  796. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  797. #else
  798. #define JSON_HEDLEY_PRAGMA(value)
  799. #endif
  800. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  801. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  802. #endif
  803. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  804. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  805. #endif
  806. #if defined(__clang__)
  807. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  808. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  809. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  810. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  811. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  812. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  813. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  814. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  815. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  816. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  817. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  818. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  819. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  820. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  821. #elif \
  822. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  823. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  824. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  825. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  826. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  827. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  828. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  829. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  830. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  831. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  832. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  833. #else
  834. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  835. #define JSON_HEDLEY_DIAGNOSTIC_POP
  836. #endif
  837. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  838. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  839. #endif
  840. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  841. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  842. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  843. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  844. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  845. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  846. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  847. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  848. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  849. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  850. #elif \
  851. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  852. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  853. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  854. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  855. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  856. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  857. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  858. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  859. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  860. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  861. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  862. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  863. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  864. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  865. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  866. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  867. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  868. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  869. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  870. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  871. #else
  872. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  873. #endif
  874. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  875. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  876. #endif
  877. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  878. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  879. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  880. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  881. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  882. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  883. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  884. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  885. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  886. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  887. #elif \
  888. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  889. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  890. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  891. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  892. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  893. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  894. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  895. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  896. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  897. #else
  898. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  899. #endif
  900. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  901. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  902. #endif
  903. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  904. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  905. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  906. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  907. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  908. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  909. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  910. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  911. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  912. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  913. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  914. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  915. #elif \
  916. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  917. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  918. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  919. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  920. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  921. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  922. #else
  923. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  924. #endif
  925. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  926. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  927. #endif
  928. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  929. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  930. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  931. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  932. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  933. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  934. #else
  935. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  936. #endif
  937. #if defined(JSON_HEDLEY_DEPRECATED)
  938. #undef JSON_HEDLEY_DEPRECATED
  939. #endif
  940. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  941. #undef JSON_HEDLEY_DEPRECATED_FOR
  942. #endif
  943. #if JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  944. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  945. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  946. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  947. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  948. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  949. #elif \
  950. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  951. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  952. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  953. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  954. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  955. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  956. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  957. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  958. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  959. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  960. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  961. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  962. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  963. #elif \
  964. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  965. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  966. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  967. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  968. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  969. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  970. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  971. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  972. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  973. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  974. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  975. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  976. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  977. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  978. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  979. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  980. #elif \
  981. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  982. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  983. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  984. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  985. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  986. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  987. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  988. #else
  989. #define JSON_HEDLEY_DEPRECATED(since)
  990. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  991. #endif
  992. #if defined(JSON_HEDLEY_UNAVAILABLE)
  993. #undef JSON_HEDLEY_UNAVAILABLE
  994. #endif
  995. #if \
  996. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  997. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  998. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  999. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  1000. #else
  1001. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  1002. #endif
  1003. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  1004. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  1005. #endif
  1006. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1007. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1008. #endif
  1009. #if (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1010. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1011. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1012. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1013. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1014. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1015. #elif \
  1016. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1017. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1018. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1019. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1020. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1021. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1022. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1023. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1024. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1025. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1026. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1027. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1028. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1029. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1030. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1031. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1032. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1033. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1034. #elif defined(_Check_return_) /* SAL */
  1035. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1036. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1037. #else
  1038. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1039. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1040. #endif
  1041. #if defined(JSON_HEDLEY_SENTINEL)
  1042. #undef JSON_HEDLEY_SENTINEL
  1043. #endif
  1044. #if \
  1045. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1046. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1047. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1048. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  1049. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1050. #else
  1051. #define JSON_HEDLEY_SENTINEL(position)
  1052. #endif
  1053. #if defined(JSON_HEDLEY_NO_RETURN)
  1054. #undef JSON_HEDLEY_NO_RETURN
  1055. #endif
  1056. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1057. #define JSON_HEDLEY_NO_RETURN __noreturn
  1058. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1059. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1060. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1061. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1062. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1063. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1064. #elif \
  1065. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1066. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1067. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1068. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1069. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1070. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1071. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1072. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1073. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1074. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1075. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1076. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1077. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1078. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1079. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1080. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1081. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1082. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1083. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1084. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1085. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1086. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1087. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1088. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1089. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1090. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1091. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1092. #else
  1093. #define JSON_HEDLEY_NO_RETURN
  1094. #endif
  1095. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1096. #undef JSON_HEDLEY_NO_ESCAPE
  1097. #endif
  1098. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1099. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1100. #else
  1101. #define JSON_HEDLEY_NO_ESCAPE
  1102. #endif
  1103. #if defined(JSON_HEDLEY_UNREACHABLE)
  1104. #undef JSON_HEDLEY_UNREACHABLE
  1105. #endif
  1106. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1107. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1108. #endif
  1109. #if defined(JSON_HEDLEY_ASSUME)
  1110. #undef JSON_HEDLEY_ASSUME
  1111. #endif
  1112. #if \
  1113. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1114. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1115. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1116. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1117. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1118. #elif \
  1119. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1120. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1121. #if defined(__cplusplus)
  1122. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1123. #else
  1124. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1125. #endif
  1126. #endif
  1127. #if \
  1128. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1129. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1130. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1131. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1132. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  1133. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1134. #elif defined(JSON_HEDLEY_ASSUME)
  1135. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1136. #endif
  1137. #if !defined(JSON_HEDLEY_ASSUME)
  1138. #if defined(JSON_HEDLEY_UNREACHABLE)
  1139. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1140. #else
  1141. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1142. #endif
  1143. #endif
  1144. #if defined(JSON_HEDLEY_UNREACHABLE)
  1145. #if \
  1146. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1147. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1148. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1149. #else
  1150. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1151. #endif
  1152. #else
  1153. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1154. #endif
  1155. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1156. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1157. #endif
  1158. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1159. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1160. #pragma clang diagnostic ignored "-Wpedantic"
  1161. #endif
  1162. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1163. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1164. #endif
  1165. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1166. #if defined(__clang__)
  1167. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1168. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1169. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1170. #endif
  1171. #endif
  1172. #if defined(JSON_HEDLEY_NON_NULL)
  1173. #undef JSON_HEDLEY_NON_NULL
  1174. #endif
  1175. #if \
  1176. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1177. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1178. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1179. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1180. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1181. #else
  1182. #define JSON_HEDLEY_NON_NULL(...)
  1183. #endif
  1184. JSON_HEDLEY_DIAGNOSTIC_POP
  1185. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1186. #undef JSON_HEDLEY_PRINTF_FORMAT
  1187. #endif
  1188. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1189. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1190. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1191. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1192. #elif \
  1193. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1194. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1195. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1196. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1197. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1198. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1199. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1200. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1201. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1202. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1203. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1204. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1205. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1206. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1207. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1208. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1209. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1210. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1211. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1212. #else
  1213. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1214. #endif
  1215. #if defined(JSON_HEDLEY_CONSTEXPR)
  1216. #undef JSON_HEDLEY_CONSTEXPR
  1217. #endif
  1218. #if defined(__cplusplus)
  1219. #if __cplusplus >= 201103L
  1220. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1221. #endif
  1222. #endif
  1223. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1224. #define JSON_HEDLEY_CONSTEXPR
  1225. #endif
  1226. #if defined(JSON_HEDLEY_PREDICT)
  1227. #undef JSON_HEDLEY_PREDICT
  1228. #endif
  1229. #if defined(JSON_HEDLEY_LIKELY)
  1230. #undef JSON_HEDLEY_LIKELY
  1231. #endif
  1232. #if defined(JSON_HEDLEY_UNLIKELY)
  1233. #undef JSON_HEDLEY_UNLIKELY
  1234. #endif
  1235. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1236. #undef JSON_HEDLEY_UNPREDICTABLE
  1237. #endif
  1238. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1239. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1240. #endif
  1241. #if \
  1242. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  1243. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  1244. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1245. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1246. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1247. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1248. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1249. #elif \
  1250. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  1251. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1252. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1253. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1254. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1255. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1256. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1257. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1258. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1259. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1260. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1261. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1262. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1263. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1264. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1265. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1266. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1267. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1268. (__extension__ ({ \
  1269. double hedley_probability_ = (probability); \
  1270. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1271. }))
  1272. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1273. (__extension__ ({ \
  1274. double hedley_probability_ = (probability); \
  1275. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1276. }))
  1277. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1278. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1279. #else
  1280. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1281. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1282. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1283. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1284. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1285. #endif
  1286. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1287. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1288. #endif
  1289. #if defined(JSON_HEDLEY_MALLOC)
  1290. #undef JSON_HEDLEY_MALLOC
  1291. #endif
  1292. #if \
  1293. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1294. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1295. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1296. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1297. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1298. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1299. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1300. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1301. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1302. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1303. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1304. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1305. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1306. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1307. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1308. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1309. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1310. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1311. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1312. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1313. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  1314. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1315. #else
  1316. #define JSON_HEDLEY_MALLOC
  1317. #endif
  1318. #if defined(JSON_HEDLEY_PURE)
  1319. #undef JSON_HEDLEY_PURE
  1320. #endif
  1321. #if \
  1322. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1323. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1324. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1325. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1326. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1327. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1328. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1329. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1330. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1331. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1332. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1333. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1334. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1335. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1336. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1337. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1338. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1339. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1340. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1341. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1342. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1343. #elif defined(__cplusplus) && \
  1344. ( \
  1345. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1346. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1347. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1348. )
  1349. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1350. #else
  1351. # define JSON_HEDLEY_PURE
  1352. #endif
  1353. #if defined(JSON_HEDLEY_CONST)
  1354. #undef JSON_HEDLEY_CONST
  1355. #endif
  1356. #if \
  1357. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1358. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1359. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1360. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1361. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1362. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1363. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1364. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1365. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1366. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1367. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1368. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1369. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1370. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1371. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1372. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1373. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1374. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1375. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1376. #elif \
  1377. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1378. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1379. #else
  1380. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1381. #endif
  1382. #if defined(JSON_HEDLEY_RESTRICT)
  1383. #undef JSON_HEDLEY_RESTRICT
  1384. #endif
  1385. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1386. #define JSON_HEDLEY_RESTRICT restrict
  1387. #elif \
  1388. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1389. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1390. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1391. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1392. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1393. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1394. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1395. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1396. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1397. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1398. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1399. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1400. defined(__clang__)
  1401. #define JSON_HEDLEY_RESTRICT __restrict
  1402. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1403. #define JSON_HEDLEY_RESTRICT _Restrict
  1404. #else
  1405. #define JSON_HEDLEY_RESTRICT
  1406. #endif
  1407. #if defined(JSON_HEDLEY_INLINE)
  1408. #undef JSON_HEDLEY_INLINE
  1409. #endif
  1410. #if \
  1411. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1412. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1413. #define JSON_HEDLEY_INLINE inline
  1414. #elif \
  1415. defined(JSON_HEDLEY_GCC_VERSION) || \
  1416. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1417. #define JSON_HEDLEY_INLINE __inline__
  1418. #elif \
  1419. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1420. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1421. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1422. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1423. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1424. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1425. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1426. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1427. #define JSON_HEDLEY_INLINE __inline
  1428. #else
  1429. #define JSON_HEDLEY_INLINE
  1430. #endif
  1431. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1432. #undef JSON_HEDLEY_ALWAYS_INLINE
  1433. #endif
  1434. #if \
  1435. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1436. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1437. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1438. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1439. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1440. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1441. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1442. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1443. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1444. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1445. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1446. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1447. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1448. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1449. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1450. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1451. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1452. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1453. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1454. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1455. #elif defined(__cplusplus) && \
  1456. ( \
  1457. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1458. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1459. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1460. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1461. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1462. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1463. )
  1464. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1465. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1466. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1467. #else
  1468. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1469. #endif
  1470. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1471. #undef JSON_HEDLEY_NEVER_INLINE
  1472. #endif
  1473. #if \
  1474. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1475. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1476. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1477. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1478. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1479. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1480. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1481. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1482. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1483. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1484. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1485. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1486. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1487. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1488. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1489. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1490. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1491. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1492. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1493. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1494. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1495. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1496. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1497. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1498. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1499. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1500. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1501. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1502. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1503. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1504. #else
  1505. #define JSON_HEDLEY_NEVER_INLINE
  1506. #endif
  1507. #if defined(JSON_HEDLEY_PRIVATE)
  1508. #undef JSON_HEDLEY_PRIVATE
  1509. #endif
  1510. #if defined(JSON_HEDLEY_PUBLIC)
  1511. #undef JSON_HEDLEY_PUBLIC
  1512. #endif
  1513. #if defined(JSON_HEDLEY_IMPORT)
  1514. #undef JSON_HEDLEY_IMPORT
  1515. #endif
  1516. #if defined(_WIN32) || defined(__CYGWIN__)
  1517. # define JSON_HEDLEY_PRIVATE
  1518. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1519. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1520. #else
  1521. # if \
  1522. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1523. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1524. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1525. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1526. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1527. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1528. ( \
  1529. defined(__TI_EABI__) && \
  1530. ( \
  1531. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1532. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1533. ) \
  1534. )
  1535. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1536. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1537. # else
  1538. # define JSON_HEDLEY_PRIVATE
  1539. # define JSON_HEDLEY_PUBLIC
  1540. # endif
  1541. # define JSON_HEDLEY_IMPORT extern
  1542. #endif
  1543. #if defined(JSON_HEDLEY_NO_THROW)
  1544. #undef JSON_HEDLEY_NO_THROW
  1545. #endif
  1546. #if \
  1547. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1548. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1549. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1550. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1551. #elif \
  1552. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1553. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1554. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1555. #else
  1556. #define JSON_HEDLEY_NO_THROW
  1557. #endif
  1558. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1559. #undef JSON_HEDLEY_FALL_THROUGH
  1560. #endif
  1561. #if \
  1562. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1563. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0)
  1564. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1565. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1566. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1567. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1568. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1569. #elif defined(__fallthrough) /* SAL */
  1570. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1571. #else
  1572. #define JSON_HEDLEY_FALL_THROUGH
  1573. #endif
  1574. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1575. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1576. #endif
  1577. #if \
  1578. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1579. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1580. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1581. #elif defined(_Ret_notnull_) /* SAL */
  1582. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1583. #else
  1584. #define JSON_HEDLEY_RETURNS_NON_NULL
  1585. #endif
  1586. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1587. #undef JSON_HEDLEY_ARRAY_PARAM
  1588. #endif
  1589. #if \
  1590. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1591. !defined(__STDC_NO_VLA__) && \
  1592. !defined(__cplusplus) && \
  1593. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1594. !defined(JSON_HEDLEY_TINYC_VERSION)
  1595. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1596. #else
  1597. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1598. #endif
  1599. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1600. #undef JSON_HEDLEY_IS_CONSTANT
  1601. #endif
  1602. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1603. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1604. #endif
  1605. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1606. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1607. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1608. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1609. #endif
  1610. #if \
  1611. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1612. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1613. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1614. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1615. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1616. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1617. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1618. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1619. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1620. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1621. #endif
  1622. #if !defined(__cplusplus)
  1623. # if \
  1624. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1625. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1626. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1627. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1628. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1629. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1630. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1631. #if defined(__INTPTR_TYPE__)
  1632. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1633. #else
  1634. #include <stdint.h>
  1635. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1636. #endif
  1637. # elif \
  1638. ( \
  1639. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1640. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1641. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1642. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1643. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1644. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1645. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1646. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1647. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1648. #if defined(__INTPTR_TYPE__)
  1649. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1650. #else
  1651. #include <stdint.h>
  1652. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1653. #endif
  1654. # elif \
  1655. defined(JSON_HEDLEY_GCC_VERSION) || \
  1656. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1657. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1658. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1659. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1660. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1661. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1662. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1663. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1664. defined(__clang__)
  1665. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1666. sizeof(void) != \
  1667. sizeof(*( \
  1668. 1 ? \
  1669. ((void*) ((expr) * 0L) ) : \
  1670. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1671. ) \
  1672. ) \
  1673. )
  1674. # endif
  1675. #endif
  1676. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1677. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1678. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1679. #endif
  1680. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1681. #else
  1682. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1683. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1684. #endif
  1685. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1686. #endif
  1687. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1688. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1689. #endif
  1690. #if defined(JSON_HEDLEY_END_C_DECLS)
  1691. #undef JSON_HEDLEY_END_C_DECLS
  1692. #endif
  1693. #if defined(JSON_HEDLEY_C_DECL)
  1694. #undef JSON_HEDLEY_C_DECL
  1695. #endif
  1696. #if defined(__cplusplus)
  1697. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1698. #define JSON_HEDLEY_END_C_DECLS }
  1699. #define JSON_HEDLEY_C_DECL extern "C"
  1700. #else
  1701. #define JSON_HEDLEY_BEGIN_C_DECLS
  1702. #define JSON_HEDLEY_END_C_DECLS
  1703. #define JSON_HEDLEY_C_DECL
  1704. #endif
  1705. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1706. #undef JSON_HEDLEY_STATIC_ASSERT
  1707. #endif
  1708. #if \
  1709. !defined(__cplusplus) && ( \
  1710. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1711. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1712. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1713. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1714. defined(_Static_assert) \
  1715. )
  1716. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1717. #elif \
  1718. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1719. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0)
  1720. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1721. #else
  1722. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1723. #endif
  1724. #if defined(JSON_HEDLEY_NULL)
  1725. #undef JSON_HEDLEY_NULL
  1726. #endif
  1727. #if defined(__cplusplus)
  1728. #if __cplusplus >= 201103L
  1729. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1730. #elif defined(NULL)
  1731. #define JSON_HEDLEY_NULL NULL
  1732. #else
  1733. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1734. #endif
  1735. #elif defined(NULL)
  1736. #define JSON_HEDLEY_NULL NULL
  1737. #else
  1738. #define JSON_HEDLEY_NULL ((void*) 0)
  1739. #endif
  1740. #if defined(JSON_HEDLEY_MESSAGE)
  1741. #undef JSON_HEDLEY_MESSAGE
  1742. #endif
  1743. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1744. # define JSON_HEDLEY_MESSAGE(msg) \
  1745. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1746. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1747. JSON_HEDLEY_PRAGMA(message msg) \
  1748. JSON_HEDLEY_DIAGNOSTIC_POP
  1749. #elif \
  1750. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1751. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1752. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1753. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1754. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1755. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1756. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1757. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1758. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1759. #else
  1760. # define JSON_HEDLEY_MESSAGE(msg)
  1761. #endif
  1762. #if defined(JSON_HEDLEY_WARNING)
  1763. #undef JSON_HEDLEY_WARNING
  1764. #endif
  1765. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1766. # define JSON_HEDLEY_WARNING(msg) \
  1767. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1768. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1769. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1770. JSON_HEDLEY_DIAGNOSTIC_POP
  1771. #elif \
  1772. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1773. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1774. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1775. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1776. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1777. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1778. #else
  1779. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1780. #endif
  1781. #if defined(JSON_HEDLEY_REQUIRE)
  1782. #undef JSON_HEDLEY_REQUIRE
  1783. #endif
  1784. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1785. #undef JSON_HEDLEY_REQUIRE_MSG
  1786. #endif
  1787. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1788. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1789. # define JSON_HEDLEY_REQUIRE(expr) \
  1790. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1791. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1792. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1793. JSON_HEDLEY_DIAGNOSTIC_POP
  1794. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1795. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1796. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1797. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1798. JSON_HEDLEY_DIAGNOSTIC_POP
  1799. # else
  1800. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1801. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1802. # endif
  1803. #else
  1804. # define JSON_HEDLEY_REQUIRE(expr)
  1805. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1806. #endif
  1807. #if defined(JSON_HEDLEY_FLAGS)
  1808. #undef JSON_HEDLEY_FLAGS
  1809. #endif
  1810. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1811. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1812. #endif
  1813. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1814. #undef JSON_HEDLEY_FLAGS_CAST
  1815. #endif
  1816. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1817. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1818. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1819. _Pragma("warning(disable:188)") \
  1820. ((T) (expr)); \
  1821. JSON_HEDLEY_DIAGNOSTIC_POP \
  1822. }))
  1823. #else
  1824. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1825. #endif
  1826. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1827. #undef JSON_HEDLEY_EMPTY_BASES
  1828. #endif
  1829. #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
  1830. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  1831. #else
  1832. #define JSON_HEDLEY_EMPTY_BASES
  1833. #endif
  1834. /* Remaining macros are deprecated. */
  1835. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1836. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1837. #endif
  1838. #if defined(__clang__)
  1839. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1840. #else
  1841. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1842. #endif
  1843. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1844. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1845. #endif
  1846. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1847. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1848. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1849. #endif
  1850. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1851. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1852. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1853. #endif
  1854. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1855. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1856. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1857. #endif
  1858. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1859. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1860. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1861. #endif
  1862. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1863. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1864. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1865. #endif
  1866. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1867. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1868. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1869. #endif
  1870. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1871. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1872. // This file contains all internal macro definitions
  1873. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1874. // exclude unsupported compilers
  1875. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1876. #if defined(__clang__)
  1877. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1878. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1879. #endif
  1880. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1881. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1882. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1883. #endif
  1884. #endif
  1885. #endif
  1886. // C++ language standard detection
  1887. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1888. #define JSON_HAS_CPP_17
  1889. #define JSON_HAS_CPP_14
  1890. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1891. #define JSON_HAS_CPP_14
  1892. #endif
  1893. // disable float-equal warnings on GCC/clang
  1894. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1895. #pragma GCC diagnostic push
  1896. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1897. #endif
  1898. // disable documentation warnings on clang
  1899. #if defined(__clang__)
  1900. #pragma GCC diagnostic push
  1901. #pragma GCC diagnostic ignored "-Wdocumentation"
  1902. #endif
  1903. // allow to disable exceptions
  1904. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1905. #define JSON_THROW(exception) throw exception
  1906. #define JSON_TRY try
  1907. #define JSON_CATCH(exception) catch(exception)
  1908. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1909. #else
  1910. #include <cstdlib>
  1911. #define JSON_THROW(exception) std::abort()
  1912. #define JSON_TRY if(true)
  1913. #define JSON_CATCH(exception) if(false)
  1914. #define JSON_INTERNAL_CATCH(exception) if(false)
  1915. #endif
  1916. // override exception macros
  1917. #if defined(JSON_THROW_USER)
  1918. #undef JSON_THROW
  1919. #define JSON_THROW JSON_THROW_USER
  1920. #endif
  1921. #if defined(JSON_TRY_USER)
  1922. #undef JSON_TRY
  1923. #define JSON_TRY JSON_TRY_USER
  1924. #endif
  1925. #if defined(JSON_CATCH_USER)
  1926. #undef JSON_CATCH
  1927. #define JSON_CATCH JSON_CATCH_USER
  1928. #undef JSON_INTERNAL_CATCH
  1929. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1930. #endif
  1931. #if defined(JSON_INTERNAL_CATCH_USER)
  1932. #undef JSON_INTERNAL_CATCH
  1933. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1934. #endif
  1935. /*!
  1936. @brief macro to briefly define a mapping between an enum and JSON
  1937. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1938. @since version 3.4.0
  1939. */
  1940. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1941. template<typename BasicJsonType> \
  1942. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1943. { \
  1944. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1945. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1946. auto it = std::find_if(std::begin(m), std::end(m), \
  1947. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1948. { \
  1949. return ej_pair.first == e; \
  1950. }); \
  1951. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1952. } \
  1953. template<typename BasicJsonType> \
  1954. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1955. { \
  1956. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1957. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1958. auto it = std::find_if(std::begin(m), std::end(m), \
  1959. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1960. { \
  1961. return ej_pair.second == j; \
  1962. }); \
  1963. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1964. }
  1965. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1966. // may be removed in the future once the class is split.
  1967. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1968. template<template<typename, typename, typename...> class ObjectType, \
  1969. template<typename, typename...> class ArrayType, \
  1970. class StringType, class BooleanType, class NumberIntegerType, \
  1971. class NumberUnsignedType, class NumberFloatType, \
  1972. template<typename> class AllocatorType, \
  1973. template<typename, typename = void> class JSONSerializer, \
  1974. class BinaryType>
  1975. #define NLOHMANN_BASIC_JSON_TPL \
  1976. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1977. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1978. AllocatorType, JSONSerializer, BinaryType>
  1979. namespace nlohmann
  1980. {
  1981. namespace detail
  1982. {
  1983. ////////////////
  1984. // exceptions //
  1985. ////////////////
  1986. /*!
  1987. @brief general exception of the @ref basic_json class
  1988. This class is an extension of `std::exception` objects with a member @a id for
  1989. exception ids. It is used as the base class for all exceptions thrown by the
  1990. @ref basic_json class. This class can hence be used as "wildcard" to catch
  1991. exceptions.
  1992. Subclasses:
  1993. - @ref parse_error for exceptions indicating a parse error
  1994. - @ref invalid_iterator for exceptions indicating errors with iterators
  1995. - @ref type_error for exceptions indicating executing a member function with
  1996. a wrong type
  1997. - @ref out_of_range for exceptions indicating access out of the defined range
  1998. - @ref other_error for exceptions indicating other library errors
  1999. @internal
  2000. @note To have nothrow-copy-constructible exceptions, we internally use
  2001. `std::runtime_error` which can cope with arbitrary-length error messages.
  2002. Intermediate strings are built with static functions and then passed to
  2003. the actual constructor.
  2004. @endinternal
  2005. @liveexample{The following code shows how arbitrary library exceptions can be
  2006. caught.,exception}
  2007. @since version 3.0.0
  2008. */
  2009. class exception : public std::exception
  2010. {
  2011. public:
  2012. /// returns the explanatory string
  2013. JSON_HEDLEY_RETURNS_NON_NULL
  2014. const char* what() const noexcept override
  2015. {
  2016. return m.what();
  2017. }
  2018. /// the id of the exception
  2019. const int id;
  2020. protected:
  2021. JSON_HEDLEY_NON_NULL(3)
  2022. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  2023. static std::string name(const std::string& ename, int id_)
  2024. {
  2025. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2026. }
  2027. private:
  2028. /// an exception object as storage for error messages
  2029. std::runtime_error m;
  2030. };
  2031. /*!
  2032. @brief exception indicating a parse error
  2033. This exception is thrown by the library when a parse error occurs. Parse errors
  2034. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  2035. as when using JSON Patch.
  2036. Member @a byte holds the byte index of the last read character in the input
  2037. file.
  2038. Exceptions have ids 1xx.
  2039. name / id | example message | description
  2040. ------------------------------ | --------------- | -------------------------
  2041. 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.
  2042. 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.
  2043. 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.
  2044. 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.
  2045. 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.
  2046. 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`.
  2047. 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.
  2048. 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.
  2049. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  2050. 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.
  2051. 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.
  2052. 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.
  2053. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  2054. @note For an input with n bytes, 1 is the index of the first character and n+1
  2055. is the index of the terminating null byte or the end of file. This also
  2056. holds true when reading a byte vector (CBOR or MessagePack).
  2057. @liveexample{The following code shows how a `parse_error` exception can be
  2058. caught.,parse_error}
  2059. @sa - @ref exception for the base class of the library exceptions
  2060. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2061. @sa - @ref type_error for exceptions indicating executing a member function with
  2062. a wrong type
  2063. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2064. @sa - @ref other_error for exceptions indicating other library errors
  2065. @since version 3.0.0
  2066. */
  2067. class parse_error : public exception
  2068. {
  2069. public:
  2070. /*!
  2071. @brief create a parse error exception
  2072. @param[in] id_ the id of the exception
  2073. @param[in] pos the position where the error occurred (or with
  2074. chars_read_total=0 if the position cannot be
  2075. determined)
  2076. @param[in] what_arg the explanatory string
  2077. @return parse_error object
  2078. */
  2079. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  2080. {
  2081. std::string w = exception::name("parse_error", id_) + "parse error" +
  2082. position_string(pos) + ": " + what_arg;
  2083. return parse_error(id_, pos.chars_read_total, w.c_str());
  2084. }
  2085. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  2086. {
  2087. std::string w = exception::name("parse_error", id_) + "parse error" +
  2088. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2089. ": " + what_arg;
  2090. return parse_error(id_, byte_, w.c_str());
  2091. }
  2092. /*!
  2093. @brief byte index of the parse error
  2094. The byte index of the last read character in the input file.
  2095. @note For an input with n bytes, 1 is the index of the first character and
  2096. n+1 is the index of the terminating null byte or the end of file.
  2097. This also holds true when reading a byte vector (CBOR or MessagePack).
  2098. */
  2099. const std::size_t byte;
  2100. private:
  2101. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2102. : exception(id_, what_arg), byte(byte_) {}
  2103. static std::string position_string(const position_t& pos)
  2104. {
  2105. return " at line " + std::to_string(pos.lines_read + 1) +
  2106. ", column " + std::to_string(pos.chars_read_current_line);
  2107. }
  2108. };
  2109. /*!
  2110. @brief exception indicating errors with iterators
  2111. This exception is thrown if iterators passed to a library function do not match
  2112. the expected semantics.
  2113. Exceptions have ids 2xx.
  2114. name / id | example message | description
  2115. ----------------------------------- | --------------- | -------------------------
  2116. 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.
  2117. 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.
  2118. 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.
  2119. 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.
  2120. 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.
  2121. 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.
  2122. 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.
  2123. 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.
  2124. 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.
  2125. 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.
  2126. 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.
  2127. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  2128. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  2129. 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().
  2130. @liveexample{The following code shows how an `invalid_iterator` exception can be
  2131. caught.,invalid_iterator}
  2132. @sa - @ref exception for the base class of the library exceptions
  2133. @sa - @ref parse_error for exceptions indicating a parse error
  2134. @sa - @ref type_error for exceptions indicating executing a member function with
  2135. a wrong type
  2136. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2137. @sa - @ref other_error for exceptions indicating other library errors
  2138. @since version 3.0.0
  2139. */
  2140. class invalid_iterator : public exception
  2141. {
  2142. public:
  2143. static invalid_iterator create(int id_, const std::string& what_arg)
  2144. {
  2145. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  2146. return invalid_iterator(id_, w.c_str());
  2147. }
  2148. private:
  2149. JSON_HEDLEY_NON_NULL(3)
  2150. invalid_iterator(int id_, const char* what_arg)
  2151. : exception(id_, what_arg) {}
  2152. };
  2153. /*!
  2154. @brief exception indicating executing a member function with a wrong type
  2155. This exception is thrown in case of a type error; that is, a library function is
  2156. executed on a JSON value whose type does not match the expected semantics.
  2157. Exceptions have ids 3xx.
  2158. name / id | example message | description
  2159. ----------------------------- | --------------- | -------------------------
  2160. 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.
  2161. 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.
  2162. 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 &.
  2163. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  2164. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  2165. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  2166. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  2167. 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.
  2168. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  2169. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  2170. 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.
  2171. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  2172. 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.
  2173. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  2174. 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.
  2175. 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. |
  2176. 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) |
  2177. @liveexample{The following code shows how a `type_error` exception can be
  2178. caught.,type_error}
  2179. @sa - @ref exception for the base class of the library exceptions
  2180. @sa - @ref parse_error for exceptions indicating a parse error
  2181. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2182. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2183. @sa - @ref other_error for exceptions indicating other library errors
  2184. @since version 3.0.0
  2185. */
  2186. class type_error : public exception
  2187. {
  2188. public:
  2189. static type_error create(int id_, const std::string& what_arg)
  2190. {
  2191. std::string w = exception::name("type_error", id_) + what_arg;
  2192. return type_error(id_, w.c_str());
  2193. }
  2194. private:
  2195. JSON_HEDLEY_NON_NULL(3)
  2196. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2197. };
  2198. /*!
  2199. @brief exception indicating access out of the defined range
  2200. This exception is thrown in case a library function is called on an input
  2201. parameter that exceeds the expected range, for instance in case of array
  2202. indices or nonexisting object keys.
  2203. Exceptions have ids 4xx.
  2204. name / id | example message | description
  2205. ------------------------------- | --------------- | -------------------------
  2206. 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.
  2207. 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.
  2208. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  2209. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  2210. 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.
  2211. 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.
  2212. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  2213. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  2214. 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 |
  2215. @liveexample{The following code shows how an `out_of_range` exception can be
  2216. caught.,out_of_range}
  2217. @sa - @ref exception for the base class of the library exceptions
  2218. @sa - @ref parse_error for exceptions indicating a parse error
  2219. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2220. @sa - @ref type_error for exceptions indicating executing a member function with
  2221. a wrong type
  2222. @sa - @ref other_error for exceptions indicating other library errors
  2223. @since version 3.0.0
  2224. */
  2225. class out_of_range : public exception
  2226. {
  2227. public:
  2228. static out_of_range create(int id_, const std::string& what_arg)
  2229. {
  2230. std::string w = exception::name("out_of_range", id_) + what_arg;
  2231. return out_of_range(id_, w.c_str());
  2232. }
  2233. private:
  2234. JSON_HEDLEY_NON_NULL(3)
  2235. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2236. };
  2237. /*!
  2238. @brief exception indicating other library errors
  2239. This exception is thrown in case of errors that cannot be classified with the
  2240. other exception types.
  2241. Exceptions have ids 5xx.
  2242. name / id | example message | description
  2243. ------------------------------ | --------------- | -------------------------
  2244. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  2245. @sa - @ref exception for the base class of the library exceptions
  2246. @sa - @ref parse_error for exceptions indicating a parse error
  2247. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2248. @sa - @ref type_error for exceptions indicating executing a member function with
  2249. a wrong type
  2250. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2251. @liveexample{The following code shows how an `other_error` exception can be
  2252. caught.,other_error}
  2253. @since version 3.0.0
  2254. */
  2255. class other_error : public exception
  2256. {
  2257. public:
  2258. static other_error create(int id_, const std::string& what_arg)
  2259. {
  2260. std::string w = exception::name("other_error", id_) + what_arg;
  2261. return other_error(id_, w.c_str());
  2262. }
  2263. private:
  2264. JSON_HEDLEY_NON_NULL(3)
  2265. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2266. };
  2267. } // namespace detail
  2268. } // namespace nlohmann
  2269. // #include <nlohmann/detail/macro_scope.hpp>
  2270. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2271. #include <cstddef> // size_t
  2272. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2273. // #include <nlohmann/detail/boolean_operators.hpp>
  2274. namespace nlohmann
  2275. {
  2276. namespace detail
  2277. {
  2278. // alias templates to reduce boilerplate
  2279. template<bool B, typename T = void>
  2280. using enable_if_t = typename std::enable_if<B, T>::type;
  2281. template<typename T>
  2282. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2283. // implementation of C++14 index_sequence and affiliates
  2284. // source: https://stackoverflow.com/a/32223343
  2285. template<std::size_t... Ints>
  2286. struct index_sequence
  2287. {
  2288. using type = index_sequence;
  2289. using value_type = std::size_t;
  2290. static constexpr std::size_t size() noexcept
  2291. {
  2292. return sizeof...(Ints);
  2293. }
  2294. };
  2295. template<class Sequence1, class Sequence2>
  2296. struct merge_and_renumber;
  2297. template<std::size_t... I1, std::size_t... I2>
  2298. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  2299. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  2300. template<std::size_t N>
  2301. struct make_index_sequence
  2302. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  2303. typename make_index_sequence < N - N / 2 >::type > {};
  2304. template<> struct make_index_sequence<0> : index_sequence<> {};
  2305. template<> struct make_index_sequence<1> : index_sequence<0> {};
  2306. template<typename... Ts>
  2307. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2308. // dispatch utility (taken from ranges-v3)
  2309. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2310. template<> struct priority_tag<0> {};
  2311. // taken from ranges-v3
  2312. template<typename T>
  2313. struct static_const
  2314. {
  2315. static constexpr T value{};
  2316. };
  2317. template<typename T>
  2318. constexpr T static_const<T>::value;
  2319. } // namespace detail
  2320. } // namespace nlohmann
  2321. // #include <nlohmann/detail/meta/type_traits.hpp>
  2322. #include <limits> // numeric_limits
  2323. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2324. #include <utility> // declval
  2325. // #include <nlohmann/detail/boolean_operators.hpp>
  2326. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2327. #include <iterator> // random_access_iterator_tag
  2328. // #include <nlohmann/detail/meta/void_t.hpp>
  2329. namespace nlohmann
  2330. {
  2331. namespace detail
  2332. {
  2333. template <typename ...Ts> struct make_void
  2334. {
  2335. using type = void;
  2336. };
  2337. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2338. } // namespace detail
  2339. } // namespace nlohmann
  2340. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2341. namespace nlohmann
  2342. {
  2343. namespace detail
  2344. {
  2345. template <typename It, typename = void>
  2346. struct iterator_types {};
  2347. template <typename It>
  2348. struct iterator_types <
  2349. It,
  2350. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2351. typename It::reference, typename It::iterator_category >>
  2352. {
  2353. using difference_type = typename It::difference_type;
  2354. using value_type = typename It::value_type;
  2355. using pointer = typename It::pointer;
  2356. using reference = typename It::reference;
  2357. using iterator_category = typename It::iterator_category;
  2358. };
  2359. // This is required as some compilers implement std::iterator_traits in a way that
  2360. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2361. template <typename T, typename = void>
  2362. struct iterator_traits
  2363. {
  2364. };
  2365. template <typename T>
  2366. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2367. : iterator_types<T>
  2368. {
  2369. };
  2370. template <typename T>
  2371. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2372. {
  2373. using iterator_category = std::random_access_iterator_tag;
  2374. using value_type = T;
  2375. using difference_type = ptrdiff_t;
  2376. using pointer = T*;
  2377. using reference = T&;
  2378. };
  2379. } // namespace detail
  2380. } // namespace nlohmann
  2381. // #include <nlohmann/detail/macro_scope.hpp>
  2382. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2383. // #include <nlohmann/detail/meta/detected.hpp>
  2384. #include <type_traits>
  2385. // #include <nlohmann/detail/meta/void_t.hpp>
  2386. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2387. namespace nlohmann
  2388. {
  2389. namespace detail
  2390. {
  2391. struct nonesuch
  2392. {
  2393. nonesuch() = delete;
  2394. ~nonesuch() = delete;
  2395. nonesuch(nonesuch const&) = delete;
  2396. nonesuch(nonesuch const&&) = delete;
  2397. void operator=(nonesuch const&) = delete;
  2398. void operator=(nonesuch&&) = delete;
  2399. };
  2400. template <class Default,
  2401. class AlwaysVoid,
  2402. template <class...> class Op,
  2403. class... Args>
  2404. struct detector
  2405. {
  2406. using value_t = std::false_type;
  2407. using type = Default;
  2408. };
  2409. template <class Default, template <class...> class Op, class... Args>
  2410. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2411. {
  2412. using value_t = std::true_type;
  2413. using type = Op<Args...>;
  2414. };
  2415. template <template <class...> class Op, class... Args>
  2416. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2417. template <template <class...> class Op, class... Args>
  2418. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2419. template <class Default, template <class...> class Op, class... Args>
  2420. using detected_or = detector<Default, void, Op, Args...>;
  2421. template <class Default, template <class...> class Op, class... Args>
  2422. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2423. template <class Expected, template <class...> class Op, class... Args>
  2424. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2425. template <class To, template <class...> class Op, class... Args>
  2426. using is_detected_convertible =
  2427. std::is_convertible<detected_t<Op, Args...>, To>;
  2428. } // namespace detail
  2429. } // namespace nlohmann
  2430. // #include <nlohmann/json_fwd.hpp>
  2431. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2432. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2433. #include <cstdint> // int64_t, uint64_t
  2434. #include <map> // map
  2435. #include <memory> // allocator
  2436. #include <string> // string
  2437. #include <vector> // vector
  2438. /*!
  2439. @brief namespace for Niels Lohmann
  2440. @see https://github.com/nlohmann
  2441. @since version 1.0.0
  2442. */
  2443. namespace nlohmann
  2444. {
  2445. /*!
  2446. @brief default JSONSerializer template argument
  2447. This serializer ignores the template arguments and uses ADL
  2448. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2449. for serialization.
  2450. */
  2451. template<typename T = void, typename SFINAE = void>
  2452. struct adl_serializer;
  2453. template<template<typename U, typename V, typename... Args> class ObjectType =
  2454. std::map,
  2455. template<typename U, typename... Args> class ArrayType = std::vector,
  2456. class StringType = std::string, class BooleanType = bool,
  2457. class NumberIntegerType = std::int64_t,
  2458. class NumberUnsignedType = std::uint64_t,
  2459. class NumberFloatType = double,
  2460. template<typename U> class AllocatorType = std::allocator,
  2461. template<typename T, typename SFINAE = void> class JSONSerializer =
  2462. adl_serializer,
  2463. class BinaryType = std::vector<std::uint8_t>>
  2464. class basic_json;
  2465. /*!
  2466. @brief JSON Pointer
  2467. A JSON pointer defines a string syntax for identifying a specific value
  2468. within a JSON document. It can be used with functions `at` and
  2469. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2470. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2471. @since version 2.0.0
  2472. */
  2473. template<typename BasicJsonType>
  2474. class json_pointer;
  2475. /*!
  2476. @brief default JSON class
  2477. This type is the default specialization of the @ref basic_json class which
  2478. uses the standard template types.
  2479. @since version 1.0.0
  2480. */
  2481. using json = basic_json<>;
  2482. } // namespace nlohmann
  2483. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2484. namespace nlohmann
  2485. {
  2486. /*!
  2487. @brief detail namespace with internal helper functions
  2488. This namespace collects functions that should not be exposed,
  2489. implementations of some @ref basic_json methods, and meta-programming helpers.
  2490. @since version 2.1.0
  2491. */
  2492. namespace detail
  2493. {
  2494. /////////////
  2495. // helpers //
  2496. /////////////
  2497. // Note to maintainers:
  2498. //
  2499. // Every trait in this file expects a non CV-qualified type.
  2500. // The only exceptions are in the 'aliases for detected' section
  2501. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2502. //
  2503. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2504. // (e.g. to_json(BasicJsonType&, const T&))
  2505. template<typename> struct is_basic_json : std::false_type {};
  2506. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2507. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2508. //////////////////////
  2509. // json_ref helpers //
  2510. //////////////////////
  2511. template <typename>
  2512. class json_ref;
  2513. template<typename>
  2514. struct is_json_ref : std::false_type {};
  2515. template <typename T>
  2516. struct is_json_ref<json_ref<T>> : std::true_type {};
  2517. //////////////////////////
  2518. // aliases for detected //
  2519. //////////////////////////
  2520. template <typename T>
  2521. using mapped_type_t = typename T::mapped_type;
  2522. template <typename T>
  2523. using key_type_t = typename T::key_type;
  2524. template <typename T>
  2525. using value_type_t = typename T::value_type;
  2526. template <typename T>
  2527. using difference_type_t = typename T::difference_type;
  2528. template <typename T>
  2529. using pointer_t = typename T::pointer;
  2530. template <typename T>
  2531. using reference_t = typename T::reference;
  2532. template <typename T>
  2533. using iterator_category_t = typename T::iterator_category;
  2534. template <typename T>
  2535. using iterator_t = typename T::iterator;
  2536. template <typename T, typename... Args>
  2537. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2538. template <typename T, typename... Args>
  2539. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2540. template <typename T, typename U>
  2541. using get_template_function = decltype(std::declval<T>().template get<U>());
  2542. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2543. template <typename BasicJsonType, typename T, typename = void>
  2544. struct has_from_json : std::false_type {};
  2545. template <typename BasicJsonType, typename T>
  2546. struct has_from_json<BasicJsonType, T,
  2547. enable_if_t<not is_basic_json<T>::value>>
  2548. {
  2549. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2550. static constexpr bool value =
  2551. is_detected_exact<void, from_json_function, serializer,
  2552. const BasicJsonType&, T&>::value;
  2553. };
  2554. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2555. // this overload is used for non-default-constructible user-defined-types
  2556. template <typename BasicJsonType, typename T, typename = void>
  2557. struct has_non_default_from_json : std::false_type {};
  2558. template<typename BasicJsonType, typename T>
  2559. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2560. {
  2561. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2562. static constexpr bool value =
  2563. is_detected_exact<T, from_json_function, serializer,
  2564. const BasicJsonType&>::value;
  2565. };
  2566. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2567. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2568. template <typename BasicJsonType, typename T, typename = void>
  2569. struct has_to_json : std::false_type {};
  2570. template <typename BasicJsonType, typename T>
  2571. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2572. {
  2573. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2574. static constexpr bool value =
  2575. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2576. T>::value;
  2577. };
  2578. ///////////////////
  2579. // is_ functions //
  2580. ///////////////////
  2581. template <typename T, typename = void>
  2582. struct is_iterator_traits : std::false_type {};
  2583. template <typename T>
  2584. struct is_iterator_traits<iterator_traits<T>>
  2585. {
  2586. private:
  2587. using traits = iterator_traits<T>;
  2588. public:
  2589. static constexpr auto value =
  2590. is_detected<value_type_t, traits>::value &&
  2591. is_detected<difference_type_t, traits>::value &&
  2592. is_detected<pointer_t, traits>::value &&
  2593. is_detected<iterator_category_t, traits>::value &&
  2594. is_detected<reference_t, traits>::value;
  2595. };
  2596. // source: https://stackoverflow.com/a/37193089/4116453
  2597. template <typename T, typename = void>
  2598. struct is_complete_type : std::false_type {};
  2599. template <typename T>
  2600. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2601. template <typename BasicJsonType, typename CompatibleObjectType,
  2602. typename = void>
  2603. struct is_compatible_object_type_impl : std::false_type {};
  2604. template <typename BasicJsonType, typename CompatibleObjectType>
  2605. struct is_compatible_object_type_impl <
  2606. BasicJsonType, CompatibleObjectType,
  2607. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  2608. is_detected<key_type_t, CompatibleObjectType>::value >>
  2609. {
  2610. using object_t = typename BasicJsonType::object_t;
  2611. // macOS's is_constructible does not play well with nonesuch...
  2612. static constexpr bool value =
  2613. std::is_constructible<typename object_t::key_type,
  2614. typename CompatibleObjectType::key_type>::value and
  2615. std::is_constructible<typename object_t::mapped_type,
  2616. typename CompatibleObjectType::mapped_type>::value;
  2617. };
  2618. template <typename BasicJsonType, typename CompatibleObjectType>
  2619. struct is_compatible_object_type
  2620. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2621. template <typename BasicJsonType, typename ConstructibleObjectType,
  2622. typename = void>
  2623. struct is_constructible_object_type_impl : std::false_type {};
  2624. template <typename BasicJsonType, typename ConstructibleObjectType>
  2625. struct is_constructible_object_type_impl <
  2626. BasicJsonType, ConstructibleObjectType,
  2627. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  2628. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2629. {
  2630. using object_t = typename BasicJsonType::object_t;
  2631. static constexpr bool value =
  2632. (std::is_default_constructible<ConstructibleObjectType>::value and
  2633. (std::is_move_assignable<ConstructibleObjectType>::value or
  2634. std::is_copy_assignable<ConstructibleObjectType>::value) and
  2635. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2636. typename object_t::key_type>::value and
  2637. std::is_same <
  2638. typename object_t::mapped_type,
  2639. typename ConstructibleObjectType::mapped_type >::value)) or
  2640. (has_from_json<BasicJsonType,
  2641. typename ConstructibleObjectType::mapped_type>::value or
  2642. has_non_default_from_json <
  2643. BasicJsonType,
  2644. typename ConstructibleObjectType::mapped_type >::value);
  2645. };
  2646. template <typename BasicJsonType, typename ConstructibleObjectType>
  2647. struct is_constructible_object_type
  2648. : is_constructible_object_type_impl<BasicJsonType,
  2649. ConstructibleObjectType> {};
  2650. template <typename BasicJsonType, typename CompatibleStringType,
  2651. typename = void>
  2652. struct is_compatible_string_type_impl : std::false_type {};
  2653. template <typename BasicJsonType, typename CompatibleStringType>
  2654. struct is_compatible_string_type_impl <
  2655. BasicJsonType, CompatibleStringType,
  2656. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2657. value_type_t, CompatibleStringType>::value >>
  2658. {
  2659. static constexpr auto value =
  2660. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2661. };
  2662. template <typename BasicJsonType, typename ConstructibleStringType>
  2663. struct is_compatible_string_type
  2664. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2665. template <typename BasicJsonType, typename ConstructibleStringType,
  2666. typename = void>
  2667. struct is_constructible_string_type_impl : std::false_type {};
  2668. template <typename BasicJsonType, typename ConstructibleStringType>
  2669. struct is_constructible_string_type_impl <
  2670. BasicJsonType, ConstructibleStringType,
  2671. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2672. value_type_t, ConstructibleStringType>::value >>
  2673. {
  2674. static constexpr auto value =
  2675. std::is_constructible<ConstructibleStringType,
  2676. typename BasicJsonType::string_t>::value;
  2677. };
  2678. template <typename BasicJsonType, typename ConstructibleStringType>
  2679. struct is_constructible_string_type
  2680. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2681. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2682. struct is_compatible_array_type_impl : std::false_type {};
  2683. template <typename BasicJsonType, typename CompatibleArrayType>
  2684. struct is_compatible_array_type_impl <
  2685. BasicJsonType, CompatibleArrayType,
  2686. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  2687. is_detected<iterator_t, CompatibleArrayType>::value and
  2688. // This is needed because json_reverse_iterator has a ::iterator type...
  2689. // Therefore it is detected as a CompatibleArrayType.
  2690. // The real fix would be to have an Iterable concept.
  2691. not is_iterator_traits<
  2692. iterator_traits<CompatibleArrayType>>::value >>
  2693. {
  2694. static constexpr bool value =
  2695. std::is_constructible<BasicJsonType,
  2696. typename CompatibleArrayType::value_type>::value;
  2697. };
  2698. template <typename BasicJsonType, typename CompatibleArrayType>
  2699. struct is_compatible_array_type
  2700. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2701. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2702. struct is_constructible_array_type_impl : std::false_type {};
  2703. template <typename BasicJsonType, typename ConstructibleArrayType>
  2704. struct is_constructible_array_type_impl <
  2705. BasicJsonType, ConstructibleArrayType,
  2706. enable_if_t<std::is_same<ConstructibleArrayType,
  2707. typename BasicJsonType::value_type>::value >>
  2708. : std::true_type {};
  2709. template <typename BasicJsonType, typename ConstructibleArrayType>
  2710. struct is_constructible_array_type_impl <
  2711. BasicJsonType, ConstructibleArrayType,
  2712. enable_if_t<not std::is_same<ConstructibleArrayType,
  2713. typename BasicJsonType::value_type>::value and
  2714. std::is_default_constructible<ConstructibleArrayType>::value and
  2715. (std::is_move_assignable<ConstructibleArrayType>::value or
  2716. std::is_copy_assignable<ConstructibleArrayType>::value) and
  2717. is_detected<value_type_t, ConstructibleArrayType>::value and
  2718. is_detected<iterator_t, ConstructibleArrayType>::value and
  2719. is_complete_type<
  2720. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  2721. {
  2722. static constexpr bool value =
  2723. // This is needed because json_reverse_iterator has a ::iterator type,
  2724. // furthermore, std::back_insert_iterator (and other iterators) have a
  2725. // base class `iterator`... Therefore it is detected as a
  2726. // ConstructibleArrayType. The real fix would be to have an Iterable
  2727. // concept.
  2728. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  2729. (std::is_same<typename ConstructibleArrayType::value_type,
  2730. typename BasicJsonType::array_t::value_type>::value or
  2731. has_from_json<BasicJsonType,
  2732. typename ConstructibleArrayType::value_type>::value or
  2733. has_non_default_from_json <
  2734. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2735. };
  2736. template <typename BasicJsonType, typename ConstructibleArrayType>
  2737. struct is_constructible_array_type
  2738. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2739. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  2740. typename = void>
  2741. struct is_compatible_integer_type_impl : std::false_type {};
  2742. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2743. struct is_compatible_integer_type_impl <
  2744. RealIntegerType, CompatibleNumberIntegerType,
  2745. enable_if_t<std::is_integral<RealIntegerType>::value and
  2746. std::is_integral<CompatibleNumberIntegerType>::value and
  2747. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2748. {
  2749. // is there an assert somewhere on overflows?
  2750. using RealLimits = std::numeric_limits<RealIntegerType>;
  2751. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2752. static constexpr auto value =
  2753. std::is_constructible<RealIntegerType,
  2754. CompatibleNumberIntegerType>::value and
  2755. CompatibleLimits::is_integer and
  2756. RealLimits::is_signed == CompatibleLimits::is_signed;
  2757. };
  2758. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2759. struct is_compatible_integer_type
  2760. : is_compatible_integer_type_impl<RealIntegerType,
  2761. CompatibleNumberIntegerType> {};
  2762. template <typename BasicJsonType, typename CompatibleType, typename = void>
  2763. struct is_compatible_type_impl: std::false_type {};
  2764. template <typename BasicJsonType, typename CompatibleType>
  2765. struct is_compatible_type_impl <
  2766. BasicJsonType, CompatibleType,
  2767. enable_if_t<is_complete_type<CompatibleType>::value >>
  2768. {
  2769. static constexpr bool value =
  2770. has_to_json<BasicJsonType, CompatibleType>::value;
  2771. };
  2772. template <typename BasicJsonType, typename CompatibleType>
  2773. struct is_compatible_type
  2774. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2775. // https://en.cppreference.com/w/cpp/types/conjunction
  2776. template<class...> struct conjunction : std::true_type { };
  2777. template<class B1> struct conjunction<B1> : B1 { };
  2778. template<class B1, class... Bn>
  2779. struct conjunction<B1, Bn...>
  2780. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  2781. template <typename T1, typename T2>
  2782. struct is_constructible_tuple : std::false_type {};
  2783. template <typename T1, typename... Args>
  2784. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<std::is_constructible<T1, Args>...> {};
  2785. } // namespace detail
  2786. } // namespace nlohmann
  2787. // #include <nlohmann/detail/value_t.hpp>
  2788. #include <array> // array
  2789. #include <cstddef> // size_t
  2790. #include <cstdint> // uint8_t
  2791. #include <string> // string
  2792. // #include <nlohmann/detail/boolean_operators.hpp>
  2793. namespace nlohmann
  2794. {
  2795. namespace detail
  2796. {
  2797. ///////////////////////////
  2798. // JSON type enumeration //
  2799. ///////////////////////////
  2800. /*!
  2801. @brief the JSON type enumeration
  2802. This enumeration collects the different JSON types. It is internally used to
  2803. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2804. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2805. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2806. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2807. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2808. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2809. @ref basic_json::is_structured() rely on it.
  2810. @note There are three enumeration entries (number_integer, number_unsigned, and
  2811. number_float), because the library distinguishes these three types for numbers:
  2812. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2813. @ref basic_json::number_integer_t is used for signed integers, and
  2814. @ref basic_json::number_float_t is used for floating-point numbers or to
  2815. approximate integers which do not fit in the limits of their respective type.
  2816. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2817. value with the default value for a given type
  2818. @since version 1.0.0
  2819. */
  2820. enum class value_t : std::uint8_t
  2821. {
  2822. null, ///< null value
  2823. object, ///< object (unordered set of name/value pairs)
  2824. array, ///< array (ordered collection of values)
  2825. string, ///< string value
  2826. boolean, ///< boolean value
  2827. number_integer, ///< number value (signed integer)
  2828. number_unsigned, ///< number value (unsigned integer)
  2829. number_float, ///< number value (floating-point)
  2830. binary, ///< binary array (ordered collection of bytes)
  2831. discarded ///< discarded by the parser callback function
  2832. };
  2833. /*!
  2834. @brief comparison operator for JSON types
  2835. Returns an ordering that is similar to Python:
  2836. - order: null < boolean < number < object < array < string < binary
  2837. - furthermore, each type is not smaller than itself
  2838. - discarded values are not comparable
  2839. - binary is represented as a b"" string in python and directly comparable to a
  2840. string; however, making a binary array directly comparable with a string would
  2841. be surprising behavior in a JSON file.
  2842. @since version 1.0.0
  2843. */
  2844. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2845. {
  2846. static constexpr std::array<std::uint8_t, 9> order = {{
  2847. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2848. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  2849. 6 /* binary */
  2850. }
  2851. };
  2852. const auto l_index = static_cast<std::size_t>(lhs);
  2853. const auto r_index = static_cast<std::size_t>(rhs);
  2854. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  2855. }
  2856. } // namespace detail
  2857. } // namespace nlohmann
  2858. namespace nlohmann
  2859. {
  2860. namespace detail
  2861. {
  2862. template<typename BasicJsonType>
  2863. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2864. {
  2865. if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
  2866. {
  2867. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2868. }
  2869. n = nullptr;
  2870. }
  2871. // overloads for basic_json template parameters
  2872. template<typename BasicJsonType, typename ArithmeticType,
  2873. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  2874. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2875. int> = 0>
  2876. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2877. {
  2878. switch (static_cast<value_t>(j))
  2879. {
  2880. case value_t::number_unsigned:
  2881. {
  2882. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2883. break;
  2884. }
  2885. case value_t::number_integer:
  2886. {
  2887. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2888. break;
  2889. }
  2890. case value_t::number_float:
  2891. {
  2892. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2893. break;
  2894. }
  2895. default:
  2896. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2897. }
  2898. }
  2899. template<typename BasicJsonType>
  2900. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2901. {
  2902. if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
  2903. {
  2904. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2905. }
  2906. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2907. }
  2908. template<typename BasicJsonType>
  2909. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2910. {
  2911. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2912. {
  2913. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2914. }
  2915. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2916. }
  2917. template <
  2918. typename BasicJsonType, typename ConstructibleStringType,
  2919. enable_if_t <
  2920. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  2921. not std::is_same<typename BasicJsonType::string_t,
  2922. ConstructibleStringType>::value,
  2923. int > = 0 >
  2924. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2925. {
  2926. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2927. {
  2928. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2929. }
  2930. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2931. }
  2932. template<typename BasicJsonType>
  2933. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2934. {
  2935. get_arithmetic_value(j, val);
  2936. }
  2937. template<typename BasicJsonType>
  2938. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2939. {
  2940. get_arithmetic_value(j, val);
  2941. }
  2942. template<typename BasicJsonType>
  2943. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2944. {
  2945. get_arithmetic_value(j, val);
  2946. }
  2947. template<typename BasicJsonType, typename EnumType,
  2948. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2949. void from_json(const BasicJsonType& j, EnumType& e)
  2950. {
  2951. typename std::underlying_type<EnumType>::type val;
  2952. get_arithmetic_value(j, val);
  2953. e = static_cast<EnumType>(val);
  2954. }
  2955. // forward_list doesn't have an insert method
  2956. template<typename BasicJsonType, typename T, typename Allocator,
  2957. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2958. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  2959. {
  2960. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2961. {
  2962. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2963. }
  2964. l.clear();
  2965. std::transform(j.rbegin(), j.rend(),
  2966. std::front_inserter(l), [](const BasicJsonType & i)
  2967. {
  2968. return i.template get<T>();
  2969. });
  2970. }
  2971. // valarray doesn't have an insert method
  2972. template<typename BasicJsonType, typename T,
  2973. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2974. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  2975. {
  2976. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2977. {
  2978. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2979. }
  2980. l.resize(j.size());
  2981. std::copy(j.begin(), j.end(), std::begin(l));
  2982. }
  2983. template <typename BasicJsonType, typename T, std::size_t N>
  2984. auto from_json(const BasicJsonType& j, T (&arr)[N])
  2985. -> decltype(j.template get<T>(), void())
  2986. {
  2987. for (std::size_t i = 0; i < N; ++i)
  2988. {
  2989. arr[i] = j.at(i).template get<T>();
  2990. }
  2991. }
  2992. template<typename BasicJsonType>
  2993. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  2994. {
  2995. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  2996. }
  2997. template <typename BasicJsonType, typename T, std::size_t N>
  2998. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  2999. priority_tag<2> /*unused*/)
  3000. -> decltype(j.template get<T>(), void())
  3001. {
  3002. for (std::size_t i = 0; i < N; ++i)
  3003. {
  3004. arr[i] = j.at(i).template get<T>();
  3005. }
  3006. }
  3007. template<typename BasicJsonType, typename ConstructibleArrayType>
  3008. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3009. -> decltype(
  3010. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3011. j.template get<typename ConstructibleArrayType::value_type>(),
  3012. void())
  3013. {
  3014. using std::end;
  3015. ConstructibleArrayType ret;
  3016. ret.reserve(j.size());
  3017. std::transform(j.begin(), j.end(),
  3018. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3019. {
  3020. // get<BasicJsonType>() returns *this, this won't call a from_json
  3021. // method when value_type is BasicJsonType
  3022. return i.template get<typename ConstructibleArrayType::value_type>();
  3023. });
  3024. arr = std::move(ret);
  3025. }
  3026. template <typename BasicJsonType, typename ConstructibleArrayType>
  3027. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3028. priority_tag<0> /*unused*/)
  3029. {
  3030. using std::end;
  3031. ConstructibleArrayType ret;
  3032. std::transform(
  3033. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3034. [](const BasicJsonType & i)
  3035. {
  3036. // get<BasicJsonType>() returns *this, this won't call a from_json
  3037. // method when value_type is BasicJsonType
  3038. return i.template get<typename ConstructibleArrayType::value_type>();
  3039. });
  3040. arr = std::move(ret);
  3041. }
  3042. template <typename BasicJsonType, typename ConstructibleArrayType,
  3043. enable_if_t <
  3044. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  3045. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  3046. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  3047. not std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value and
  3048. not is_basic_json<ConstructibleArrayType>::value,
  3049. int > = 0 >
  3050. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3051. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3052. j.template get<typename ConstructibleArrayType::value_type>(),
  3053. void())
  3054. {
  3055. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  3056. {
  3057. JSON_THROW(type_error::create(302, "type must be array, but is " +
  3058. std::string(j.type_name())));
  3059. }
  3060. from_json_array_impl(j, arr, priority_tag<3> {});
  3061. }
  3062. template <typename BasicJsonType>
  3063. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3064. {
  3065. if (JSON_HEDLEY_UNLIKELY(not j.is_binary()))
  3066. {
  3067. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name())));
  3068. }
  3069. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3070. }
  3071. template<typename BasicJsonType, typename ConstructibleObjectType,
  3072. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3073. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3074. {
  3075. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  3076. {
  3077. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  3078. }
  3079. ConstructibleObjectType ret;
  3080. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3081. using value_type = typename ConstructibleObjectType::value_type;
  3082. std::transform(
  3083. inner_object->begin(), inner_object->end(),
  3084. std::inserter(ret, ret.begin()),
  3085. [](typename BasicJsonType::object_t::value_type const & p)
  3086. {
  3087. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3088. });
  3089. obj = std::move(ret);
  3090. }
  3091. // overload for arithmetic types, not chosen for basic_json template arguments
  3092. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3093. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3094. // an arithmetic type?
  3095. template<typename BasicJsonType, typename ArithmeticType,
  3096. enable_if_t <
  3097. std::is_arithmetic<ArithmeticType>::value and
  3098. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  3099. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  3100. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  3101. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3102. int> = 0>
  3103. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3104. {
  3105. switch (static_cast<value_t>(j))
  3106. {
  3107. case value_t::number_unsigned:
  3108. {
  3109. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3110. break;
  3111. }
  3112. case value_t::number_integer:
  3113. {
  3114. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3115. break;
  3116. }
  3117. case value_t::number_float:
  3118. {
  3119. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3120. break;
  3121. }
  3122. case value_t::boolean:
  3123. {
  3124. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3125. break;
  3126. }
  3127. default:
  3128. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  3129. }
  3130. }
  3131. template<typename BasicJsonType, typename A1, typename A2>
  3132. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  3133. {
  3134. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  3135. }
  3136. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3137. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  3138. {
  3139. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  3140. }
  3141. template<typename BasicJsonType, typename... Args>
  3142. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  3143. {
  3144. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3145. }
  3146. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3147. typename = enable_if_t<not std::is_constructible<
  3148. typename BasicJsonType::string_t, Key>::value>>
  3149. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3150. {
  3151. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  3152. {
  3153. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3154. }
  3155. m.clear();
  3156. for (const auto& p : j)
  3157. {
  3158. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  3159. {
  3160. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3161. }
  3162. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3163. }
  3164. }
  3165. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3166. typename = enable_if_t<not std::is_constructible<
  3167. typename BasicJsonType::string_t, Key>::value>>
  3168. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3169. {
  3170. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  3171. {
  3172. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3173. }
  3174. m.clear();
  3175. for (const auto& p : j)
  3176. {
  3177. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  3178. {
  3179. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3180. }
  3181. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3182. }
  3183. }
  3184. struct from_json_fn
  3185. {
  3186. template<typename BasicJsonType, typename T>
  3187. auto operator()(const BasicJsonType& j, T& val) const
  3188. noexcept(noexcept(from_json(j, val)))
  3189. -> decltype(from_json(j, val), void())
  3190. {
  3191. return from_json(j, val);
  3192. }
  3193. };
  3194. } // namespace detail
  3195. /// namespace to hold default `from_json` function
  3196. /// to see why this is required:
  3197. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3198. namespace
  3199. {
  3200. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  3201. } // namespace
  3202. } // namespace nlohmann
  3203. // #include <nlohmann/detail/conversions/to_json.hpp>
  3204. #include <algorithm> // copy
  3205. #include <iterator> // begin, end
  3206. #include <string> // string
  3207. #include <tuple> // tuple, get
  3208. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3209. #include <utility> // move, forward, declval, pair
  3210. #include <valarray> // valarray
  3211. #include <vector> // vector
  3212. // #include <nlohmann/detail/boolean_operators.hpp>
  3213. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3214. #include <cstddef> // size_t
  3215. #include <iterator> // input_iterator_tag
  3216. #include <string> // string, to_string
  3217. #include <tuple> // tuple_size, get, tuple_element
  3218. // #include <nlohmann/detail/meta/type_traits.hpp>
  3219. // #include <nlohmann/detail/value_t.hpp>
  3220. namespace nlohmann
  3221. {
  3222. namespace detail
  3223. {
  3224. template<typename string_type>
  3225. void int_to_string( string_type& target, std::size_t value )
  3226. {
  3227. target = std::to_string(value);
  3228. }
  3229. template <typename IteratorType> class iteration_proxy_value
  3230. {
  3231. public:
  3232. using difference_type = std::ptrdiff_t;
  3233. using value_type = iteration_proxy_value;
  3234. using pointer = value_type * ;
  3235. using reference = value_type & ;
  3236. using iterator_category = std::input_iterator_tag;
  3237. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3238. private:
  3239. /// the iterator
  3240. IteratorType anchor;
  3241. /// an index for arrays (used to create key names)
  3242. std::size_t array_index = 0;
  3243. /// last stringified array index
  3244. mutable std::size_t array_index_last = 0;
  3245. /// a string representation of the array index
  3246. mutable string_type array_index_str = "0";
  3247. /// an empty string (to return a reference for primitive values)
  3248. const string_type empty_str = "";
  3249. public:
  3250. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  3251. /// dereference operator (needed for range-based for)
  3252. iteration_proxy_value& operator*()
  3253. {
  3254. return *this;
  3255. }
  3256. /// increment operator (needed for range-based for)
  3257. iteration_proxy_value& operator++()
  3258. {
  3259. ++anchor;
  3260. ++array_index;
  3261. return *this;
  3262. }
  3263. /// equality operator (needed for InputIterator)
  3264. bool operator==(const iteration_proxy_value& o) const
  3265. {
  3266. return anchor == o.anchor;
  3267. }
  3268. /// inequality operator (needed for range-based for)
  3269. bool operator!=(const iteration_proxy_value& o) const
  3270. {
  3271. return anchor != o.anchor;
  3272. }
  3273. /// return key of the iterator
  3274. const string_type& key() const
  3275. {
  3276. assert(anchor.m_object != nullptr);
  3277. switch (anchor.m_object->type())
  3278. {
  3279. // use integer array index as key
  3280. case value_t::array:
  3281. {
  3282. if (array_index != array_index_last)
  3283. {
  3284. int_to_string( array_index_str, array_index );
  3285. array_index_last = array_index;
  3286. }
  3287. return array_index_str;
  3288. }
  3289. // use key from the object
  3290. case value_t::object:
  3291. return anchor.key();
  3292. // use an empty key for all primitive types
  3293. default:
  3294. return empty_str;
  3295. }
  3296. }
  3297. /// return value of the iterator
  3298. typename IteratorType::reference value() const
  3299. {
  3300. return anchor.value();
  3301. }
  3302. };
  3303. /// proxy class for the items() function
  3304. template<typename IteratorType> class iteration_proxy
  3305. {
  3306. private:
  3307. /// the container to iterate
  3308. typename IteratorType::reference container;
  3309. public:
  3310. /// construct iteration proxy from a container
  3311. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3312. : container(cont) {}
  3313. /// return iterator begin (needed for range-based for)
  3314. iteration_proxy_value<IteratorType> begin() noexcept
  3315. {
  3316. return iteration_proxy_value<IteratorType>(container.begin());
  3317. }
  3318. /// return iterator end (needed for range-based for)
  3319. iteration_proxy_value<IteratorType> end() noexcept
  3320. {
  3321. return iteration_proxy_value<IteratorType>(container.end());
  3322. }
  3323. };
  3324. // Structured Bindings Support
  3325. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3326. // And see https://github.com/nlohmann/json/pull/1391
  3327. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  3328. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  3329. {
  3330. return i.key();
  3331. }
  3332. // Structured Bindings Support
  3333. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3334. // And see https://github.com/nlohmann/json/pull/1391
  3335. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3336. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3337. {
  3338. return i.value();
  3339. }
  3340. } // namespace detail
  3341. } // namespace nlohmann
  3342. // The Addition to the STD Namespace is required to add
  3343. // Structured Bindings Support to the iteration_proxy_value class
  3344. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3345. // And see https://github.com/nlohmann/json/pull/1391
  3346. namespace std
  3347. {
  3348. #if defined(__clang__)
  3349. // Fix: https://github.com/nlohmann/json/issues/1401
  3350. #pragma clang diagnostic push
  3351. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3352. #endif
  3353. template <typename IteratorType>
  3354. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3355. : public std::integral_constant<std::size_t, 2> {};
  3356. template <std::size_t N, typename IteratorType>
  3357. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3358. {
  3359. public:
  3360. using type = decltype(
  3361. get<N>(std::declval <
  3362. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3363. };
  3364. #if defined(__clang__)
  3365. #pragma clang diagnostic pop
  3366. #endif
  3367. } // namespace std
  3368. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3369. // #include <nlohmann/detail/meta/type_traits.hpp>
  3370. // #include <nlohmann/detail/value_t.hpp>
  3371. namespace nlohmann
  3372. {
  3373. namespace detail
  3374. {
  3375. //////////////////
  3376. // constructors //
  3377. //////////////////
  3378. template<value_t> struct external_constructor;
  3379. template<>
  3380. struct external_constructor<value_t::boolean>
  3381. {
  3382. template<typename BasicJsonType>
  3383. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  3384. {
  3385. j.m_type = value_t::boolean;
  3386. j.m_value = b;
  3387. j.assert_invariant();
  3388. }
  3389. };
  3390. template<>
  3391. struct external_constructor<value_t::string>
  3392. {
  3393. template<typename BasicJsonType>
  3394. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  3395. {
  3396. j.m_type = value_t::string;
  3397. j.m_value = s;
  3398. j.assert_invariant();
  3399. }
  3400. template<typename BasicJsonType>
  3401. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3402. {
  3403. j.m_type = value_t::string;
  3404. j.m_value = std::move(s);
  3405. j.assert_invariant();
  3406. }
  3407. template<typename BasicJsonType, typename CompatibleStringType,
  3408. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  3409. int> = 0>
  3410. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  3411. {
  3412. j.m_type = value_t::string;
  3413. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  3414. j.assert_invariant();
  3415. }
  3416. };
  3417. template<>
  3418. struct external_constructor<value_t::binary>
  3419. {
  3420. template<typename BasicJsonType>
  3421. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  3422. {
  3423. j.m_type = value_t::binary;
  3424. typename BasicJsonType::binary_t value{b};
  3425. j.m_value = value;
  3426. j.assert_invariant();
  3427. }
  3428. template<typename BasicJsonType>
  3429. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  3430. {
  3431. j.m_type = value_t::binary;
  3432. typename BasicJsonType::binary_t value{std::move(b)};
  3433. j.m_value = value;
  3434. j.assert_invariant();
  3435. }
  3436. };
  3437. template<>
  3438. struct external_constructor<value_t::number_float>
  3439. {
  3440. template<typename BasicJsonType>
  3441. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  3442. {
  3443. j.m_type = value_t::number_float;
  3444. j.m_value = val;
  3445. j.assert_invariant();
  3446. }
  3447. };
  3448. template<>
  3449. struct external_constructor<value_t::number_unsigned>
  3450. {
  3451. template<typename BasicJsonType>
  3452. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  3453. {
  3454. j.m_type = value_t::number_unsigned;
  3455. j.m_value = val;
  3456. j.assert_invariant();
  3457. }
  3458. };
  3459. template<>
  3460. struct external_constructor<value_t::number_integer>
  3461. {
  3462. template<typename BasicJsonType>
  3463. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3464. {
  3465. j.m_type = value_t::number_integer;
  3466. j.m_value = val;
  3467. j.assert_invariant();
  3468. }
  3469. };
  3470. template<>
  3471. struct external_constructor<value_t::array>
  3472. {
  3473. template<typename BasicJsonType>
  3474. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3475. {
  3476. j.m_type = value_t::array;
  3477. j.m_value = arr;
  3478. j.assert_invariant();
  3479. }
  3480. template<typename BasicJsonType>
  3481. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3482. {
  3483. j.m_type = value_t::array;
  3484. j.m_value = std::move(arr);
  3485. j.assert_invariant();
  3486. }
  3487. template<typename BasicJsonType, typename CompatibleArrayType,
  3488. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3489. int> = 0>
  3490. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3491. {
  3492. using std::begin;
  3493. using std::end;
  3494. j.m_type = value_t::array;
  3495. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3496. j.assert_invariant();
  3497. }
  3498. template<typename BasicJsonType>
  3499. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3500. {
  3501. j.m_type = value_t::array;
  3502. j.m_value = value_t::array;
  3503. j.m_value.array->reserve(arr.size());
  3504. for (const bool x : arr)
  3505. {
  3506. j.m_value.array->push_back(x);
  3507. }
  3508. j.assert_invariant();
  3509. }
  3510. template<typename BasicJsonType, typename T,
  3511. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3512. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3513. {
  3514. j.m_type = value_t::array;
  3515. j.m_value = value_t::array;
  3516. j.m_value.array->resize(arr.size());
  3517. if (arr.size() > 0)
  3518. {
  3519. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3520. }
  3521. j.assert_invariant();
  3522. }
  3523. };
  3524. template<>
  3525. struct external_constructor<value_t::object>
  3526. {
  3527. template<typename BasicJsonType>
  3528. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3529. {
  3530. j.m_type = value_t::object;
  3531. j.m_value = obj;
  3532. j.assert_invariant();
  3533. }
  3534. template<typename BasicJsonType>
  3535. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3536. {
  3537. j.m_type = value_t::object;
  3538. j.m_value = std::move(obj);
  3539. j.assert_invariant();
  3540. }
  3541. template<typename BasicJsonType, typename CompatibleObjectType,
  3542. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  3543. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3544. {
  3545. using std::begin;
  3546. using std::end;
  3547. j.m_type = value_t::object;
  3548. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3549. j.assert_invariant();
  3550. }
  3551. };
  3552. /////////////
  3553. // to_json //
  3554. /////////////
  3555. template<typename BasicJsonType, typename T,
  3556. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3557. void to_json(BasicJsonType& j, T b) noexcept
  3558. {
  3559. external_constructor<value_t::boolean>::construct(j, b);
  3560. }
  3561. template<typename BasicJsonType, typename CompatibleString,
  3562. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3563. void to_json(BasicJsonType& j, const CompatibleString& s)
  3564. {
  3565. external_constructor<value_t::string>::construct(j, s);
  3566. }
  3567. template<typename BasicJsonType>
  3568. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3569. {
  3570. external_constructor<value_t::string>::construct(j, std::move(s));
  3571. }
  3572. template<typename BasicJsonType, typename FloatType,
  3573. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3574. void to_json(BasicJsonType& j, FloatType val) noexcept
  3575. {
  3576. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3577. }
  3578. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3579. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3580. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3581. {
  3582. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3583. }
  3584. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3585. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3586. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3587. {
  3588. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3589. }
  3590. template<typename BasicJsonType, typename EnumType,
  3591. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3592. void to_json(BasicJsonType& j, EnumType e) noexcept
  3593. {
  3594. using underlying_type = typename std::underlying_type<EnumType>::type;
  3595. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3596. }
  3597. template<typename BasicJsonType>
  3598. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3599. {
  3600. external_constructor<value_t::array>::construct(j, e);
  3601. }
  3602. template <typename BasicJsonType, typename CompatibleArrayType,
  3603. enable_if_t<is_compatible_array_type<BasicJsonType,
  3604. CompatibleArrayType>::value and
  3605. not is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value and
  3606. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  3607. not std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value and
  3608. not is_basic_json<CompatibleArrayType>::value,
  3609. int> = 0>
  3610. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3611. {
  3612. external_constructor<value_t::array>::construct(j, arr);
  3613. }
  3614. template <typename BasicJsonType>
  3615. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  3616. {
  3617. external_constructor<value_t::binary>::construct(j, bin);
  3618. }
  3619. template<typename BasicJsonType, typename T,
  3620. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3621. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3622. {
  3623. external_constructor<value_t::array>::construct(j, std::move(arr));
  3624. }
  3625. template<typename BasicJsonType>
  3626. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3627. {
  3628. external_constructor<value_t::array>::construct(j, std::move(arr));
  3629. }
  3630. template<typename BasicJsonType, typename CompatibleObjectType,
  3631. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  3632. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3633. {
  3634. external_constructor<value_t::object>::construct(j, obj);
  3635. }
  3636. template<typename BasicJsonType>
  3637. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3638. {
  3639. external_constructor<value_t::object>::construct(j, std::move(obj));
  3640. }
  3641. template <
  3642. typename BasicJsonType, typename T, std::size_t N,
  3643. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  3644. const T(&)[N]>::value,
  3645. int> = 0 >
  3646. void to_json(BasicJsonType& j, const T(&arr)[N])
  3647. {
  3648. external_constructor<value_t::array>::construct(j, arr);
  3649. }
  3650. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  3651. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  3652. {
  3653. j = { p.first, p.second };
  3654. }
  3655. // for https://github.com/nlohmann/json/pull/1134
  3656. template < typename BasicJsonType, typename T,
  3657. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3658. void to_json(BasicJsonType& j, const T& b)
  3659. {
  3660. j = { {b.key(), b.value()} };
  3661. }
  3662. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3663. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3664. {
  3665. j = { std::get<Idx>(t)... };
  3666. }
  3667. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  3668. void to_json(BasicJsonType& j, const T& t)
  3669. {
  3670. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  3671. }
  3672. struct to_json_fn
  3673. {
  3674. template<typename BasicJsonType, typename T>
  3675. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3676. -> decltype(to_json(j, std::forward<T>(val)), void())
  3677. {
  3678. return to_json(j, std::forward<T>(val));
  3679. }
  3680. };
  3681. } // namespace detail
  3682. /// namespace to hold default `to_json` function
  3683. namespace
  3684. {
  3685. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3686. } // namespace
  3687. } // namespace nlohmann
  3688. namespace nlohmann
  3689. {
  3690. template<typename, typename>
  3691. struct adl_serializer
  3692. {
  3693. /*!
  3694. @brief convert a JSON value to any value type
  3695. This function is usually called by the `get()` function of the
  3696. @ref basic_json class (either explicit or via conversion operators).
  3697. @param[in] j JSON value to read from
  3698. @param[in,out] val value to write to
  3699. */
  3700. template<typename BasicJsonType, typename ValueType>
  3701. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3702. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3703. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3704. {
  3705. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3706. }
  3707. /*!
  3708. @brief convert any value type to a JSON value
  3709. This function is usually called by the constructors of the @ref basic_json
  3710. class.
  3711. @param[in,out] j JSON value to write to
  3712. @param[in] val value to read from
  3713. */
  3714. template <typename BasicJsonType, typename ValueType>
  3715. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3716. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3717. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3718. {
  3719. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3720. }
  3721. };
  3722. } // namespace nlohmann
  3723. // #include <nlohmann/byte_container_with_subtype.hpp>
  3724. #include <cstdint> // uint8_t
  3725. #include <tuple> // tie
  3726. #include <utility> // move
  3727. namespace nlohmann
  3728. {
  3729. /*!
  3730. @brief an internal type for a backed binary type
  3731. This type extends the template parameter @a BinaryType provided to `basic_json`
  3732. with a subtype used by BSON and MessagePack. This type exists so that the user
  3733. does not have to specify a type themselves with a specific naming scheme in
  3734. order to override the binary type.
  3735. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by
  3736. default)
  3737. @since version 3.8.0
  3738. */
  3739. template<typename BinaryType>
  3740. class byte_container_with_subtype : public BinaryType
  3741. {
  3742. public:
  3743. /// the type of the underlying container
  3744. using container_type = BinaryType;
  3745. byte_container_with_subtype() noexcept(noexcept(container_type()))
  3746. : container_type()
  3747. {}
  3748. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  3749. : container_type(b)
  3750. {}
  3751. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  3752. : container_type(std::move(b))
  3753. {}
  3754. byte_container_with_subtype(const container_type& b, std::uint8_t subtype) noexcept(noexcept(container_type(b)))
  3755. : container_type(b)
  3756. , m_subtype(subtype)
  3757. , m_has_subtype(true)
  3758. {}
  3759. byte_container_with_subtype(container_type&& b, std::uint8_t subtype) noexcept(noexcept(container_type(std::move(b))))
  3760. : container_type(std::move(b))
  3761. , m_subtype(subtype)
  3762. , m_has_subtype(true)
  3763. {}
  3764. bool operator==(const byte_container_with_subtype& rhs) const
  3765. {
  3766. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  3767. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  3768. }
  3769. bool operator!=(const byte_container_with_subtype& rhs) const
  3770. {
  3771. return !(rhs == *this);
  3772. }
  3773. /*!
  3774. @brief sets the binary subtype
  3775. Sets the binary subtype of the value, also flags a binary JSON value as
  3776. having a subtype, which has implications for serialization.
  3777. @complexity Constant.
  3778. @exceptionsafety No-throw guarantee: this member function never throws
  3779. exceptions.
  3780. @sa @ref subtype() -- return the binary subtype
  3781. @sa @ref clear_subtype() -- clears the binary subtype
  3782. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3783. subtype
  3784. @since version 3.8.0
  3785. */
  3786. void set_subtype(std::uint8_t subtype) noexcept
  3787. {
  3788. m_subtype = subtype;
  3789. m_has_subtype = true;
  3790. }
  3791. /*!
  3792. @brief return the binary subtype
  3793. Returns the numerical subtype of the value if it has a subtype. If it does
  3794. not have a subtype, this function will return size_t(-1) as a sentinel
  3795. value.
  3796. @return the numerical subtype of the binary value
  3797. @complexity Constant.
  3798. @exceptionsafety No-throw guarantee: this member function never throws
  3799. exceptions.
  3800. @sa @ref set_subtype() -- sets the binary subtype
  3801. @sa @ref clear_subtype() -- clears the binary subtype
  3802. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3803. subtype
  3804. @since version 3.8.0
  3805. */
  3806. constexpr std::uint8_t subtype() const noexcept
  3807. {
  3808. return m_subtype;
  3809. }
  3810. /*!
  3811. @brief return whether the value has a subtype
  3812. @return whether the value has a subtype
  3813. @complexity Constant.
  3814. @exceptionsafety No-throw guarantee: this member function never throws
  3815. exceptions.
  3816. @sa @ref subtype() -- return the binary subtype
  3817. @sa @ref set_subtype() -- sets the binary subtype
  3818. @sa @ref clear_subtype() -- clears the binary subtype
  3819. @since version 3.8.0
  3820. */
  3821. constexpr bool has_subtype() const noexcept
  3822. {
  3823. return m_has_subtype;
  3824. }
  3825. /*!
  3826. @brief clears the binary subtype
  3827. Clears the binary subtype and flags the value as not having a subtype, which
  3828. has implications for serialization; for instance MessagePack will prefer the
  3829. bin family over the ext family.
  3830. @complexity Constant.
  3831. @exceptionsafety No-throw guarantee: this member function never throws
  3832. exceptions.
  3833. @sa @ref subtype() -- return the binary subtype
  3834. @sa @ref set_subtype() -- sets the binary subtype
  3835. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3836. subtype
  3837. @since version 3.8.0
  3838. */
  3839. void clear_subtype() noexcept
  3840. {
  3841. m_subtype = 0;
  3842. m_has_subtype = false;
  3843. }
  3844. private:
  3845. std::uint8_t m_subtype = 0;
  3846. bool m_has_subtype = false;
  3847. };
  3848. } // namespace nlohmann
  3849. // #include <nlohmann/detail/boolean_operators.hpp>
  3850. // #include <nlohmann/detail/conversions/from_json.hpp>
  3851. // #include <nlohmann/detail/conversions/to_json.hpp>
  3852. // #include <nlohmann/detail/exceptions.hpp>
  3853. // #include <nlohmann/detail/input/binary_reader.hpp>
  3854. #include <algorithm> // generate_n
  3855. #include <array> // array
  3856. #include <cassert> // assert
  3857. #include <cmath> // ldexp
  3858. #include <cstddef> // size_t
  3859. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3860. #include <cstdio> // snprintf
  3861. #include <cstring> // memcpy
  3862. #include <iterator> // back_inserter
  3863. #include <limits> // numeric_limits
  3864. #include <string> // char_traits, string
  3865. #include <utility> // make_pair, move
  3866. // #include <nlohmann/detail/exceptions.hpp>
  3867. // #include <nlohmann/detail/input/input_adapters.hpp>
  3868. #include <array> // array
  3869. #include <cassert> // assert
  3870. #include <cstddef> // size_t
  3871. #include <cstdio> //FILE *
  3872. #include <cstring> // strlen
  3873. #include <istream> // istream
  3874. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3875. #include <memory> // shared_ptr, make_shared, addressof
  3876. #include <numeric> // accumulate
  3877. #include <string> // string, char_traits
  3878. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3879. #include <utility> // pair, declval
  3880. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3881. // #include <nlohmann/detail/macro_scope.hpp>
  3882. namespace nlohmann
  3883. {
  3884. namespace detail
  3885. {
  3886. /// the supported input formats
  3887. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3888. ////////////////////
  3889. // input adapters //
  3890. ////////////////////
  3891. /*!
  3892. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3893. buffer. This adapter is a very low level adapter.
  3894. */
  3895. class file_input_adapter
  3896. {
  3897. public:
  3898. JSON_HEDLEY_NON_NULL(2)
  3899. explicit file_input_adapter(std::FILE* f) noexcept
  3900. : m_file(f)
  3901. {}
  3902. // make class move-only
  3903. file_input_adapter(const file_input_adapter&) = delete;
  3904. file_input_adapter(file_input_adapter&&) = default;
  3905. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3906. file_input_adapter& operator=(file_input_adapter&&) = delete;
  3907. std::char_traits<char>::int_type get_character() noexcept
  3908. {
  3909. return std::fgetc(m_file);
  3910. }
  3911. private:
  3912. /// the file pointer to read from
  3913. std::FILE* m_file;
  3914. };
  3915. /*!
  3916. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3917. beginning of input. Does not support changing the underlying std::streambuf
  3918. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3919. subsequent use of standard std::istream operations to process any input
  3920. characters following those used in parsing the JSON input. Clears the
  3921. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3922. subsequent call for input from the std::istream.
  3923. */
  3924. class input_stream_adapter
  3925. {
  3926. public:
  3927. ~input_stream_adapter()
  3928. {
  3929. // clear stream flags; we use underlying streambuf I/O, do not
  3930. // maintain ifstream flags, except eof
  3931. if (is)
  3932. {
  3933. is->clear(is->rdstate() & std::ios::eofbit);
  3934. }
  3935. }
  3936. explicit input_stream_adapter(std::istream& i)
  3937. : is(&i), sb(i.rdbuf())
  3938. {}
  3939. // delete because of pointer members
  3940. input_stream_adapter(const input_stream_adapter&) = delete;
  3941. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3942. input_stream_adapter& operator=(input_stream_adapter&& rhs) = delete;
  3943. input_stream_adapter(input_stream_adapter&& rhs) : is(rhs.is), sb(rhs.sb)
  3944. {
  3945. rhs.is = nullptr;
  3946. rhs.sb = nullptr;
  3947. }
  3948. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3949. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3950. // end up as the same value, eg. 0xFFFFFFFF.
  3951. std::char_traits<char>::int_type get_character()
  3952. {
  3953. auto res = sb->sbumpc();
  3954. // set eof manually, as we don't use the istream interface.
  3955. if (res == EOF)
  3956. {
  3957. is->clear(is->rdstate() | std::ios::eofbit);
  3958. }
  3959. return res;
  3960. }
  3961. private:
  3962. /// the associated input stream
  3963. std::istream* is = nullptr;
  3964. std::streambuf* sb = nullptr;
  3965. };
  3966. /// input adapter for buffer input
  3967. class input_buffer_adapter
  3968. {
  3969. public:
  3970. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3971. : cursor(b), limit(b == nullptr ? nullptr : (b + l))
  3972. {}
  3973. // delete because of pointer members
  3974. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3975. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3976. input_buffer_adapter(input_buffer_adapter&&) = default;
  3977. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3978. std::char_traits<char>::int_type get_character() noexcept
  3979. {
  3980. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3981. {
  3982. assert(cursor != nullptr and limit != nullptr);
  3983. return std::char_traits<char>::to_int_type(*(cursor++));
  3984. }
  3985. return std::char_traits<char>::eof();
  3986. }
  3987. private:
  3988. /// pointer to the current character
  3989. const char* cursor;
  3990. /// pointer past the last character
  3991. const char* const limit;
  3992. };
  3993. template<typename WideStringType, size_t T>
  3994. struct wide_string_input_helper
  3995. {
  3996. // UTF-32
  3997. static void fill_buffer(const WideStringType& str,
  3998. size_t& current_wchar,
  3999. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4000. size_t& utf8_bytes_index,
  4001. size_t& utf8_bytes_filled)
  4002. {
  4003. utf8_bytes_index = 0;
  4004. if (current_wchar == str.size())
  4005. {
  4006. utf8_bytes[0] = std::char_traits<char>::eof();
  4007. utf8_bytes_filled = 1;
  4008. }
  4009. else
  4010. {
  4011. // get the current character
  4012. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  4013. // UTF-32 to UTF-8 encoding
  4014. if (wc < 0x80)
  4015. {
  4016. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4017. utf8_bytes_filled = 1;
  4018. }
  4019. else if (wc <= 0x7FF)
  4020. {
  4021. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  4022. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  4023. utf8_bytes_filled = 2;
  4024. }
  4025. else if (wc <= 0xFFFF)
  4026. {
  4027. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  4028. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  4029. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  4030. utf8_bytes_filled = 3;
  4031. }
  4032. else if (wc <= 0x10FFFF)
  4033. {
  4034. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  4035. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  4036. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  4037. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  4038. utf8_bytes_filled = 4;
  4039. }
  4040. else
  4041. {
  4042. // unknown character
  4043. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4044. utf8_bytes_filled = 1;
  4045. }
  4046. }
  4047. }
  4048. };
  4049. template<typename WideStringType>
  4050. struct wide_string_input_helper<WideStringType, 2>
  4051. {
  4052. // UTF-16
  4053. static void fill_buffer(const WideStringType& str,
  4054. size_t& current_wchar,
  4055. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4056. size_t& utf8_bytes_index,
  4057. size_t& utf8_bytes_filled)
  4058. {
  4059. utf8_bytes_index = 0;
  4060. if (current_wchar == str.size())
  4061. {
  4062. utf8_bytes[0] = std::char_traits<char>::eof();
  4063. utf8_bytes_filled = 1;
  4064. }
  4065. else
  4066. {
  4067. // get the current character
  4068. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  4069. // UTF-16 to UTF-8 encoding
  4070. if (wc < 0x80)
  4071. {
  4072. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4073. utf8_bytes_filled = 1;
  4074. }
  4075. else if (wc <= 0x7FF)
  4076. {
  4077. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  4078. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  4079. utf8_bytes_filled = 2;
  4080. }
  4081. else if (0xD800 > wc or wc >= 0xE000)
  4082. {
  4083. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  4084. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  4085. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  4086. utf8_bytes_filled = 3;
  4087. }
  4088. else
  4089. {
  4090. if (current_wchar < str.size())
  4091. {
  4092. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  4093. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4094. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4095. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4096. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4097. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4098. utf8_bytes_filled = 4;
  4099. }
  4100. else
  4101. {
  4102. // unknown character
  4103. ++current_wchar;
  4104. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4105. utf8_bytes_filled = 1;
  4106. }
  4107. }
  4108. }
  4109. }
  4110. };
  4111. template<typename WideStringType>
  4112. class wide_string_input_adapter
  4113. {
  4114. public:
  4115. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  4116. : str(w)
  4117. {}
  4118. std::char_traits<char>::int_type get_character() noexcept
  4119. {
  4120. // check if buffer needs to be filled
  4121. if (utf8_bytes_index == utf8_bytes_filled)
  4122. {
  4123. fill_buffer<sizeof(typename WideStringType::value_type)>();
  4124. assert(utf8_bytes_filled > 0);
  4125. assert(utf8_bytes_index == 0);
  4126. }
  4127. // use buffer
  4128. assert(utf8_bytes_filled > 0);
  4129. assert(utf8_bytes_index < utf8_bytes_filled);
  4130. return utf8_bytes[utf8_bytes_index++];
  4131. }
  4132. private:
  4133. template<size_t T>
  4134. void fill_buffer()
  4135. {
  4136. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  4137. }
  4138. /// the wstring to process
  4139. const WideStringType& str;
  4140. /// index of the current wchar in str
  4141. std::size_t current_wchar = 0;
  4142. /// a buffer for UTF-8 bytes
  4143. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  4144. /// index to the utf8_codes array for the next valid byte
  4145. std::size_t utf8_bytes_index = 0;
  4146. /// number of valid bytes in the utf8_codes array
  4147. std::size_t utf8_bytes_filled = 0;
  4148. };
  4149. inline file_input_adapter input_adapter(std::FILE* file)
  4150. {
  4151. return file_input_adapter(file);
  4152. }
  4153. inline input_stream_adapter input_adapter(std::istream& stream)
  4154. {
  4155. return input_stream_adapter(stream);
  4156. }
  4157. inline input_stream_adapter input_adapter(std::istream&& stream)
  4158. {
  4159. return input_stream_adapter(stream);
  4160. }
  4161. template<typename CharT, typename SizeT,
  4162. typename std::enable_if<
  4163. std::is_pointer<CharT>::value and
  4164. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4165. not std::is_same<SizeT, bool>::value and
  4166. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4167. int>::type = 0>
  4168. input_buffer_adapter input_adapter(CharT b, SizeT l)
  4169. {
  4170. return input_buffer_adapter(reinterpret_cast<const char*>(b), l);
  4171. }
  4172. template<typename CharT,
  4173. typename std::enable_if<
  4174. std::is_pointer<CharT>::value and
  4175. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4176. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4177. int>::type = 0>
  4178. input_buffer_adapter input_adapter(CharT b)
  4179. {
  4180. return input_adapter(reinterpret_cast<const char*>(b),
  4181. std::strlen(reinterpret_cast<const char*>(b)));
  4182. }
  4183. template<class IteratorType,
  4184. typename std::enable_if<
  4185. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4186. int>::type = 0>
  4187. input_buffer_adapter input_adapter(IteratorType first, IteratorType last)
  4188. {
  4189. #ifndef NDEBUG
  4190. // assertion to check that the iterator range is indeed contiguous,
  4191. // see https://stackoverflow.com/a/35008842/266378 for more discussion
  4192. const auto is_contiguous = std::accumulate(
  4193. first, last, std::pair<bool, int>(true, 0),
  4194. [&first](std::pair<bool, int> res, decltype(*first) val)
  4195. {
  4196. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  4197. return res;
  4198. }).first;
  4199. assert(is_contiguous);
  4200. #endif
  4201. // assertion to check that each element is 1 byte long
  4202. static_assert(
  4203. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  4204. "each element in the iterator range must have the size of 1 byte");
  4205. const auto len = static_cast<size_t>(std::distance(first, last));
  4206. if (JSON_HEDLEY_LIKELY(len > 0))
  4207. {
  4208. // there is at least one element: use the address of first
  4209. return input_buffer_adapter(reinterpret_cast<const char*>(&(*first)), len);
  4210. }
  4211. else
  4212. {
  4213. // the address of first cannot be used: use nullptr
  4214. return input_buffer_adapter(nullptr, len);
  4215. }
  4216. }
  4217. inline wide_string_input_adapter<std::wstring> input_adapter(const std::wstring& ws)
  4218. {
  4219. return wide_string_input_adapter<std::wstring>(ws);
  4220. }
  4221. inline wide_string_input_adapter<std::u16string> input_adapter(const std::u16string& ws)
  4222. {
  4223. return wide_string_input_adapter<std::u16string>(ws);
  4224. }
  4225. inline wide_string_input_adapter<std::u32string> input_adapter(const std::u32string& ws)
  4226. {
  4227. return wide_string_input_adapter<std::u32string>(ws);
  4228. }
  4229. template<class ContiguousContainer, typename
  4230. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  4231. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  4232. int>::type = 0>
  4233. input_buffer_adapter input_adapter(const ContiguousContainer& c)
  4234. {
  4235. return input_adapter(std::begin(c), std::end(c));
  4236. }
  4237. template<class T, std::size_t N>
  4238. input_buffer_adapter input_adapter(T (&array)[N])
  4239. {
  4240. return input_adapter(std::begin(array), std::end(array));
  4241. }
  4242. // This class only handles inputs of input_buffer_adapter type.
  4243. // It's required so that expressions like {ptr, len} can be implicitely casted
  4244. // to the correct adapter.
  4245. class span_input_adapter
  4246. {
  4247. public:
  4248. template<typename CharT,
  4249. typename std::enable_if<
  4250. std::is_pointer<CharT>::value and
  4251. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4252. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4253. int>::type = 0>
  4254. span_input_adapter(CharT b, std::size_t l)
  4255. : ia(reinterpret_cast<const char*>(b), l) {}
  4256. template<typename CharT,
  4257. typename std::enable_if<
  4258. std::is_pointer<CharT>::value and
  4259. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4260. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4261. int>::type = 0>
  4262. span_input_adapter(CharT b)
  4263. : span_input_adapter(reinterpret_cast<const char*>(b),
  4264. std::strlen(reinterpret_cast<const char*>(b))) {}
  4265. template<class IteratorType,
  4266. typename std::enable_if<
  4267. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4268. int>::type = 0>
  4269. span_input_adapter(IteratorType first, IteratorType last)
  4270. : ia(input_adapter(first, last)) {}
  4271. template<class T, std::size_t N>
  4272. span_input_adapter(T (&array)[N])
  4273. : span_input_adapter(std::begin(array), std::end(array)) {}
  4274. /// input adapter for contiguous container
  4275. template<class ContiguousContainer, typename
  4276. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  4277. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  4278. int>::type = 0>
  4279. span_input_adapter(const ContiguousContainer& c)
  4280. : span_input_adapter(std::begin(c), std::end(c)) {}
  4281. input_buffer_adapter&& get()
  4282. {
  4283. return std::move(ia);
  4284. }
  4285. private:
  4286. input_buffer_adapter ia;
  4287. };
  4288. } // namespace detail
  4289. } // namespace nlohmann
  4290. // #include <nlohmann/detail/input/json_sax.hpp>
  4291. #include <cassert> // assert
  4292. #include <cstddef>
  4293. #include <string> // string
  4294. #include <utility> // move
  4295. #include <vector> // vector
  4296. // #include <nlohmann/detail/exceptions.hpp>
  4297. // #include <nlohmann/detail/macro_scope.hpp>
  4298. namespace nlohmann
  4299. {
  4300. /*!
  4301. @brief SAX interface
  4302. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  4303. Each function is called in different situations while the input is parsed. The
  4304. boolean return value informs the parser whether to continue processing the
  4305. input.
  4306. */
  4307. template<typename BasicJsonType>
  4308. struct json_sax
  4309. {
  4310. using number_integer_t = typename BasicJsonType::number_integer_t;
  4311. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4312. using number_float_t = typename BasicJsonType::number_float_t;
  4313. using string_t = typename BasicJsonType::string_t;
  4314. using binary_t = typename BasicJsonType::binary_t;
  4315. /*!
  4316. @brief a null value was read
  4317. @return whether parsing should proceed
  4318. */
  4319. virtual bool null() = 0;
  4320. /*!
  4321. @brief a boolean value was read
  4322. @param[in] val boolean value
  4323. @return whether parsing should proceed
  4324. */
  4325. virtual bool boolean(bool val) = 0;
  4326. /*!
  4327. @brief an integer number was read
  4328. @param[in] val integer value
  4329. @return whether parsing should proceed
  4330. */
  4331. virtual bool number_integer(number_integer_t val) = 0;
  4332. /*!
  4333. @brief an unsigned integer number was read
  4334. @param[in] val unsigned integer value
  4335. @return whether parsing should proceed
  4336. */
  4337. virtual bool number_unsigned(number_unsigned_t val) = 0;
  4338. /*!
  4339. @brief an floating-point number was read
  4340. @param[in] val floating-point value
  4341. @param[in] s raw token value
  4342. @return whether parsing should proceed
  4343. */
  4344. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  4345. /*!
  4346. @brief a string was read
  4347. @param[in] val string value
  4348. @return whether parsing should proceed
  4349. @note It is safe to move the passed string.
  4350. */
  4351. virtual bool string(string_t& val) = 0;
  4352. /*!
  4353. @brief a binary string was read
  4354. @param[in] val binary value
  4355. @return whether parsing should proceed
  4356. @note It is safe to move the passed binary.
  4357. */
  4358. virtual bool binary(binary_t& val) = 0;
  4359. /*!
  4360. @brief the beginning of an object was read
  4361. @param[in] elements number of object elements or -1 if unknown
  4362. @return whether parsing should proceed
  4363. @note binary formats may report the number of elements
  4364. */
  4365. virtual bool start_object(std::size_t elements) = 0;
  4366. /*!
  4367. @brief an object key was read
  4368. @param[in] val object key
  4369. @return whether parsing should proceed
  4370. @note It is safe to move the passed string.
  4371. */
  4372. virtual bool key(string_t& val) = 0;
  4373. /*!
  4374. @brief the end of an object was read
  4375. @return whether parsing should proceed
  4376. */
  4377. virtual bool end_object() = 0;
  4378. /*!
  4379. @brief the beginning of an array was read
  4380. @param[in] elements number of array elements or -1 if unknown
  4381. @return whether parsing should proceed
  4382. @note binary formats may report the number of elements
  4383. */
  4384. virtual bool start_array(std::size_t elements) = 0;
  4385. /*!
  4386. @brief the end of an array was read
  4387. @return whether parsing should proceed
  4388. */
  4389. virtual bool end_array() = 0;
  4390. /*!
  4391. @brief a parse error occurred
  4392. @param[in] position the position in the input where the error occurs
  4393. @param[in] last_token the last read token
  4394. @param[in] ex an exception object describing the error
  4395. @return whether parsing should proceed (must return false)
  4396. */
  4397. virtual bool parse_error(std::size_t position,
  4398. const std::string& last_token,
  4399. const detail::exception& ex) = 0;
  4400. virtual ~json_sax() = default;
  4401. };
  4402. namespace detail
  4403. {
  4404. /*!
  4405. @brief SAX implementation to create a JSON value from SAX events
  4406. This class implements the @ref json_sax interface and processes the SAX events
  4407. to create a JSON value which makes it basically a DOM parser. The structure or
  4408. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  4409. a pointer to the respective array or object for each recursion depth.
  4410. After successful parsing, the value that is passed by reference to the
  4411. constructor contains the parsed value.
  4412. @tparam BasicJsonType the JSON type
  4413. */
  4414. template<typename BasicJsonType>
  4415. class json_sax_dom_parser
  4416. {
  4417. public:
  4418. using number_integer_t = typename BasicJsonType::number_integer_t;
  4419. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4420. using number_float_t = typename BasicJsonType::number_float_t;
  4421. using string_t = typename BasicJsonType::string_t;
  4422. using binary_t = typename BasicJsonType::binary_t;
  4423. /*!
  4424. @param[in, out] r reference to a JSON value that is manipulated while
  4425. parsing
  4426. @param[in] allow_exceptions_ whether parse errors yield exceptions
  4427. */
  4428. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  4429. : root(r), allow_exceptions(allow_exceptions_)
  4430. {}
  4431. // make class move-only
  4432. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  4433. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  4434. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  4435. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  4436. ~json_sax_dom_parser() = default;
  4437. bool null()
  4438. {
  4439. handle_value(nullptr);
  4440. return true;
  4441. }
  4442. bool boolean(bool val)
  4443. {
  4444. handle_value(val);
  4445. return true;
  4446. }
  4447. bool number_integer(number_integer_t val)
  4448. {
  4449. handle_value(val);
  4450. return true;
  4451. }
  4452. bool number_unsigned(number_unsigned_t val)
  4453. {
  4454. handle_value(val);
  4455. return true;
  4456. }
  4457. bool number_float(number_float_t val, const string_t& /*unused*/)
  4458. {
  4459. handle_value(val);
  4460. return true;
  4461. }
  4462. bool string(string_t& val)
  4463. {
  4464. handle_value(val);
  4465. return true;
  4466. }
  4467. bool binary(binary_t& val)
  4468. {
  4469. handle_value(std::move(val));
  4470. return true;
  4471. }
  4472. bool start_object(std::size_t len)
  4473. {
  4474. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  4475. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4476. {
  4477. JSON_THROW(out_of_range::create(408,
  4478. "excessive object size: " + std::to_string(len)));
  4479. }
  4480. return true;
  4481. }
  4482. bool key(string_t& val)
  4483. {
  4484. // add null at given key and store the reference for later
  4485. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  4486. return true;
  4487. }
  4488. bool end_object()
  4489. {
  4490. ref_stack.pop_back();
  4491. return true;
  4492. }
  4493. bool start_array(std::size_t len)
  4494. {
  4495. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  4496. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4497. {
  4498. JSON_THROW(out_of_range::create(408,
  4499. "excessive array size: " + std::to_string(len)));
  4500. }
  4501. return true;
  4502. }
  4503. bool end_array()
  4504. {
  4505. ref_stack.pop_back();
  4506. return true;
  4507. }
  4508. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4509. const detail::exception& ex)
  4510. {
  4511. errored = true;
  4512. if (allow_exceptions)
  4513. {
  4514. // determine the proper exception type from the id
  4515. switch ((ex.id / 100) % 100)
  4516. {
  4517. case 1:
  4518. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4519. case 4:
  4520. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4521. // LCOV_EXCL_START
  4522. case 2:
  4523. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4524. case 3:
  4525. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4526. case 5:
  4527. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4528. default:
  4529. assert(false);
  4530. // LCOV_EXCL_STOP
  4531. }
  4532. }
  4533. return false;
  4534. }
  4535. constexpr bool is_errored() const
  4536. {
  4537. return errored;
  4538. }
  4539. private:
  4540. /*!
  4541. @invariant If the ref stack is empty, then the passed value will be the new
  4542. root.
  4543. @invariant If the ref stack contains a value, then it is an array or an
  4544. object to which we can add elements
  4545. */
  4546. template<typename Value>
  4547. JSON_HEDLEY_RETURNS_NON_NULL
  4548. BasicJsonType* handle_value(Value&& v)
  4549. {
  4550. if (ref_stack.empty())
  4551. {
  4552. root = BasicJsonType(std::forward<Value>(v));
  4553. return &root;
  4554. }
  4555. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4556. if (ref_stack.back()->is_array())
  4557. {
  4558. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4559. return &(ref_stack.back()->m_value.array->back());
  4560. }
  4561. assert(ref_stack.back()->is_object());
  4562. assert(object_element);
  4563. *object_element = BasicJsonType(std::forward<Value>(v));
  4564. return object_element;
  4565. }
  4566. /// the parsed JSON value
  4567. BasicJsonType& root;
  4568. /// stack to model hierarchy of values
  4569. std::vector<BasicJsonType*> ref_stack {};
  4570. /// helper to hold the reference for the next object element
  4571. BasicJsonType* object_element = nullptr;
  4572. /// whether a syntax error occurred
  4573. bool errored = false;
  4574. /// whether to throw exceptions in case of errors
  4575. const bool allow_exceptions = true;
  4576. };
  4577. template<typename BasicJsonType>
  4578. class json_sax_dom_callback_parser
  4579. {
  4580. public:
  4581. using number_integer_t = typename BasicJsonType::number_integer_t;
  4582. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4583. using number_float_t = typename BasicJsonType::number_float_t;
  4584. using string_t = typename BasicJsonType::string_t;
  4585. using binary_t = typename BasicJsonType::binary_t;
  4586. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4587. using parse_event_t = typename BasicJsonType::parse_event_t;
  4588. json_sax_dom_callback_parser(BasicJsonType& r,
  4589. const parser_callback_t cb,
  4590. const bool allow_exceptions_ = true)
  4591. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4592. {
  4593. keep_stack.push_back(true);
  4594. }
  4595. // make class move-only
  4596. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4597. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4598. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4599. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4600. ~json_sax_dom_callback_parser() = default;
  4601. bool null()
  4602. {
  4603. handle_value(nullptr);
  4604. return true;
  4605. }
  4606. bool boolean(bool val)
  4607. {
  4608. handle_value(val);
  4609. return true;
  4610. }
  4611. bool number_integer(number_integer_t val)
  4612. {
  4613. handle_value(val);
  4614. return true;
  4615. }
  4616. bool number_unsigned(number_unsigned_t val)
  4617. {
  4618. handle_value(val);
  4619. return true;
  4620. }
  4621. bool number_float(number_float_t val, const string_t& /*unused*/)
  4622. {
  4623. handle_value(val);
  4624. return true;
  4625. }
  4626. bool string(string_t& val)
  4627. {
  4628. handle_value(val);
  4629. return true;
  4630. }
  4631. bool binary(binary_t& val)
  4632. {
  4633. handle_value(std::move(val));
  4634. return true;
  4635. }
  4636. bool start_object(std::size_t len)
  4637. {
  4638. // check callback for object start
  4639. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4640. keep_stack.push_back(keep);
  4641. auto val = handle_value(BasicJsonType::value_t::object, true);
  4642. ref_stack.push_back(val.second);
  4643. // check object limit
  4644. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4645. {
  4646. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4647. }
  4648. return true;
  4649. }
  4650. bool key(string_t& val)
  4651. {
  4652. BasicJsonType k = BasicJsonType(val);
  4653. // check callback for key
  4654. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4655. key_keep_stack.push_back(keep);
  4656. // add discarded value at given key and store the reference for later
  4657. if (keep and ref_stack.back())
  4658. {
  4659. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4660. }
  4661. return true;
  4662. }
  4663. bool end_object()
  4664. {
  4665. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4666. {
  4667. // discard object
  4668. *ref_stack.back() = discarded;
  4669. }
  4670. assert(not ref_stack.empty());
  4671. assert(not keep_stack.empty());
  4672. ref_stack.pop_back();
  4673. keep_stack.pop_back();
  4674. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_structured())
  4675. {
  4676. // remove discarded value
  4677. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4678. {
  4679. if (it->is_discarded())
  4680. {
  4681. ref_stack.back()->erase(it);
  4682. break;
  4683. }
  4684. }
  4685. }
  4686. return true;
  4687. }
  4688. bool start_array(std::size_t len)
  4689. {
  4690. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4691. keep_stack.push_back(keep);
  4692. auto val = handle_value(BasicJsonType::value_t::array, true);
  4693. ref_stack.push_back(val.second);
  4694. // check array limit
  4695. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4696. {
  4697. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4698. }
  4699. return true;
  4700. }
  4701. bool end_array()
  4702. {
  4703. bool keep = true;
  4704. if (ref_stack.back())
  4705. {
  4706. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4707. if (not keep)
  4708. {
  4709. // discard array
  4710. *ref_stack.back() = discarded;
  4711. }
  4712. }
  4713. assert(not ref_stack.empty());
  4714. assert(not keep_stack.empty());
  4715. ref_stack.pop_back();
  4716. keep_stack.pop_back();
  4717. // remove discarded value
  4718. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4719. {
  4720. ref_stack.back()->m_value.array->pop_back();
  4721. }
  4722. return true;
  4723. }
  4724. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4725. const detail::exception& ex)
  4726. {
  4727. errored = true;
  4728. if (allow_exceptions)
  4729. {
  4730. // determine the proper exception type from the id
  4731. switch ((ex.id / 100) % 100)
  4732. {
  4733. case 1:
  4734. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4735. case 4:
  4736. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4737. // LCOV_EXCL_START
  4738. case 2:
  4739. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4740. case 3:
  4741. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4742. case 5:
  4743. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4744. default:
  4745. assert(false);
  4746. // LCOV_EXCL_STOP
  4747. }
  4748. }
  4749. return false;
  4750. }
  4751. constexpr bool is_errored() const
  4752. {
  4753. return errored;
  4754. }
  4755. private:
  4756. /*!
  4757. @param[in] v value to add to the JSON value we build during parsing
  4758. @param[in] skip_callback whether we should skip calling the callback
  4759. function; this is required after start_array() and
  4760. start_object() SAX events, because otherwise we would call the
  4761. callback function with an empty array or object, respectively.
  4762. @invariant If the ref stack is empty, then the passed value will be the new
  4763. root.
  4764. @invariant If the ref stack contains a value, then it is an array or an
  4765. object to which we can add elements
  4766. @return pair of boolean (whether value should be kept) and pointer (to the
  4767. passed value in the ref_stack hierarchy; nullptr if not kept)
  4768. */
  4769. template<typename Value>
  4770. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4771. {
  4772. assert(not keep_stack.empty());
  4773. // do not handle this value if we know it would be added to a discarded
  4774. // container
  4775. if (not keep_stack.back())
  4776. {
  4777. return {false, nullptr};
  4778. }
  4779. // create value
  4780. auto value = BasicJsonType(std::forward<Value>(v));
  4781. // check callback
  4782. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4783. // do not handle this value if we just learnt it shall be discarded
  4784. if (not keep)
  4785. {
  4786. return {false, nullptr};
  4787. }
  4788. if (ref_stack.empty())
  4789. {
  4790. root = std::move(value);
  4791. return {true, &root};
  4792. }
  4793. // skip this value if we already decided to skip the parent
  4794. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4795. if (not ref_stack.back())
  4796. {
  4797. return {false, nullptr};
  4798. }
  4799. // we now only expect arrays and objects
  4800. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4801. // array
  4802. if (ref_stack.back()->is_array())
  4803. {
  4804. ref_stack.back()->m_value.array->push_back(std::move(value));
  4805. return {true, &(ref_stack.back()->m_value.array->back())};
  4806. }
  4807. // object
  4808. assert(ref_stack.back()->is_object());
  4809. // check if we should store an element for the current key
  4810. assert(not key_keep_stack.empty());
  4811. const bool store_element = key_keep_stack.back();
  4812. key_keep_stack.pop_back();
  4813. if (not store_element)
  4814. {
  4815. return {false, nullptr};
  4816. }
  4817. assert(object_element);
  4818. *object_element = std::move(value);
  4819. return {true, object_element};
  4820. }
  4821. /// the parsed JSON value
  4822. BasicJsonType& root;
  4823. /// stack to model hierarchy of values
  4824. std::vector<BasicJsonType*> ref_stack {};
  4825. /// stack to manage which values to keep
  4826. std::vector<bool> keep_stack {};
  4827. /// stack to manage which object keys to keep
  4828. std::vector<bool> key_keep_stack {};
  4829. /// helper to hold the reference for the next object element
  4830. BasicJsonType* object_element = nullptr;
  4831. /// whether a syntax error occurred
  4832. bool errored = false;
  4833. /// callback function
  4834. const parser_callback_t callback = nullptr;
  4835. /// whether to throw exceptions in case of errors
  4836. const bool allow_exceptions = true;
  4837. /// a discarded value for the callback
  4838. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4839. };
  4840. template<typename BasicJsonType>
  4841. class json_sax_acceptor
  4842. {
  4843. public:
  4844. using number_integer_t = typename BasicJsonType::number_integer_t;
  4845. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4846. using number_float_t = typename BasicJsonType::number_float_t;
  4847. using string_t = typename BasicJsonType::string_t;
  4848. using binary_t = typename BasicJsonType::binary_t;
  4849. bool null()
  4850. {
  4851. return true;
  4852. }
  4853. bool boolean(bool /*unused*/)
  4854. {
  4855. return true;
  4856. }
  4857. bool number_integer(number_integer_t /*unused*/)
  4858. {
  4859. return true;
  4860. }
  4861. bool number_unsigned(number_unsigned_t /*unused*/)
  4862. {
  4863. return true;
  4864. }
  4865. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4866. {
  4867. return true;
  4868. }
  4869. bool string(string_t& /*unused*/)
  4870. {
  4871. return true;
  4872. }
  4873. bool binary(binary_t& /*unused*/)
  4874. {
  4875. return true;
  4876. }
  4877. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4878. {
  4879. return true;
  4880. }
  4881. bool key(string_t& /*unused*/)
  4882. {
  4883. return true;
  4884. }
  4885. bool end_object()
  4886. {
  4887. return true;
  4888. }
  4889. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4890. {
  4891. return true;
  4892. }
  4893. bool end_array()
  4894. {
  4895. return true;
  4896. }
  4897. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4898. {
  4899. return false;
  4900. }
  4901. };
  4902. } // namespace detail
  4903. } // namespace nlohmann
  4904. // #include <nlohmann/detail/macro_scope.hpp>
  4905. // #include <nlohmann/detail/meta/is_sax.hpp>
  4906. #include <cstdint> // size_t
  4907. #include <utility> // declval
  4908. #include <string> // string
  4909. // #include <nlohmann/detail/meta/detected.hpp>
  4910. // #include <nlohmann/detail/meta/type_traits.hpp>
  4911. namespace nlohmann
  4912. {
  4913. namespace detail
  4914. {
  4915. template <typename T>
  4916. using null_function_t = decltype(std::declval<T&>().null());
  4917. template <typename T>
  4918. using boolean_function_t =
  4919. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4920. template <typename T, typename Integer>
  4921. using number_integer_function_t =
  4922. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4923. template <typename T, typename Unsigned>
  4924. using number_unsigned_function_t =
  4925. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4926. template <typename T, typename Float, typename String>
  4927. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4928. std::declval<Float>(), std::declval<const String&>()));
  4929. template <typename T, typename String>
  4930. using string_function_t =
  4931. decltype(std::declval<T&>().string(std::declval<String&>()));
  4932. template <typename T>
  4933. using start_object_function_t =
  4934. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4935. template <typename T, typename String>
  4936. using key_function_t =
  4937. decltype(std::declval<T&>().key(std::declval<String&>()));
  4938. template <typename T>
  4939. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4940. template <typename T>
  4941. using start_array_function_t =
  4942. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4943. template <typename T>
  4944. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4945. template <typename T, typename Exception>
  4946. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4947. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4948. std::declval<const Exception&>()));
  4949. template <typename SAX, typename BasicJsonType>
  4950. struct is_sax
  4951. {
  4952. private:
  4953. static_assert(is_basic_json<BasicJsonType>::value,
  4954. "BasicJsonType must be of type basic_json<...>");
  4955. using number_integer_t = typename BasicJsonType::number_integer_t;
  4956. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4957. using number_float_t = typename BasicJsonType::number_float_t;
  4958. using string_t = typename BasicJsonType::string_t;
  4959. using exception_t = typename BasicJsonType::exception;
  4960. public:
  4961. static constexpr bool value =
  4962. is_detected_exact<bool, null_function_t, SAX>::value &&
  4963. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4964. is_detected_exact<bool, number_integer_function_t, SAX,
  4965. number_integer_t>::value &&
  4966. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4967. number_unsigned_t>::value &&
  4968. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4969. string_t>::value &&
  4970. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4971. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4972. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4973. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4974. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4975. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4976. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4977. };
  4978. template <typename SAX, typename BasicJsonType>
  4979. struct is_sax_static_asserts
  4980. {
  4981. private:
  4982. static_assert(is_basic_json<BasicJsonType>::value,
  4983. "BasicJsonType must be of type basic_json<...>");
  4984. using number_integer_t = typename BasicJsonType::number_integer_t;
  4985. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4986. using number_float_t = typename BasicJsonType::number_float_t;
  4987. using string_t = typename BasicJsonType::string_t;
  4988. using exception_t = typename BasicJsonType::exception;
  4989. public:
  4990. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4991. "Missing/invalid function: bool null()");
  4992. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4993. "Missing/invalid function: bool boolean(bool)");
  4994. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4995. "Missing/invalid function: bool boolean(bool)");
  4996. static_assert(
  4997. is_detected_exact<bool, number_integer_function_t, SAX,
  4998. number_integer_t>::value,
  4999. "Missing/invalid function: bool number_integer(number_integer_t)");
  5000. static_assert(
  5001. is_detected_exact<bool, number_unsigned_function_t, SAX,
  5002. number_unsigned_t>::value,
  5003. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  5004. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  5005. number_float_t, string_t>::value,
  5006. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  5007. static_assert(
  5008. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  5009. "Missing/invalid function: bool string(string_t&)");
  5010. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  5011. "Missing/invalid function: bool start_object(std::size_t)");
  5012. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  5013. "Missing/invalid function: bool key(string_t&)");
  5014. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  5015. "Missing/invalid function: bool end_object()");
  5016. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  5017. "Missing/invalid function: bool start_array(std::size_t)");
  5018. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  5019. "Missing/invalid function: bool end_array()");
  5020. static_assert(
  5021. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  5022. "Missing/invalid function: bool parse_error(std::size_t, const "
  5023. "std::string&, const exception&)");
  5024. };
  5025. } // namespace detail
  5026. } // namespace nlohmann
  5027. // #include <nlohmann/detail/value_t.hpp>
  5028. namespace nlohmann
  5029. {
  5030. namespace detail
  5031. {
  5032. /*!
  5033. @brief determine system byte order
  5034. @return true if and only if system's byte order is little endian
  5035. @note from https://stackoverflow.com/a/1001328/266378
  5036. */
  5037. static inline bool little_endianess(int num = 1) noexcept
  5038. {
  5039. return *reinterpret_cast<char*>(&num) == 1;
  5040. }
  5041. ///////////////////
  5042. // binary reader //
  5043. ///////////////////
  5044. /*!
  5045. @brief deserialization of CBOR, MessagePack, and UBJSON values
  5046. */
  5047. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  5048. class binary_reader
  5049. {
  5050. using number_integer_t = typename BasicJsonType::number_integer_t;
  5051. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5052. using number_float_t = typename BasicJsonType::number_float_t;
  5053. using string_t = typename BasicJsonType::string_t;
  5054. using binary_t = typename BasicJsonType::binary_t;
  5055. using json_sax_t = SAX;
  5056. public:
  5057. /*!
  5058. @brief create a binary reader
  5059. @param[in] adapter input adapter to read from
  5060. */
  5061. explicit binary_reader(InputAdapterType&& adapter) : ia(std::move(adapter))
  5062. {
  5063. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  5064. }
  5065. // make class move-only
  5066. binary_reader(const binary_reader&) = delete;
  5067. binary_reader(binary_reader&&) = default;
  5068. binary_reader& operator=(const binary_reader&) = delete;
  5069. binary_reader& operator=(binary_reader&&) = default;
  5070. ~binary_reader() = default;
  5071. /*!
  5072. @param[in] format the binary format to parse
  5073. @param[in] sax_ a SAX event processor
  5074. @param[in] strict whether to expect the input to be consumed completed
  5075. @return
  5076. */
  5077. JSON_HEDLEY_NON_NULL(3)
  5078. bool sax_parse(const input_format_t format,
  5079. json_sax_t* sax_,
  5080. const bool strict = true)
  5081. {
  5082. sax = sax_;
  5083. bool result = false;
  5084. switch (format)
  5085. {
  5086. case input_format_t::bson:
  5087. result = parse_bson_internal();
  5088. break;
  5089. case input_format_t::cbor:
  5090. result = parse_cbor_internal();
  5091. break;
  5092. case input_format_t::msgpack:
  5093. result = parse_msgpack_internal();
  5094. break;
  5095. case input_format_t::ubjson:
  5096. result = parse_ubjson_internal();
  5097. break;
  5098. default: // LCOV_EXCL_LINE
  5099. assert(false); // LCOV_EXCL_LINE
  5100. }
  5101. // strict mode: next byte must be EOF
  5102. if (result and strict)
  5103. {
  5104. if (format == input_format_t::ubjson)
  5105. {
  5106. get_ignore_noop();
  5107. }
  5108. else
  5109. {
  5110. get();
  5111. }
  5112. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  5113. {
  5114. return sax->parse_error(chars_read, get_token_string(),
  5115. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  5116. }
  5117. }
  5118. return result;
  5119. }
  5120. private:
  5121. //////////
  5122. // BSON //
  5123. //////////
  5124. /*!
  5125. @brief Reads in a BSON-object and passes it to the SAX-parser.
  5126. @return whether a valid BSON-value was passed to the SAX parser
  5127. */
  5128. bool parse_bson_internal()
  5129. {
  5130. std::int32_t document_size;
  5131. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5132. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  5133. {
  5134. return false;
  5135. }
  5136. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  5137. {
  5138. return false;
  5139. }
  5140. return sax->end_object();
  5141. }
  5142. /*!
  5143. @brief Parses a C-style string from the BSON input.
  5144. @param[in, out] result A reference to the string variable where the read
  5145. string is to be stored.
  5146. @return `true` if the \x00-byte indicating the end of the string was
  5147. encountered before the EOF; false` indicates an unexpected EOF.
  5148. */
  5149. bool get_bson_cstr(string_t& result)
  5150. {
  5151. auto out = std::back_inserter(result);
  5152. while (true)
  5153. {
  5154. get();
  5155. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  5156. {
  5157. return false;
  5158. }
  5159. if (current == 0x00)
  5160. {
  5161. return true;
  5162. }
  5163. *out++ = static_cast<char>(current);
  5164. }
  5165. return true;
  5166. }
  5167. /*!
  5168. @brief Parses a zero-terminated string of length @a len from the BSON
  5169. input.
  5170. @param[in] len The length (including the zero-byte at the end) of the
  5171. string to be read.
  5172. @param[in, out] result A reference to the string variable where the read
  5173. string is to be stored.
  5174. @tparam NumberType The type of the length @a len
  5175. @pre len >= 1
  5176. @return `true` if the string was successfully parsed
  5177. */
  5178. template<typename NumberType>
  5179. bool get_bson_string(const NumberType len, string_t& result)
  5180. {
  5181. if (JSON_HEDLEY_UNLIKELY(len < 1))
  5182. {
  5183. auto last_token = get_token_string();
  5184. 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")));
  5185. }
  5186. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  5187. }
  5188. /*!
  5189. @brief Parses a byte array input of length @a len from the BSON input.
  5190. @param[in] len The length of the byte array to be read.
  5191. @param[in, out] result A reference to the binary variable where the read
  5192. array is to be stored.
  5193. @tparam NumberType The type of the length @a len
  5194. @pre len >= 0
  5195. @return `true` if the byte array was successfully parsed
  5196. */
  5197. template<typename NumberType>
  5198. bool get_bson_binary(const NumberType len, binary_t& result)
  5199. {
  5200. if (JSON_HEDLEY_UNLIKELY(len < 0))
  5201. {
  5202. auto last_token = get_token_string();
  5203. 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")));
  5204. }
  5205. // All BSON binary values have a subtype
  5206. std::uint8_t subtype;
  5207. get_number<std::uint8_t>(input_format_t::bson, subtype);
  5208. result.set_subtype(subtype);
  5209. return get_binary(input_format_t::bson, len, result);
  5210. }
  5211. /*!
  5212. @brief Read a BSON document element of the given @a element_type.
  5213. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  5214. @param[in] element_type_parse_position The position in the input stream,
  5215. where the `element_type` was read.
  5216. @warning Not all BSON element types are supported yet. An unsupported
  5217. @a element_type will give rise to a parse_error.114:
  5218. Unsupported BSON record type 0x...
  5219. @return whether a valid BSON-object/array was passed to the SAX parser
  5220. */
  5221. bool parse_bson_element_internal(const int element_type,
  5222. const std::size_t element_type_parse_position)
  5223. {
  5224. switch (element_type)
  5225. {
  5226. case 0x01: // double
  5227. {
  5228. double number;
  5229. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5230. }
  5231. case 0x02: // string
  5232. {
  5233. std::int32_t len;
  5234. string_t value;
  5235. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  5236. }
  5237. case 0x03: // object
  5238. {
  5239. return parse_bson_internal();
  5240. }
  5241. case 0x04: // array
  5242. {
  5243. return parse_bson_array();
  5244. }
  5245. case 0x05: // binary
  5246. {
  5247. std::int32_t len;
  5248. binary_t value;
  5249. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_binary(len, value) and sax->binary(value);
  5250. }
  5251. case 0x08: // boolean
  5252. {
  5253. return sax->boolean(get() != 0);
  5254. }
  5255. case 0x0A: // null
  5256. {
  5257. return sax->null();
  5258. }
  5259. case 0x10: // int32
  5260. {
  5261. std::int32_t value;
  5262. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5263. }
  5264. case 0x12: // int64
  5265. {
  5266. std::int64_t value;
  5267. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  5268. }
  5269. default: // anything else not supported (yet)
  5270. {
  5271. std::array<char, 3> cr{{}};
  5272. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  5273. 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())));
  5274. }
  5275. }
  5276. }
  5277. /*!
  5278. @brief Read a BSON element list (as specified in the BSON-spec)
  5279. The same binary layout is used for objects and arrays, hence it must be
  5280. indicated with the argument @a is_array which one is expected
  5281. (true --> array, false --> object).
  5282. @param[in] is_array Determines if the element list being read is to be
  5283. treated as an object (@a is_array == false), or as an
  5284. array (@a is_array == true).
  5285. @return whether a valid BSON-object/array was passed to the SAX parser
  5286. */
  5287. bool parse_bson_element_list(const bool is_array)
  5288. {
  5289. string_t key;
  5290. while (int element_type = get())
  5291. {
  5292. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  5293. {
  5294. return false;
  5295. }
  5296. const std::size_t element_type_parse_position = chars_read;
  5297. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  5298. {
  5299. return false;
  5300. }
  5301. if (not is_array and not sax->key(key))
  5302. {
  5303. return false;
  5304. }
  5305. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  5306. {
  5307. return false;
  5308. }
  5309. // get_bson_cstr only appends
  5310. key.clear();
  5311. }
  5312. return true;
  5313. }
  5314. /*!
  5315. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  5316. @return whether a valid BSON-array was passed to the SAX parser
  5317. */
  5318. bool parse_bson_array()
  5319. {
  5320. std::int32_t document_size;
  5321. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5322. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5323. {
  5324. return false;
  5325. }
  5326. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  5327. {
  5328. return false;
  5329. }
  5330. return sax->end_array();
  5331. }
  5332. //////////
  5333. // CBOR //
  5334. //////////
  5335. /*!
  5336. @param[in] get_char whether a new character should be retrieved from the
  5337. input (true, default) or whether the last read
  5338. character should be considered instead
  5339. @return whether a valid CBOR value was passed to the SAX parser
  5340. */
  5341. bool parse_cbor_internal(const bool get_char = true)
  5342. {
  5343. switch (get_char ? get() : current)
  5344. {
  5345. // EOF
  5346. case std::char_traits<char>::eof():
  5347. return unexpect_eof(input_format_t::cbor, "value");
  5348. // Integer 0x00..0x17 (0..23)
  5349. case 0x00:
  5350. case 0x01:
  5351. case 0x02:
  5352. case 0x03:
  5353. case 0x04:
  5354. case 0x05:
  5355. case 0x06:
  5356. case 0x07:
  5357. case 0x08:
  5358. case 0x09:
  5359. case 0x0A:
  5360. case 0x0B:
  5361. case 0x0C:
  5362. case 0x0D:
  5363. case 0x0E:
  5364. case 0x0F:
  5365. case 0x10:
  5366. case 0x11:
  5367. case 0x12:
  5368. case 0x13:
  5369. case 0x14:
  5370. case 0x15:
  5371. case 0x16:
  5372. case 0x17:
  5373. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5374. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5375. {
  5376. std::uint8_t number;
  5377. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5378. }
  5379. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5380. {
  5381. std::uint16_t number;
  5382. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5383. }
  5384. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  5385. {
  5386. std::uint32_t number;
  5387. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5388. }
  5389. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  5390. {
  5391. std::uint64_t number;
  5392. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  5393. }
  5394. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5395. case 0x20:
  5396. case 0x21:
  5397. case 0x22:
  5398. case 0x23:
  5399. case 0x24:
  5400. case 0x25:
  5401. case 0x26:
  5402. case 0x27:
  5403. case 0x28:
  5404. case 0x29:
  5405. case 0x2A:
  5406. case 0x2B:
  5407. case 0x2C:
  5408. case 0x2D:
  5409. case 0x2E:
  5410. case 0x2F:
  5411. case 0x30:
  5412. case 0x31:
  5413. case 0x32:
  5414. case 0x33:
  5415. case 0x34:
  5416. case 0x35:
  5417. case 0x36:
  5418. case 0x37:
  5419. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  5420. case 0x38: // Negative integer (one-byte uint8_t follows)
  5421. {
  5422. std::uint8_t number;
  5423. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5424. }
  5425. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5426. {
  5427. std::uint16_t number;
  5428. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5429. }
  5430. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  5431. {
  5432. std::uint32_t number;
  5433. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5434. }
  5435. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  5436. {
  5437. std::uint64_t number;
  5438. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  5439. - static_cast<number_integer_t>(number));
  5440. }
  5441. // Binary data (0x00..0x17 bytes follow)
  5442. case 0x40:
  5443. case 0x41:
  5444. case 0x42:
  5445. case 0x43:
  5446. case 0x44:
  5447. case 0x45:
  5448. case 0x46:
  5449. case 0x47:
  5450. case 0x48:
  5451. case 0x49:
  5452. case 0x4A:
  5453. case 0x4B:
  5454. case 0x4C:
  5455. case 0x4D:
  5456. case 0x4E:
  5457. case 0x4F:
  5458. case 0x50:
  5459. case 0x51:
  5460. case 0x52:
  5461. case 0x53:
  5462. case 0x54:
  5463. case 0x55:
  5464. case 0x56:
  5465. case 0x57:
  5466. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5467. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5468. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5469. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5470. case 0x5F: // Binary data (indefinite length)
  5471. {
  5472. binary_t b;
  5473. return get_cbor_binary(b) and sax->binary(b);
  5474. }
  5475. // UTF-8 string (0x00..0x17 bytes follow)
  5476. case 0x60:
  5477. case 0x61:
  5478. case 0x62:
  5479. case 0x63:
  5480. case 0x64:
  5481. case 0x65:
  5482. case 0x66:
  5483. case 0x67:
  5484. case 0x68:
  5485. case 0x69:
  5486. case 0x6A:
  5487. case 0x6B:
  5488. case 0x6C:
  5489. case 0x6D:
  5490. case 0x6E:
  5491. case 0x6F:
  5492. case 0x70:
  5493. case 0x71:
  5494. case 0x72:
  5495. case 0x73:
  5496. case 0x74:
  5497. case 0x75:
  5498. case 0x76:
  5499. case 0x77:
  5500. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5501. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5502. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5503. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5504. case 0x7F: // UTF-8 string (indefinite length)
  5505. {
  5506. string_t s;
  5507. return get_cbor_string(s) and sax->string(s);
  5508. }
  5509. // array (0x00..0x17 data items follow)
  5510. case 0x80:
  5511. case 0x81:
  5512. case 0x82:
  5513. case 0x83:
  5514. case 0x84:
  5515. case 0x85:
  5516. case 0x86:
  5517. case 0x87:
  5518. case 0x88:
  5519. case 0x89:
  5520. case 0x8A:
  5521. case 0x8B:
  5522. case 0x8C:
  5523. case 0x8D:
  5524. case 0x8E:
  5525. case 0x8F:
  5526. case 0x90:
  5527. case 0x91:
  5528. case 0x92:
  5529. case 0x93:
  5530. case 0x94:
  5531. case 0x95:
  5532. case 0x96:
  5533. case 0x97:
  5534. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5535. case 0x98: // array (one-byte uint8_t for n follows)
  5536. {
  5537. std::uint8_t len;
  5538. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5539. }
  5540. case 0x99: // array (two-byte uint16_t for n follow)
  5541. {
  5542. std::uint16_t len;
  5543. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5544. }
  5545. case 0x9A: // array (four-byte uint32_t for n follow)
  5546. {
  5547. std::uint32_t len;
  5548. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5549. }
  5550. case 0x9B: // array (eight-byte uint64_t for n follow)
  5551. {
  5552. std::uint64_t len;
  5553. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  5554. }
  5555. case 0x9F: // array (indefinite length)
  5556. return get_cbor_array(std::size_t(-1));
  5557. // map (0x00..0x17 pairs of data items follow)
  5558. case 0xA0:
  5559. case 0xA1:
  5560. case 0xA2:
  5561. case 0xA3:
  5562. case 0xA4:
  5563. case 0xA5:
  5564. case 0xA6:
  5565. case 0xA7:
  5566. case 0xA8:
  5567. case 0xA9:
  5568. case 0xAA:
  5569. case 0xAB:
  5570. case 0xAC:
  5571. case 0xAD:
  5572. case 0xAE:
  5573. case 0xAF:
  5574. case 0xB0:
  5575. case 0xB1:
  5576. case 0xB2:
  5577. case 0xB3:
  5578. case 0xB4:
  5579. case 0xB5:
  5580. case 0xB6:
  5581. case 0xB7:
  5582. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5583. case 0xB8: // map (one-byte uint8_t for n follows)
  5584. {
  5585. std::uint8_t len;
  5586. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5587. }
  5588. case 0xB9: // map (two-byte uint16_t for n follow)
  5589. {
  5590. std::uint16_t len;
  5591. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5592. }
  5593. case 0xBA: // map (four-byte uint32_t for n follow)
  5594. {
  5595. std::uint32_t len;
  5596. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5597. }
  5598. case 0xBB: // map (eight-byte uint64_t for n follow)
  5599. {
  5600. std::uint64_t len;
  5601. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5602. }
  5603. case 0xBF: // map (indefinite length)
  5604. return get_cbor_object(std::size_t(-1));
  5605. case 0xF4: // false
  5606. return sax->boolean(false);
  5607. case 0xF5: // true
  5608. return sax->boolean(true);
  5609. case 0xF6: // null
  5610. return sax->null();
  5611. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5612. {
  5613. const int byte1_raw = get();
  5614. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5615. {
  5616. return false;
  5617. }
  5618. const int byte2_raw = get();
  5619. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5620. {
  5621. return false;
  5622. }
  5623. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  5624. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  5625. // code from RFC 7049, Appendix D, Figure 3:
  5626. // As half-precision floating-point numbers were only added
  5627. // to IEEE 754 in 2008, today's programming platforms often
  5628. // still only have limited support for them. It is very
  5629. // easy to include at least decoding support for them even
  5630. // without such support. An example of a small decoder for
  5631. // half-precision floating-point numbers in the C language
  5632. // is shown in Fig. 3.
  5633. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  5634. const double val = [&half]
  5635. {
  5636. const int exp = (half >> 10u) & 0x1Fu;
  5637. const unsigned int mant = half & 0x3FFu;
  5638. assert(0 <= exp and exp <= 32);
  5639. assert(mant <= 1024);
  5640. switch (exp)
  5641. {
  5642. case 0:
  5643. return std::ldexp(mant, -24);
  5644. case 31:
  5645. return (mant == 0)
  5646. ? std::numeric_limits<double>::infinity()
  5647. : std::numeric_limits<double>::quiet_NaN();
  5648. default:
  5649. return std::ldexp(mant + 1024, exp - 25);
  5650. }
  5651. }();
  5652. return sax->number_float((half & 0x8000u) != 0
  5653. ? static_cast<number_float_t>(-val)
  5654. : static_cast<number_float_t>(val), "");
  5655. }
  5656. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5657. {
  5658. float number;
  5659. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5660. }
  5661. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5662. {
  5663. double number;
  5664. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5665. }
  5666. default: // anything else (0xFF is handled inside the other types)
  5667. {
  5668. auto last_token = get_token_string();
  5669. 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")));
  5670. }
  5671. }
  5672. }
  5673. /*!
  5674. @brief reads a CBOR string
  5675. This function first reads starting bytes to determine the expected
  5676. string length and then copies this number of bytes into a string.
  5677. Additionally, CBOR's strings with indefinite lengths are supported.
  5678. @param[out] result created string
  5679. @return whether string creation completed
  5680. */
  5681. bool get_cbor_string(string_t& result)
  5682. {
  5683. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  5684. {
  5685. return false;
  5686. }
  5687. switch (current)
  5688. {
  5689. // UTF-8 string (0x00..0x17 bytes follow)
  5690. case 0x60:
  5691. case 0x61:
  5692. case 0x62:
  5693. case 0x63:
  5694. case 0x64:
  5695. case 0x65:
  5696. case 0x66:
  5697. case 0x67:
  5698. case 0x68:
  5699. case 0x69:
  5700. case 0x6A:
  5701. case 0x6B:
  5702. case 0x6C:
  5703. case 0x6D:
  5704. case 0x6E:
  5705. case 0x6F:
  5706. case 0x70:
  5707. case 0x71:
  5708. case 0x72:
  5709. case 0x73:
  5710. case 0x74:
  5711. case 0x75:
  5712. case 0x76:
  5713. case 0x77:
  5714. {
  5715. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5716. }
  5717. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5718. {
  5719. std::uint8_t len;
  5720. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5721. }
  5722. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5723. {
  5724. std::uint16_t len;
  5725. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5726. }
  5727. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5728. {
  5729. std::uint32_t len;
  5730. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5731. }
  5732. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5733. {
  5734. std::uint64_t len;
  5735. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5736. }
  5737. case 0x7F: // UTF-8 string (indefinite length)
  5738. {
  5739. while (get() != 0xFF)
  5740. {
  5741. string_t chunk;
  5742. if (not get_cbor_string(chunk))
  5743. {
  5744. return false;
  5745. }
  5746. result.append(chunk);
  5747. }
  5748. return true;
  5749. }
  5750. default:
  5751. {
  5752. auto last_token = get_token_string();
  5753. 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")));
  5754. }
  5755. }
  5756. }
  5757. /*!
  5758. @brief reads a CBOR byte array
  5759. This function first reads starting bytes to determine the expected
  5760. byte array length and then copies this number of bytes into the byte array.
  5761. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  5762. @param[out] result created byte array
  5763. @return whether byte array creation completed
  5764. */
  5765. bool get_cbor_binary(binary_t& result)
  5766. {
  5767. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "binary")))
  5768. {
  5769. return false;
  5770. }
  5771. switch (current)
  5772. {
  5773. // Binary data (0x00..0x17 bytes follow)
  5774. case 0x40:
  5775. case 0x41:
  5776. case 0x42:
  5777. case 0x43:
  5778. case 0x44:
  5779. case 0x45:
  5780. case 0x46:
  5781. case 0x47:
  5782. case 0x48:
  5783. case 0x49:
  5784. case 0x4A:
  5785. case 0x4B:
  5786. case 0x4C:
  5787. case 0x4D:
  5788. case 0x4E:
  5789. case 0x4F:
  5790. case 0x50:
  5791. case 0x51:
  5792. case 0x52:
  5793. case 0x53:
  5794. case 0x54:
  5795. case 0x55:
  5796. case 0x56:
  5797. case 0x57:
  5798. {
  5799. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5800. }
  5801. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5802. {
  5803. std::uint8_t len;
  5804. return get_number(input_format_t::cbor, len) and
  5805. get_binary(input_format_t::cbor, len, result);
  5806. }
  5807. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5808. {
  5809. std::uint16_t len;
  5810. return get_number(input_format_t::cbor, len) and
  5811. get_binary(input_format_t::cbor, len, result);
  5812. }
  5813. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5814. {
  5815. std::uint32_t len;
  5816. return get_number(input_format_t::cbor, len) and
  5817. get_binary(input_format_t::cbor, len, result);
  5818. }
  5819. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5820. {
  5821. std::uint64_t len;
  5822. return get_number(input_format_t::cbor, len) and
  5823. get_binary(input_format_t::cbor, len, result);
  5824. }
  5825. case 0x5F: // Binary data (indefinite length)
  5826. {
  5827. while (get() != 0xFF)
  5828. {
  5829. binary_t chunk;
  5830. if (not get_cbor_binary(chunk))
  5831. {
  5832. return false;
  5833. }
  5834. result.insert(result.end(), chunk.begin(), chunk.end());
  5835. }
  5836. return true;
  5837. }
  5838. default:
  5839. {
  5840. auto last_token = get_token_string();
  5841. 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")));
  5842. }
  5843. }
  5844. }
  5845. /*!
  5846. @param[in] len the length of the array or std::size_t(-1) for an
  5847. array of indefinite size
  5848. @return whether array creation completed
  5849. */
  5850. bool get_cbor_array(const std::size_t len)
  5851. {
  5852. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5853. {
  5854. return false;
  5855. }
  5856. if (len != std::size_t(-1))
  5857. {
  5858. for (std::size_t i = 0; i < len; ++i)
  5859. {
  5860. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5861. {
  5862. return false;
  5863. }
  5864. }
  5865. }
  5866. else
  5867. {
  5868. while (get() != 0xFF)
  5869. {
  5870. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5871. {
  5872. return false;
  5873. }
  5874. }
  5875. }
  5876. return sax->end_array();
  5877. }
  5878. /*!
  5879. @param[in] len the length of the object or std::size_t(-1) for an
  5880. object of indefinite size
  5881. @return whether object creation completed
  5882. */
  5883. bool get_cbor_object(const std::size_t len)
  5884. {
  5885. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5886. {
  5887. return false;
  5888. }
  5889. string_t key;
  5890. if (len != std::size_t(-1))
  5891. {
  5892. for (std::size_t i = 0; i < len; ++i)
  5893. {
  5894. get();
  5895. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5896. {
  5897. return false;
  5898. }
  5899. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5900. {
  5901. return false;
  5902. }
  5903. key.clear();
  5904. }
  5905. }
  5906. else
  5907. {
  5908. while (get() != 0xFF)
  5909. {
  5910. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5911. {
  5912. return false;
  5913. }
  5914. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5915. {
  5916. return false;
  5917. }
  5918. key.clear();
  5919. }
  5920. }
  5921. return sax->end_object();
  5922. }
  5923. /////////////
  5924. // MsgPack //
  5925. /////////////
  5926. /*!
  5927. @return whether a valid MessagePack value was passed to the SAX parser
  5928. */
  5929. bool parse_msgpack_internal()
  5930. {
  5931. switch (get())
  5932. {
  5933. // EOF
  5934. case std::char_traits<char>::eof():
  5935. return unexpect_eof(input_format_t::msgpack, "value");
  5936. // positive fixint
  5937. case 0x00:
  5938. case 0x01:
  5939. case 0x02:
  5940. case 0x03:
  5941. case 0x04:
  5942. case 0x05:
  5943. case 0x06:
  5944. case 0x07:
  5945. case 0x08:
  5946. case 0x09:
  5947. case 0x0A:
  5948. case 0x0B:
  5949. case 0x0C:
  5950. case 0x0D:
  5951. case 0x0E:
  5952. case 0x0F:
  5953. case 0x10:
  5954. case 0x11:
  5955. case 0x12:
  5956. case 0x13:
  5957. case 0x14:
  5958. case 0x15:
  5959. case 0x16:
  5960. case 0x17:
  5961. case 0x18:
  5962. case 0x19:
  5963. case 0x1A:
  5964. case 0x1B:
  5965. case 0x1C:
  5966. case 0x1D:
  5967. case 0x1E:
  5968. case 0x1F:
  5969. case 0x20:
  5970. case 0x21:
  5971. case 0x22:
  5972. case 0x23:
  5973. case 0x24:
  5974. case 0x25:
  5975. case 0x26:
  5976. case 0x27:
  5977. case 0x28:
  5978. case 0x29:
  5979. case 0x2A:
  5980. case 0x2B:
  5981. case 0x2C:
  5982. case 0x2D:
  5983. case 0x2E:
  5984. case 0x2F:
  5985. case 0x30:
  5986. case 0x31:
  5987. case 0x32:
  5988. case 0x33:
  5989. case 0x34:
  5990. case 0x35:
  5991. case 0x36:
  5992. case 0x37:
  5993. case 0x38:
  5994. case 0x39:
  5995. case 0x3A:
  5996. case 0x3B:
  5997. case 0x3C:
  5998. case 0x3D:
  5999. case 0x3E:
  6000. case 0x3F:
  6001. case 0x40:
  6002. case 0x41:
  6003. case 0x42:
  6004. case 0x43:
  6005. case 0x44:
  6006. case 0x45:
  6007. case 0x46:
  6008. case 0x47:
  6009. case 0x48:
  6010. case 0x49:
  6011. case 0x4A:
  6012. case 0x4B:
  6013. case 0x4C:
  6014. case 0x4D:
  6015. case 0x4E:
  6016. case 0x4F:
  6017. case 0x50:
  6018. case 0x51:
  6019. case 0x52:
  6020. case 0x53:
  6021. case 0x54:
  6022. case 0x55:
  6023. case 0x56:
  6024. case 0x57:
  6025. case 0x58:
  6026. case 0x59:
  6027. case 0x5A:
  6028. case 0x5B:
  6029. case 0x5C:
  6030. case 0x5D:
  6031. case 0x5E:
  6032. case 0x5F:
  6033. case 0x60:
  6034. case 0x61:
  6035. case 0x62:
  6036. case 0x63:
  6037. case 0x64:
  6038. case 0x65:
  6039. case 0x66:
  6040. case 0x67:
  6041. case 0x68:
  6042. case 0x69:
  6043. case 0x6A:
  6044. case 0x6B:
  6045. case 0x6C:
  6046. case 0x6D:
  6047. case 0x6E:
  6048. case 0x6F:
  6049. case 0x70:
  6050. case 0x71:
  6051. case 0x72:
  6052. case 0x73:
  6053. case 0x74:
  6054. case 0x75:
  6055. case 0x76:
  6056. case 0x77:
  6057. case 0x78:
  6058. case 0x79:
  6059. case 0x7A:
  6060. case 0x7B:
  6061. case 0x7C:
  6062. case 0x7D:
  6063. case 0x7E:
  6064. case 0x7F:
  6065. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  6066. // fixmap
  6067. case 0x80:
  6068. case 0x81:
  6069. case 0x82:
  6070. case 0x83:
  6071. case 0x84:
  6072. case 0x85:
  6073. case 0x86:
  6074. case 0x87:
  6075. case 0x88:
  6076. case 0x89:
  6077. case 0x8A:
  6078. case 0x8B:
  6079. case 0x8C:
  6080. case 0x8D:
  6081. case 0x8E:
  6082. case 0x8F:
  6083. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  6084. // fixarray
  6085. case 0x90:
  6086. case 0x91:
  6087. case 0x92:
  6088. case 0x93:
  6089. case 0x94:
  6090. case 0x95:
  6091. case 0x96:
  6092. case 0x97:
  6093. case 0x98:
  6094. case 0x99:
  6095. case 0x9A:
  6096. case 0x9B:
  6097. case 0x9C:
  6098. case 0x9D:
  6099. case 0x9E:
  6100. case 0x9F:
  6101. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  6102. // fixstr
  6103. case 0xA0:
  6104. case 0xA1:
  6105. case 0xA2:
  6106. case 0xA3:
  6107. case 0xA4:
  6108. case 0xA5:
  6109. case 0xA6:
  6110. case 0xA7:
  6111. case 0xA8:
  6112. case 0xA9:
  6113. case 0xAA:
  6114. case 0xAB:
  6115. case 0xAC:
  6116. case 0xAD:
  6117. case 0xAE:
  6118. case 0xAF:
  6119. case 0xB0:
  6120. case 0xB1:
  6121. case 0xB2:
  6122. case 0xB3:
  6123. case 0xB4:
  6124. case 0xB5:
  6125. case 0xB6:
  6126. case 0xB7:
  6127. case 0xB8:
  6128. case 0xB9:
  6129. case 0xBA:
  6130. case 0xBB:
  6131. case 0xBC:
  6132. case 0xBD:
  6133. case 0xBE:
  6134. case 0xBF:
  6135. case 0xD9: // str 8
  6136. case 0xDA: // str 16
  6137. case 0xDB: // str 32
  6138. {
  6139. string_t s;
  6140. return get_msgpack_string(s) and sax->string(s);
  6141. }
  6142. case 0xC0: // nil
  6143. return sax->null();
  6144. case 0xC2: // false
  6145. return sax->boolean(false);
  6146. case 0xC3: // true
  6147. return sax->boolean(true);
  6148. case 0xC4: // bin 8
  6149. case 0xC5: // bin 16
  6150. case 0xC6: // bin 32
  6151. case 0xC7: // ext 8
  6152. case 0xC8: // ext 16
  6153. case 0xC9: // ext 32
  6154. case 0xD4: // fixext 1
  6155. case 0xD5: // fixext 2
  6156. case 0xD6: // fixext 4
  6157. case 0xD7: // fixext 8
  6158. case 0xD8: // fixext 16
  6159. {
  6160. binary_t b;
  6161. return get_msgpack_binary(b) and sax->binary(b);
  6162. }
  6163. case 0xCA: // float 32
  6164. {
  6165. float number;
  6166. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6167. }
  6168. case 0xCB: // float 64
  6169. {
  6170. double number;
  6171. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6172. }
  6173. case 0xCC: // uint 8
  6174. {
  6175. std::uint8_t number;
  6176. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6177. }
  6178. case 0xCD: // uint 16
  6179. {
  6180. std::uint16_t number;
  6181. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6182. }
  6183. case 0xCE: // uint 32
  6184. {
  6185. std::uint32_t number;
  6186. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6187. }
  6188. case 0xCF: // uint 64
  6189. {
  6190. std::uint64_t number;
  6191. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  6192. }
  6193. case 0xD0: // int 8
  6194. {
  6195. std::int8_t number;
  6196. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6197. }
  6198. case 0xD1: // int 16
  6199. {
  6200. std::int16_t number;
  6201. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6202. }
  6203. case 0xD2: // int 32
  6204. {
  6205. std::int32_t number;
  6206. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6207. }
  6208. case 0xD3: // int 64
  6209. {
  6210. std::int64_t number;
  6211. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  6212. }
  6213. case 0xDC: // array 16
  6214. {
  6215. std::uint16_t len;
  6216. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6217. }
  6218. case 0xDD: // array 32
  6219. {
  6220. std::uint32_t len;
  6221. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  6222. }
  6223. case 0xDE: // map 16
  6224. {
  6225. std::uint16_t len;
  6226. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6227. }
  6228. case 0xDF: // map 32
  6229. {
  6230. std::uint32_t len;
  6231. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  6232. }
  6233. // negative fixint
  6234. case 0xE0:
  6235. case 0xE1:
  6236. case 0xE2:
  6237. case 0xE3:
  6238. case 0xE4:
  6239. case 0xE5:
  6240. case 0xE6:
  6241. case 0xE7:
  6242. case 0xE8:
  6243. case 0xE9:
  6244. case 0xEA:
  6245. case 0xEB:
  6246. case 0xEC:
  6247. case 0xED:
  6248. case 0xEE:
  6249. case 0xEF:
  6250. case 0xF0:
  6251. case 0xF1:
  6252. case 0xF2:
  6253. case 0xF3:
  6254. case 0xF4:
  6255. case 0xF5:
  6256. case 0xF6:
  6257. case 0xF7:
  6258. case 0xF8:
  6259. case 0xF9:
  6260. case 0xFA:
  6261. case 0xFB:
  6262. case 0xFC:
  6263. case 0xFD:
  6264. case 0xFE:
  6265. case 0xFF:
  6266. return sax->number_integer(static_cast<std::int8_t>(current));
  6267. default: // anything else
  6268. {
  6269. auto last_token = get_token_string();
  6270. 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")));
  6271. }
  6272. }
  6273. }
  6274. /*!
  6275. @brief reads a MessagePack string
  6276. This function first reads starting bytes to determine the expected
  6277. string length and then copies this number of bytes into a string.
  6278. @param[out] result created string
  6279. @return whether string creation completed
  6280. */
  6281. bool get_msgpack_string(string_t& result)
  6282. {
  6283. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  6284. {
  6285. return false;
  6286. }
  6287. switch (current)
  6288. {
  6289. // fixstr
  6290. case 0xA0:
  6291. case 0xA1:
  6292. case 0xA2:
  6293. case 0xA3:
  6294. case 0xA4:
  6295. case 0xA5:
  6296. case 0xA6:
  6297. case 0xA7:
  6298. case 0xA8:
  6299. case 0xA9:
  6300. case 0xAA:
  6301. case 0xAB:
  6302. case 0xAC:
  6303. case 0xAD:
  6304. case 0xAE:
  6305. case 0xAF:
  6306. case 0xB0:
  6307. case 0xB1:
  6308. case 0xB2:
  6309. case 0xB3:
  6310. case 0xB4:
  6311. case 0xB5:
  6312. case 0xB6:
  6313. case 0xB7:
  6314. case 0xB8:
  6315. case 0xB9:
  6316. case 0xBA:
  6317. case 0xBB:
  6318. case 0xBC:
  6319. case 0xBD:
  6320. case 0xBE:
  6321. case 0xBF:
  6322. {
  6323. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  6324. }
  6325. case 0xD9: // str 8
  6326. {
  6327. std::uint8_t len;
  6328. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6329. }
  6330. case 0xDA: // str 16
  6331. {
  6332. std::uint16_t len;
  6333. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6334. }
  6335. case 0xDB: // str 32
  6336. {
  6337. std::uint32_t len;
  6338. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  6339. }
  6340. default:
  6341. {
  6342. auto last_token = get_token_string();
  6343. 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")));
  6344. }
  6345. }
  6346. }
  6347. /*!
  6348. @brief reads a MessagePack byte array
  6349. This function first reads starting bytes to determine the expected
  6350. byte array length and then copies this number of bytes into a byte array.
  6351. @param[out] result created byte array
  6352. @return whether byte array creation completed
  6353. */
  6354. bool get_msgpack_binary(binary_t& result)
  6355. {
  6356. // helper function to set the subtype
  6357. auto assign_and_return_true = [&result](std::int8_t subtype)
  6358. {
  6359. result.set_subtype(static_cast<std::uint8_t>(subtype));
  6360. return true;
  6361. };
  6362. switch (current)
  6363. {
  6364. case 0xC4: // bin 8
  6365. {
  6366. std::uint8_t len;
  6367. return get_number(input_format_t::msgpack, len) and
  6368. get_binary(input_format_t::msgpack, len, result);
  6369. }
  6370. case 0xC5: // bin 16
  6371. {
  6372. std::uint16_t len;
  6373. return get_number(input_format_t::msgpack, len) and
  6374. get_binary(input_format_t::msgpack, len, result);
  6375. }
  6376. case 0xC6: // bin 32
  6377. {
  6378. std::uint32_t len;
  6379. return get_number(input_format_t::msgpack, len) and
  6380. get_binary(input_format_t::msgpack, len, result);
  6381. }
  6382. case 0xC7: // ext 8
  6383. {
  6384. std::uint8_t len;
  6385. std::int8_t subtype;
  6386. return get_number(input_format_t::msgpack, len) and
  6387. get_number(input_format_t::msgpack, subtype) and
  6388. get_binary(input_format_t::msgpack, len, result) and
  6389. assign_and_return_true(subtype);
  6390. }
  6391. case 0xC8: // ext 16
  6392. {
  6393. std::uint16_t len;
  6394. std::int8_t subtype;
  6395. return get_number(input_format_t::msgpack, len) and
  6396. get_number(input_format_t::msgpack, subtype) and
  6397. get_binary(input_format_t::msgpack, len, result) and
  6398. assign_and_return_true(subtype);
  6399. }
  6400. case 0xC9: // ext 32
  6401. {
  6402. std::uint32_t len;
  6403. std::int8_t subtype;
  6404. return get_number(input_format_t::msgpack, len) and
  6405. get_number(input_format_t::msgpack, subtype) and
  6406. get_binary(input_format_t::msgpack, len, result) and
  6407. assign_and_return_true(subtype);
  6408. }
  6409. case 0xD4: // fixext 1
  6410. {
  6411. std::int8_t subtype;
  6412. return get_number(input_format_t::msgpack, subtype) and
  6413. get_binary(input_format_t::msgpack, 1, result) and
  6414. assign_and_return_true(subtype);
  6415. }
  6416. case 0xD5: // fixext 2
  6417. {
  6418. std::int8_t subtype;
  6419. return get_number(input_format_t::msgpack, subtype) and
  6420. get_binary(input_format_t::msgpack, 2, result) and
  6421. assign_and_return_true(subtype);
  6422. }
  6423. case 0xD6: // fixext 4
  6424. {
  6425. std::int8_t subtype;
  6426. return get_number(input_format_t::msgpack, subtype) and
  6427. get_binary(input_format_t::msgpack, 4, result) and
  6428. assign_and_return_true(subtype);
  6429. }
  6430. case 0xD7: // fixext 8
  6431. {
  6432. std::int8_t subtype;
  6433. return get_number(input_format_t::msgpack, subtype) and
  6434. get_binary(input_format_t::msgpack, 8, result) and
  6435. assign_and_return_true(subtype);
  6436. }
  6437. case 0xD8: // fixext 16
  6438. {
  6439. std::int8_t subtype;
  6440. return get_number(input_format_t::msgpack, subtype) and
  6441. get_binary(input_format_t::msgpack, 16, result) and
  6442. assign_and_return_true(subtype);
  6443. }
  6444. default: // LCOV_EXCL_LINE
  6445. return false; // LCOV_EXCL_LINE
  6446. }
  6447. }
  6448. /*!
  6449. @param[in] len the length of the array
  6450. @return whether array creation completed
  6451. */
  6452. bool get_msgpack_array(const std::size_t len)
  6453. {
  6454. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  6455. {
  6456. return false;
  6457. }
  6458. for (std::size_t i = 0; i < len; ++i)
  6459. {
  6460. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  6461. {
  6462. return false;
  6463. }
  6464. }
  6465. return sax->end_array();
  6466. }
  6467. /*!
  6468. @param[in] len the length of the object
  6469. @return whether object creation completed
  6470. */
  6471. bool get_msgpack_object(const std::size_t len)
  6472. {
  6473. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  6474. {
  6475. return false;
  6476. }
  6477. string_t key;
  6478. for (std::size_t i = 0; i < len; ++i)
  6479. {
  6480. get();
  6481. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  6482. {
  6483. return false;
  6484. }
  6485. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  6486. {
  6487. return false;
  6488. }
  6489. key.clear();
  6490. }
  6491. return sax->end_object();
  6492. }
  6493. ////////////
  6494. // UBJSON //
  6495. ////////////
  6496. /*!
  6497. @param[in] get_char whether a new character should be retrieved from the
  6498. input (true, default) or whether the last read
  6499. character should be considered instead
  6500. @return whether a valid UBJSON value was passed to the SAX parser
  6501. */
  6502. bool parse_ubjson_internal(const bool get_char = true)
  6503. {
  6504. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  6505. }
  6506. /*!
  6507. @brief reads a UBJSON string
  6508. This function is either called after reading the 'S' byte explicitly
  6509. indicating a string, or in case of an object key where the 'S' byte can be
  6510. left out.
  6511. @param[out] result created string
  6512. @param[in] get_char whether a new character should be retrieved from the
  6513. input (true, default) or whether the last read
  6514. character should be considered instead
  6515. @return whether string creation completed
  6516. */
  6517. bool get_ubjson_string(string_t& result, const bool get_char = true)
  6518. {
  6519. if (get_char)
  6520. {
  6521. get(); // TODO(niels): may we ignore N here?
  6522. }
  6523. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6524. {
  6525. return false;
  6526. }
  6527. switch (current)
  6528. {
  6529. case 'U':
  6530. {
  6531. std::uint8_t len;
  6532. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6533. }
  6534. case 'i':
  6535. {
  6536. std::int8_t len;
  6537. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6538. }
  6539. case 'I':
  6540. {
  6541. std::int16_t len;
  6542. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6543. }
  6544. case 'l':
  6545. {
  6546. std::int32_t len;
  6547. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6548. }
  6549. case 'L':
  6550. {
  6551. std::int64_t len;
  6552. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  6553. }
  6554. default:
  6555. auto last_token = get_token_string();
  6556. 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")));
  6557. }
  6558. }
  6559. /*!
  6560. @param[out] result determined size
  6561. @return whether size determination completed
  6562. */
  6563. bool get_ubjson_size_value(std::size_t& result)
  6564. {
  6565. switch (get_ignore_noop())
  6566. {
  6567. case 'U':
  6568. {
  6569. std::uint8_t number;
  6570. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6571. {
  6572. return false;
  6573. }
  6574. result = static_cast<std::size_t>(number);
  6575. return true;
  6576. }
  6577. case 'i':
  6578. {
  6579. std::int8_t number;
  6580. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6581. {
  6582. return false;
  6583. }
  6584. result = static_cast<std::size_t>(number);
  6585. return true;
  6586. }
  6587. case 'I':
  6588. {
  6589. std::int16_t number;
  6590. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6591. {
  6592. return false;
  6593. }
  6594. result = static_cast<std::size_t>(number);
  6595. return true;
  6596. }
  6597. case 'l':
  6598. {
  6599. std::int32_t number;
  6600. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6601. {
  6602. return false;
  6603. }
  6604. result = static_cast<std::size_t>(number);
  6605. return true;
  6606. }
  6607. case 'L':
  6608. {
  6609. std::int64_t number;
  6610. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  6611. {
  6612. return false;
  6613. }
  6614. result = static_cast<std::size_t>(number);
  6615. return true;
  6616. }
  6617. default:
  6618. {
  6619. auto last_token = get_token_string();
  6620. 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")));
  6621. }
  6622. }
  6623. }
  6624. /*!
  6625. @brief determine the type and size for a container
  6626. In the optimized UBJSON format, a type and a size can be provided to allow
  6627. for a more compact representation.
  6628. @param[out] result pair of the size and the type
  6629. @return whether pair creation completed
  6630. */
  6631. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  6632. {
  6633. result.first = string_t::npos; // size
  6634. result.second = 0; // type
  6635. get_ignore_noop();
  6636. if (current == '$')
  6637. {
  6638. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  6639. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  6640. {
  6641. return false;
  6642. }
  6643. get_ignore_noop();
  6644. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  6645. {
  6646. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  6647. {
  6648. return false;
  6649. }
  6650. auto last_token = get_token_string();
  6651. 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")));
  6652. }
  6653. return get_ubjson_size_value(result.first);
  6654. }
  6655. if (current == '#')
  6656. {
  6657. return get_ubjson_size_value(result.first);
  6658. }
  6659. return true;
  6660. }
  6661. /*!
  6662. @param prefix the previously read or set type prefix
  6663. @return whether value creation completed
  6664. */
  6665. bool get_ubjson_value(const int prefix)
  6666. {
  6667. switch (prefix)
  6668. {
  6669. case std::char_traits<char>::eof(): // EOF
  6670. return unexpect_eof(input_format_t::ubjson, "value");
  6671. case 'T': // true
  6672. return sax->boolean(true);
  6673. case 'F': // false
  6674. return sax->boolean(false);
  6675. case 'Z': // null
  6676. return sax->null();
  6677. case 'U':
  6678. {
  6679. std::uint8_t number;
  6680. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  6681. }
  6682. case 'i':
  6683. {
  6684. std::int8_t number;
  6685. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6686. }
  6687. case 'I':
  6688. {
  6689. std::int16_t number;
  6690. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6691. }
  6692. case 'l':
  6693. {
  6694. std::int32_t number;
  6695. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6696. }
  6697. case 'L':
  6698. {
  6699. std::int64_t number;
  6700. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  6701. }
  6702. case 'd':
  6703. {
  6704. float number;
  6705. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6706. }
  6707. case 'D':
  6708. {
  6709. double number;
  6710. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  6711. }
  6712. case 'C': // char
  6713. {
  6714. get();
  6715. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  6716. {
  6717. return false;
  6718. }
  6719. if (JSON_HEDLEY_UNLIKELY(current > 127))
  6720. {
  6721. auto last_token = get_token_string();
  6722. 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")));
  6723. }
  6724. string_t s(1, static_cast<char>(current));
  6725. return sax->string(s);
  6726. }
  6727. case 'S': // string
  6728. {
  6729. string_t s;
  6730. return get_ubjson_string(s) and sax->string(s);
  6731. }
  6732. case '[': // array
  6733. return get_ubjson_array();
  6734. case '{': // object
  6735. return get_ubjson_object();
  6736. default: // anything else
  6737. {
  6738. auto last_token = get_token_string();
  6739. 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")));
  6740. }
  6741. }
  6742. }
  6743. /*!
  6744. @return whether array creation completed
  6745. */
  6746. bool get_ubjson_array()
  6747. {
  6748. std::pair<std::size_t, int> size_and_type;
  6749. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6750. {
  6751. return false;
  6752. }
  6753. if (size_and_type.first != string_t::npos)
  6754. {
  6755. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  6756. {
  6757. return false;
  6758. }
  6759. if (size_and_type.second != 0)
  6760. {
  6761. if (size_and_type.second != 'N')
  6762. {
  6763. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6764. {
  6765. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6766. {
  6767. return false;
  6768. }
  6769. }
  6770. }
  6771. }
  6772. else
  6773. {
  6774. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6775. {
  6776. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6777. {
  6778. return false;
  6779. }
  6780. }
  6781. }
  6782. }
  6783. else
  6784. {
  6785. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  6786. {
  6787. return false;
  6788. }
  6789. while (current != ']')
  6790. {
  6791. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  6792. {
  6793. return false;
  6794. }
  6795. get_ignore_noop();
  6796. }
  6797. }
  6798. return sax->end_array();
  6799. }
  6800. /*!
  6801. @return whether object creation completed
  6802. */
  6803. bool get_ubjson_object()
  6804. {
  6805. std::pair<std::size_t, int> size_and_type;
  6806. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6807. {
  6808. return false;
  6809. }
  6810. string_t key;
  6811. if (size_and_type.first != string_t::npos)
  6812. {
  6813. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  6814. {
  6815. return false;
  6816. }
  6817. if (size_and_type.second != 0)
  6818. {
  6819. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6820. {
  6821. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6822. {
  6823. return false;
  6824. }
  6825. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6826. {
  6827. return false;
  6828. }
  6829. key.clear();
  6830. }
  6831. }
  6832. else
  6833. {
  6834. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6835. {
  6836. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6837. {
  6838. return false;
  6839. }
  6840. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6841. {
  6842. return false;
  6843. }
  6844. key.clear();
  6845. }
  6846. }
  6847. }
  6848. else
  6849. {
  6850. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6851. {
  6852. return false;
  6853. }
  6854. while (current != '}')
  6855. {
  6856. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  6857. {
  6858. return false;
  6859. }
  6860. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6861. {
  6862. return false;
  6863. }
  6864. get_ignore_noop();
  6865. key.clear();
  6866. }
  6867. }
  6868. return sax->end_object();
  6869. }
  6870. // Note, no reader for UBJSON binary types is implemented because they do
  6871. // not exist
  6872. ///////////////////////
  6873. // Utility functions //
  6874. ///////////////////////
  6875. /*!
  6876. @brief get next character from the input
  6877. This function provides the interface to the used input adapter. It does
  6878. not throw in case the input reached EOF, but returns a -'ve valued
  6879. `std::char_traits<char>::eof()` in that case.
  6880. @return character read from the input
  6881. */
  6882. int get()
  6883. {
  6884. ++chars_read;
  6885. return current = ia.get_character();
  6886. }
  6887. /*!
  6888. @return character read from the input after ignoring all 'N' entries
  6889. */
  6890. int get_ignore_noop()
  6891. {
  6892. do
  6893. {
  6894. get();
  6895. }
  6896. while (current == 'N');
  6897. return current;
  6898. }
  6899. /*
  6900. @brief read a number from the input
  6901. @tparam NumberType the type of the number
  6902. @param[in] format the current format (for diagnostics)
  6903. @param[out] result number of type @a NumberType
  6904. @return whether conversion completed
  6905. @note This function needs to respect the system's endianess, because
  6906. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  6907. (big endian) and therefore need reordering on little endian systems.
  6908. */
  6909. template<typename NumberType, bool InputIsLittleEndian = false>
  6910. bool get_number(const input_format_t format, NumberType& result)
  6911. {
  6912. // step 1: read input into array with system's byte order
  6913. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6914. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6915. {
  6916. get();
  6917. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6918. {
  6919. return false;
  6920. }
  6921. // reverse byte order prior to conversion if necessary
  6922. if (is_little_endian != InputIsLittleEndian)
  6923. {
  6924. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6925. }
  6926. else
  6927. {
  6928. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6929. }
  6930. }
  6931. // step 2: convert array into number of type T and return
  6932. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6933. return true;
  6934. }
  6935. /*!
  6936. @brief create a string by reading characters from the input
  6937. @tparam NumberType the type of the number
  6938. @param[in] format the current format (for diagnostics)
  6939. @param[in] len number of characters to read
  6940. @param[out] result string created by reading @a len bytes
  6941. @return whether string creation completed
  6942. @note We can not reserve @a len bytes for the result, because @a len
  6943. may be too large. Usually, @ref unexpect_eof() detects the end of
  6944. the input before we run out of string memory.
  6945. */
  6946. template<typename NumberType>
  6947. bool get_string(const input_format_t format,
  6948. const NumberType len,
  6949. string_t& result)
  6950. {
  6951. bool success = true;
  6952. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6953. {
  6954. get();
  6955. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6956. {
  6957. success = false;
  6958. }
  6959. return static_cast<char>(current);
  6960. });
  6961. return success;
  6962. }
  6963. /*!
  6964. @brief create a byte array by reading bytes from the input
  6965. @tparam NumberType the type of the number
  6966. @param[in] format the current format (for diagnostics)
  6967. @param[in] len number of bytes to read
  6968. @param[out] result byte array created by reading @a len bytes
  6969. @return whether byte array creation completed
  6970. @note We can not reserve @a len bytes for the result, because @a len
  6971. may be too large. Usually, @ref unexpect_eof() detects the end of
  6972. the input before we run out of memory.
  6973. */
  6974. template<typename NumberType>
  6975. bool get_binary(const input_format_t format,
  6976. const NumberType len,
  6977. binary_t& result)
  6978. {
  6979. bool success = true;
  6980. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6981. {
  6982. get();
  6983. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "binary")))
  6984. {
  6985. success = false;
  6986. }
  6987. return static_cast<std::uint8_t>(current);
  6988. });
  6989. return success;
  6990. }
  6991. /*!
  6992. @param[in] format the current format (for diagnostics)
  6993. @param[in] context further context information (for diagnostics)
  6994. @return whether the last read character is not EOF
  6995. */
  6996. JSON_HEDLEY_NON_NULL(3)
  6997. bool unexpect_eof(const input_format_t format, const char* context) const
  6998. {
  6999. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  7000. {
  7001. return sax->parse_error(chars_read, "<end of file>",
  7002. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  7003. }
  7004. return true;
  7005. }
  7006. /*!
  7007. @return a string representation of the last read byte
  7008. */
  7009. std::string get_token_string() const
  7010. {
  7011. std::array<char, 3> cr{{}};
  7012. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  7013. return std::string{cr.data()};
  7014. }
  7015. /*!
  7016. @param[in] format the current format
  7017. @param[in] detail a detailed error message
  7018. @param[in] context further context information
  7019. @return a message string to use in the parse_error exceptions
  7020. */
  7021. std::string exception_message(const input_format_t format,
  7022. const std::string& detail,
  7023. const std::string& context) const
  7024. {
  7025. std::string error_msg = "syntax error while parsing ";
  7026. switch (format)
  7027. {
  7028. case input_format_t::cbor:
  7029. error_msg += "CBOR";
  7030. break;
  7031. case input_format_t::msgpack:
  7032. error_msg += "MessagePack";
  7033. break;
  7034. case input_format_t::ubjson:
  7035. error_msg += "UBJSON";
  7036. break;
  7037. case input_format_t::bson:
  7038. error_msg += "BSON";
  7039. break;
  7040. default: // LCOV_EXCL_LINE
  7041. assert(false); // LCOV_EXCL_LINE
  7042. }
  7043. return error_msg + " " + context + ": " + detail;
  7044. }
  7045. private:
  7046. /// input adapter
  7047. InputAdapterType ia;
  7048. /// the current character
  7049. int current = std::char_traits<char>::eof();
  7050. /// the number of characters read
  7051. std::size_t chars_read = 0;
  7052. /// whether we can assume little endianess
  7053. const bool is_little_endian = little_endianess();
  7054. /// the SAX parser
  7055. json_sax_t* sax = nullptr;
  7056. };
  7057. } // namespace detail
  7058. } // namespace nlohmann
  7059. // #include <nlohmann/detail/input/input_adapters.hpp>
  7060. // #include <nlohmann/detail/input/lexer.hpp>
  7061. #include <array> // array
  7062. #include <clocale> // localeconv
  7063. #include <cstddef> // size_t
  7064. #include <cstdio> // snprintf
  7065. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  7066. #include <initializer_list> // initializer_list
  7067. #include <string> // char_traits, string
  7068. #include <utility> // move
  7069. #include <vector> // vector
  7070. // #include <nlohmann/detail/input/input_adapters.hpp>
  7071. // #include <nlohmann/detail/input/position_t.hpp>
  7072. // #include <nlohmann/detail/macro_scope.hpp>
  7073. namespace nlohmann
  7074. {
  7075. namespace detail
  7076. {
  7077. ///////////
  7078. // lexer //
  7079. ///////////
  7080. template<typename BasicJsonType>
  7081. class lexer_base
  7082. {
  7083. public:
  7084. /// token types for the parser
  7085. enum class token_type
  7086. {
  7087. uninitialized, ///< indicating the scanner is uninitialized
  7088. literal_true, ///< the `true` literal
  7089. literal_false, ///< the `false` literal
  7090. literal_null, ///< the `null` literal
  7091. value_string, ///< a string -- use get_string() for actual value
  7092. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  7093. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  7094. value_float, ///< an floating point number -- use get_number_float() for actual value
  7095. begin_array, ///< the character for array begin `[`
  7096. begin_object, ///< the character for object begin `{`
  7097. end_array, ///< the character for array end `]`
  7098. end_object, ///< the character for object end `}`
  7099. name_separator, ///< the name separator `:`
  7100. value_separator, ///< the value separator `,`
  7101. parse_error, ///< indicating a parse error
  7102. end_of_input, ///< indicating the end of the input buffer
  7103. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  7104. };
  7105. /// return name of values of type token_type (only used for errors)
  7106. JSON_HEDLEY_RETURNS_NON_NULL
  7107. JSON_HEDLEY_CONST
  7108. static const char* token_type_name(const token_type t) noexcept
  7109. {
  7110. switch (t)
  7111. {
  7112. case token_type::uninitialized:
  7113. return "<uninitialized>";
  7114. case token_type::literal_true:
  7115. return "true literal";
  7116. case token_type::literal_false:
  7117. return "false literal";
  7118. case token_type::literal_null:
  7119. return "null literal";
  7120. case token_type::value_string:
  7121. return "string literal";
  7122. case token_type::value_unsigned:
  7123. case token_type::value_integer:
  7124. case token_type::value_float:
  7125. return "number literal";
  7126. case token_type::begin_array:
  7127. return "'['";
  7128. case token_type::begin_object:
  7129. return "'{'";
  7130. case token_type::end_array:
  7131. return "']'";
  7132. case token_type::end_object:
  7133. return "'}'";
  7134. case token_type::name_separator:
  7135. return "':'";
  7136. case token_type::value_separator:
  7137. return "','";
  7138. case token_type::parse_error:
  7139. return "<parse error>";
  7140. case token_type::end_of_input:
  7141. return "end of input";
  7142. case token_type::literal_or_value:
  7143. return "'[', '{', or a literal";
  7144. // LCOV_EXCL_START
  7145. default: // catch non-enum values
  7146. return "unknown token";
  7147. // LCOV_EXCL_STOP
  7148. }
  7149. }
  7150. };
  7151. /*!
  7152. @brief lexical analysis
  7153. This class organizes the lexical analysis during JSON deserialization.
  7154. */
  7155. template<typename BasicJsonType, typename InputAdapterType>
  7156. class lexer : public lexer_base<BasicJsonType>
  7157. {
  7158. using number_integer_t = typename BasicJsonType::number_integer_t;
  7159. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7160. using number_float_t = typename BasicJsonType::number_float_t;
  7161. using string_t = typename BasicJsonType::string_t;
  7162. public:
  7163. using token_type = typename lexer_base<BasicJsonType>::token_type;
  7164. explicit lexer(InputAdapterType&& adapter)
  7165. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  7166. // delete because of pointer members
  7167. lexer(const lexer&) = delete;
  7168. lexer(lexer&&) = default;
  7169. lexer& operator=(lexer&) = delete;
  7170. lexer& operator=(lexer&&) = default;
  7171. ~lexer() = default;
  7172. private:
  7173. /////////////////////
  7174. // locales
  7175. /////////////////////
  7176. /// return the locale-dependent decimal point
  7177. JSON_HEDLEY_PURE
  7178. static char get_decimal_point() noexcept
  7179. {
  7180. const auto loc = localeconv();
  7181. assert(loc != nullptr);
  7182. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  7183. }
  7184. /////////////////////
  7185. // scan functions
  7186. /////////////////////
  7187. /*!
  7188. @brief get codepoint from 4 hex characters following `\u`
  7189. For input "\u c1 c2 c3 c4" the codepoint is:
  7190. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  7191. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  7192. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  7193. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  7194. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  7195. between the ASCII value of the character and the desired integer value.
  7196. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  7197. non-hex character)
  7198. */
  7199. int get_codepoint()
  7200. {
  7201. // this function only makes sense after reading `\u`
  7202. assert(current == 'u');
  7203. int codepoint = 0;
  7204. const auto factors = { 12u, 8u, 4u, 0u };
  7205. for (const auto factor : factors)
  7206. {
  7207. get();
  7208. if (current >= '0' and current <= '9')
  7209. {
  7210. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  7211. }
  7212. else if (current >= 'A' and current <= 'F')
  7213. {
  7214. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  7215. }
  7216. else if (current >= 'a' and current <= 'f')
  7217. {
  7218. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  7219. }
  7220. else
  7221. {
  7222. return -1;
  7223. }
  7224. }
  7225. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  7226. return codepoint;
  7227. }
  7228. /*!
  7229. @brief check if the next byte(s) are inside a given range
  7230. Adds the current byte and, for each passed range, reads a new byte and
  7231. checks if it is inside the range. If a violation was detected, set up an
  7232. error message and return false. Otherwise, return true.
  7233. @param[in] ranges list of integers; interpreted as list of pairs of
  7234. inclusive lower and upper bound, respectively
  7235. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  7236. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  7237. @return true if and only if no range violation was detected
  7238. */
  7239. bool next_byte_in_range(std::initializer_list<int> ranges)
  7240. {
  7241. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  7242. add(current);
  7243. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  7244. {
  7245. get();
  7246. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  7247. {
  7248. add(current);
  7249. }
  7250. else
  7251. {
  7252. error_message = "invalid string: ill-formed UTF-8 byte";
  7253. return false;
  7254. }
  7255. }
  7256. return true;
  7257. }
  7258. /*!
  7259. @brief scan a string literal
  7260. This function scans a string according to Sect. 7 of RFC 7159. While
  7261. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  7262. function returns successfully, token_buffer is *not* null-terminated (as it
  7263. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  7264. string.
  7265. @return token_type::value_string if string could be successfully scanned,
  7266. token_type::parse_error otherwise
  7267. @note In case of errors, variable error_message contains a textual
  7268. description.
  7269. */
  7270. token_type scan_string()
  7271. {
  7272. // reset token_buffer (ignore opening quote)
  7273. reset();
  7274. // we entered the function by reading an open quote
  7275. assert(current == '\"');
  7276. while (true)
  7277. {
  7278. // get next character
  7279. switch (get())
  7280. {
  7281. // end of file while parsing string
  7282. case std::char_traits<char>::eof():
  7283. {
  7284. error_message = "invalid string: missing closing quote";
  7285. return token_type::parse_error;
  7286. }
  7287. // closing quote
  7288. case '\"':
  7289. {
  7290. return token_type::value_string;
  7291. }
  7292. // escapes
  7293. case '\\':
  7294. {
  7295. switch (get())
  7296. {
  7297. // quotation mark
  7298. case '\"':
  7299. add('\"');
  7300. break;
  7301. // reverse solidus
  7302. case '\\':
  7303. add('\\');
  7304. break;
  7305. // solidus
  7306. case '/':
  7307. add('/');
  7308. break;
  7309. // backspace
  7310. case 'b':
  7311. add('\b');
  7312. break;
  7313. // form feed
  7314. case 'f':
  7315. add('\f');
  7316. break;
  7317. // line feed
  7318. case 'n':
  7319. add('\n');
  7320. break;
  7321. // carriage return
  7322. case 'r':
  7323. add('\r');
  7324. break;
  7325. // tab
  7326. case 't':
  7327. add('\t');
  7328. break;
  7329. // unicode escapes
  7330. case 'u':
  7331. {
  7332. const int codepoint1 = get_codepoint();
  7333. int codepoint = codepoint1; // start with codepoint1
  7334. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  7335. {
  7336. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7337. return token_type::parse_error;
  7338. }
  7339. // check if code point is a high surrogate
  7340. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  7341. {
  7342. // expect next \uxxxx entry
  7343. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  7344. {
  7345. const int codepoint2 = get_codepoint();
  7346. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  7347. {
  7348. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7349. return token_type::parse_error;
  7350. }
  7351. // check if codepoint2 is a low surrogate
  7352. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  7353. {
  7354. // overwrite codepoint
  7355. codepoint = static_cast<int>(
  7356. // high surrogate occupies the most significant 22 bits
  7357. (static_cast<unsigned int>(codepoint1) << 10u)
  7358. // low surrogate occupies the least significant 15 bits
  7359. + static_cast<unsigned int>(codepoint2)
  7360. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  7361. // in the result so we have to subtract with:
  7362. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  7363. - 0x35FDC00u);
  7364. }
  7365. else
  7366. {
  7367. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7368. return token_type::parse_error;
  7369. }
  7370. }
  7371. else
  7372. {
  7373. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7374. return token_type::parse_error;
  7375. }
  7376. }
  7377. else
  7378. {
  7379. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  7380. {
  7381. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  7382. return token_type::parse_error;
  7383. }
  7384. }
  7385. // result of the above calculation yields a proper codepoint
  7386. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  7387. // translate codepoint into bytes
  7388. if (codepoint < 0x80)
  7389. {
  7390. // 1-byte characters: 0xxxxxxx (ASCII)
  7391. add(codepoint);
  7392. }
  7393. else if (codepoint <= 0x7FF)
  7394. {
  7395. // 2-byte characters: 110xxxxx 10xxxxxx
  7396. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  7397. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7398. }
  7399. else if (codepoint <= 0xFFFF)
  7400. {
  7401. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  7402. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  7403. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7404. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7405. }
  7406. else
  7407. {
  7408. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  7409. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  7410. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  7411. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7412. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7413. }
  7414. break;
  7415. }
  7416. // other characters after escape
  7417. default:
  7418. error_message = "invalid string: forbidden character after backslash";
  7419. return token_type::parse_error;
  7420. }
  7421. break;
  7422. }
  7423. // invalid control characters
  7424. case 0x00:
  7425. {
  7426. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  7427. return token_type::parse_error;
  7428. }
  7429. case 0x01:
  7430. {
  7431. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  7432. return token_type::parse_error;
  7433. }
  7434. case 0x02:
  7435. {
  7436. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  7437. return token_type::parse_error;
  7438. }
  7439. case 0x03:
  7440. {
  7441. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  7442. return token_type::parse_error;
  7443. }
  7444. case 0x04:
  7445. {
  7446. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  7447. return token_type::parse_error;
  7448. }
  7449. case 0x05:
  7450. {
  7451. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  7452. return token_type::parse_error;
  7453. }
  7454. case 0x06:
  7455. {
  7456. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  7457. return token_type::parse_error;
  7458. }
  7459. case 0x07:
  7460. {
  7461. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  7462. return token_type::parse_error;
  7463. }
  7464. case 0x08:
  7465. {
  7466. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  7467. return token_type::parse_error;
  7468. }
  7469. case 0x09:
  7470. {
  7471. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  7472. return token_type::parse_error;
  7473. }
  7474. case 0x0A:
  7475. {
  7476. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  7477. return token_type::parse_error;
  7478. }
  7479. case 0x0B:
  7480. {
  7481. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  7482. return token_type::parse_error;
  7483. }
  7484. case 0x0C:
  7485. {
  7486. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  7487. return token_type::parse_error;
  7488. }
  7489. case 0x0D:
  7490. {
  7491. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  7492. return token_type::parse_error;
  7493. }
  7494. case 0x0E:
  7495. {
  7496. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  7497. return token_type::parse_error;
  7498. }
  7499. case 0x0F:
  7500. {
  7501. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  7502. return token_type::parse_error;
  7503. }
  7504. case 0x10:
  7505. {
  7506. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  7507. return token_type::parse_error;
  7508. }
  7509. case 0x11:
  7510. {
  7511. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  7512. return token_type::parse_error;
  7513. }
  7514. case 0x12:
  7515. {
  7516. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  7517. return token_type::parse_error;
  7518. }
  7519. case 0x13:
  7520. {
  7521. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  7522. return token_type::parse_error;
  7523. }
  7524. case 0x14:
  7525. {
  7526. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  7527. return token_type::parse_error;
  7528. }
  7529. case 0x15:
  7530. {
  7531. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  7532. return token_type::parse_error;
  7533. }
  7534. case 0x16:
  7535. {
  7536. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  7537. return token_type::parse_error;
  7538. }
  7539. case 0x17:
  7540. {
  7541. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  7542. return token_type::parse_error;
  7543. }
  7544. case 0x18:
  7545. {
  7546. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  7547. return token_type::parse_error;
  7548. }
  7549. case 0x19:
  7550. {
  7551. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  7552. return token_type::parse_error;
  7553. }
  7554. case 0x1A:
  7555. {
  7556. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  7557. return token_type::parse_error;
  7558. }
  7559. case 0x1B:
  7560. {
  7561. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  7562. return token_type::parse_error;
  7563. }
  7564. case 0x1C:
  7565. {
  7566. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  7567. return token_type::parse_error;
  7568. }
  7569. case 0x1D:
  7570. {
  7571. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  7572. return token_type::parse_error;
  7573. }
  7574. case 0x1E:
  7575. {
  7576. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  7577. return token_type::parse_error;
  7578. }
  7579. case 0x1F:
  7580. {
  7581. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  7582. return token_type::parse_error;
  7583. }
  7584. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  7585. case 0x20:
  7586. case 0x21:
  7587. case 0x23:
  7588. case 0x24:
  7589. case 0x25:
  7590. case 0x26:
  7591. case 0x27:
  7592. case 0x28:
  7593. case 0x29:
  7594. case 0x2A:
  7595. case 0x2B:
  7596. case 0x2C:
  7597. case 0x2D:
  7598. case 0x2E:
  7599. case 0x2F:
  7600. case 0x30:
  7601. case 0x31:
  7602. case 0x32:
  7603. case 0x33:
  7604. case 0x34:
  7605. case 0x35:
  7606. case 0x36:
  7607. case 0x37:
  7608. case 0x38:
  7609. case 0x39:
  7610. case 0x3A:
  7611. case 0x3B:
  7612. case 0x3C:
  7613. case 0x3D:
  7614. case 0x3E:
  7615. case 0x3F:
  7616. case 0x40:
  7617. case 0x41:
  7618. case 0x42:
  7619. case 0x43:
  7620. case 0x44:
  7621. case 0x45:
  7622. case 0x46:
  7623. case 0x47:
  7624. case 0x48:
  7625. case 0x49:
  7626. case 0x4A:
  7627. case 0x4B:
  7628. case 0x4C:
  7629. case 0x4D:
  7630. case 0x4E:
  7631. case 0x4F:
  7632. case 0x50:
  7633. case 0x51:
  7634. case 0x52:
  7635. case 0x53:
  7636. case 0x54:
  7637. case 0x55:
  7638. case 0x56:
  7639. case 0x57:
  7640. case 0x58:
  7641. case 0x59:
  7642. case 0x5A:
  7643. case 0x5B:
  7644. case 0x5D:
  7645. case 0x5E:
  7646. case 0x5F:
  7647. case 0x60:
  7648. case 0x61:
  7649. case 0x62:
  7650. case 0x63:
  7651. case 0x64:
  7652. case 0x65:
  7653. case 0x66:
  7654. case 0x67:
  7655. case 0x68:
  7656. case 0x69:
  7657. case 0x6A:
  7658. case 0x6B:
  7659. case 0x6C:
  7660. case 0x6D:
  7661. case 0x6E:
  7662. case 0x6F:
  7663. case 0x70:
  7664. case 0x71:
  7665. case 0x72:
  7666. case 0x73:
  7667. case 0x74:
  7668. case 0x75:
  7669. case 0x76:
  7670. case 0x77:
  7671. case 0x78:
  7672. case 0x79:
  7673. case 0x7A:
  7674. case 0x7B:
  7675. case 0x7C:
  7676. case 0x7D:
  7677. case 0x7E:
  7678. case 0x7F:
  7679. {
  7680. add(current);
  7681. break;
  7682. }
  7683. // U+0080..U+07FF: bytes C2..DF 80..BF
  7684. case 0xC2:
  7685. case 0xC3:
  7686. case 0xC4:
  7687. case 0xC5:
  7688. case 0xC6:
  7689. case 0xC7:
  7690. case 0xC8:
  7691. case 0xC9:
  7692. case 0xCA:
  7693. case 0xCB:
  7694. case 0xCC:
  7695. case 0xCD:
  7696. case 0xCE:
  7697. case 0xCF:
  7698. case 0xD0:
  7699. case 0xD1:
  7700. case 0xD2:
  7701. case 0xD3:
  7702. case 0xD4:
  7703. case 0xD5:
  7704. case 0xD6:
  7705. case 0xD7:
  7706. case 0xD8:
  7707. case 0xD9:
  7708. case 0xDA:
  7709. case 0xDB:
  7710. case 0xDC:
  7711. case 0xDD:
  7712. case 0xDE:
  7713. case 0xDF:
  7714. {
  7715. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  7716. {
  7717. return token_type::parse_error;
  7718. }
  7719. break;
  7720. }
  7721. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  7722. case 0xE0:
  7723. {
  7724. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  7725. {
  7726. return token_type::parse_error;
  7727. }
  7728. break;
  7729. }
  7730. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  7731. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  7732. case 0xE1:
  7733. case 0xE2:
  7734. case 0xE3:
  7735. case 0xE4:
  7736. case 0xE5:
  7737. case 0xE6:
  7738. case 0xE7:
  7739. case 0xE8:
  7740. case 0xE9:
  7741. case 0xEA:
  7742. case 0xEB:
  7743. case 0xEC:
  7744. case 0xEE:
  7745. case 0xEF:
  7746. {
  7747. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  7748. {
  7749. return token_type::parse_error;
  7750. }
  7751. break;
  7752. }
  7753. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  7754. case 0xED:
  7755. {
  7756. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  7757. {
  7758. return token_type::parse_error;
  7759. }
  7760. break;
  7761. }
  7762. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  7763. case 0xF0:
  7764. {
  7765. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7766. {
  7767. return token_type::parse_error;
  7768. }
  7769. break;
  7770. }
  7771. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  7772. case 0xF1:
  7773. case 0xF2:
  7774. case 0xF3:
  7775. {
  7776. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7777. {
  7778. return token_type::parse_error;
  7779. }
  7780. break;
  7781. }
  7782. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  7783. case 0xF4:
  7784. {
  7785. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  7786. {
  7787. return token_type::parse_error;
  7788. }
  7789. break;
  7790. }
  7791. // remaining bytes (80..C1 and F5..FF) are ill-formed
  7792. default:
  7793. {
  7794. error_message = "invalid string: ill-formed UTF-8 byte";
  7795. return token_type::parse_error;
  7796. }
  7797. }
  7798. }
  7799. }
  7800. JSON_HEDLEY_NON_NULL(2)
  7801. static void strtof(float& f, const char* str, char** endptr) noexcept
  7802. {
  7803. f = std::strtof(str, endptr);
  7804. }
  7805. JSON_HEDLEY_NON_NULL(2)
  7806. static void strtof(double& f, const char* str, char** endptr) noexcept
  7807. {
  7808. f = std::strtod(str, endptr);
  7809. }
  7810. JSON_HEDLEY_NON_NULL(2)
  7811. static void strtof(long double& f, const char* str, char** endptr) noexcept
  7812. {
  7813. f = std::strtold(str, endptr);
  7814. }
  7815. /*!
  7816. @brief scan a number literal
  7817. This function scans a string according to Sect. 6 of RFC 7159.
  7818. The function is realized with a deterministic finite state machine derived
  7819. from the grammar described in RFC 7159. Starting in state "init", the
  7820. input is read and used to determined the next state. Only state "done"
  7821. accepts the number. State "error" is a trap state to model errors. In the
  7822. table below, "anything" means any character but the ones listed before.
  7823. state | 0 | 1-9 | e E | + | - | . | anything
  7824. ---------|----------|----------|----------|---------|---------|----------|-----------
  7825. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  7826. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  7827. zero | done | done | exponent | done | done | decimal1 | done
  7828. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  7829. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  7830. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  7831. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  7832. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  7833. any2 | any2 | any2 | done | done | done | done | done
  7834. The state machine is realized with one label per state (prefixed with
  7835. "scan_number_") and `goto` statements between them. The state machine
  7836. contains cycles, but any cycle can be left when EOF is read. Therefore,
  7837. the function is guaranteed to terminate.
  7838. During scanning, the read bytes are stored in token_buffer. This string is
  7839. then converted to a signed integer, an unsigned integer, or a
  7840. floating-point number.
  7841. @return token_type::value_unsigned, token_type::value_integer, or
  7842. token_type::value_float if number could be successfully scanned,
  7843. token_type::parse_error otherwise
  7844. @note The scanner is independent of the current locale. Internally, the
  7845. locale's decimal point is used instead of `.` to work with the
  7846. locale-dependent converters.
  7847. */
  7848. token_type scan_number() // lgtm [cpp/use-of-goto]
  7849. {
  7850. // reset token_buffer to store the number's bytes
  7851. reset();
  7852. // the type of the parsed number; initially set to unsigned; will be
  7853. // changed if minus sign, decimal point or exponent is read
  7854. token_type number_type = token_type::value_unsigned;
  7855. // state (init): we just found out we need to scan a number
  7856. switch (current)
  7857. {
  7858. case '-':
  7859. {
  7860. add(current);
  7861. goto scan_number_minus;
  7862. }
  7863. case '0':
  7864. {
  7865. add(current);
  7866. goto scan_number_zero;
  7867. }
  7868. case '1':
  7869. case '2':
  7870. case '3':
  7871. case '4':
  7872. case '5':
  7873. case '6':
  7874. case '7':
  7875. case '8':
  7876. case '9':
  7877. {
  7878. add(current);
  7879. goto scan_number_any1;
  7880. }
  7881. // all other characters are rejected outside scan_number()
  7882. default: // LCOV_EXCL_LINE
  7883. assert(false); // LCOV_EXCL_LINE
  7884. }
  7885. scan_number_minus:
  7886. // state: we just parsed a leading minus sign
  7887. number_type = token_type::value_integer;
  7888. switch (get())
  7889. {
  7890. case '0':
  7891. {
  7892. add(current);
  7893. goto scan_number_zero;
  7894. }
  7895. case '1':
  7896. case '2':
  7897. case '3':
  7898. case '4':
  7899. case '5':
  7900. case '6':
  7901. case '7':
  7902. case '8':
  7903. case '9':
  7904. {
  7905. add(current);
  7906. goto scan_number_any1;
  7907. }
  7908. default:
  7909. {
  7910. error_message = "invalid number; expected digit after '-'";
  7911. return token_type::parse_error;
  7912. }
  7913. }
  7914. scan_number_zero:
  7915. // state: we just parse a zero (maybe with a leading minus sign)
  7916. switch (get())
  7917. {
  7918. case '.':
  7919. {
  7920. add(decimal_point_char);
  7921. goto scan_number_decimal1;
  7922. }
  7923. case 'e':
  7924. case 'E':
  7925. {
  7926. add(current);
  7927. goto scan_number_exponent;
  7928. }
  7929. default:
  7930. goto scan_number_done;
  7931. }
  7932. scan_number_any1:
  7933. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  7934. switch (get())
  7935. {
  7936. case '0':
  7937. case '1':
  7938. case '2':
  7939. case '3':
  7940. case '4':
  7941. case '5':
  7942. case '6':
  7943. case '7':
  7944. case '8':
  7945. case '9':
  7946. {
  7947. add(current);
  7948. goto scan_number_any1;
  7949. }
  7950. case '.':
  7951. {
  7952. add(decimal_point_char);
  7953. goto scan_number_decimal1;
  7954. }
  7955. case 'e':
  7956. case 'E':
  7957. {
  7958. add(current);
  7959. goto scan_number_exponent;
  7960. }
  7961. default:
  7962. goto scan_number_done;
  7963. }
  7964. scan_number_decimal1:
  7965. // state: we just parsed a decimal point
  7966. number_type = token_type::value_float;
  7967. switch (get())
  7968. {
  7969. case '0':
  7970. case '1':
  7971. case '2':
  7972. case '3':
  7973. case '4':
  7974. case '5':
  7975. case '6':
  7976. case '7':
  7977. case '8':
  7978. case '9':
  7979. {
  7980. add(current);
  7981. goto scan_number_decimal2;
  7982. }
  7983. default:
  7984. {
  7985. error_message = "invalid number; expected digit after '.'";
  7986. return token_type::parse_error;
  7987. }
  7988. }
  7989. scan_number_decimal2:
  7990. // we just parsed at least one number after a decimal point
  7991. switch (get())
  7992. {
  7993. case '0':
  7994. case '1':
  7995. case '2':
  7996. case '3':
  7997. case '4':
  7998. case '5':
  7999. case '6':
  8000. case '7':
  8001. case '8':
  8002. case '9':
  8003. {
  8004. add(current);
  8005. goto scan_number_decimal2;
  8006. }
  8007. case 'e':
  8008. case 'E':
  8009. {
  8010. add(current);
  8011. goto scan_number_exponent;
  8012. }
  8013. default:
  8014. goto scan_number_done;
  8015. }
  8016. scan_number_exponent:
  8017. // we just parsed an exponent
  8018. number_type = token_type::value_float;
  8019. switch (get())
  8020. {
  8021. case '+':
  8022. case '-':
  8023. {
  8024. add(current);
  8025. goto scan_number_sign;
  8026. }
  8027. case '0':
  8028. case '1':
  8029. case '2':
  8030. case '3':
  8031. case '4':
  8032. case '5':
  8033. case '6':
  8034. case '7':
  8035. case '8':
  8036. case '9':
  8037. {
  8038. add(current);
  8039. goto scan_number_any2;
  8040. }
  8041. default:
  8042. {
  8043. error_message =
  8044. "invalid number; expected '+', '-', or digit after exponent";
  8045. return token_type::parse_error;
  8046. }
  8047. }
  8048. scan_number_sign:
  8049. // we just parsed an exponent sign
  8050. switch (get())
  8051. {
  8052. case '0':
  8053. case '1':
  8054. case '2':
  8055. case '3':
  8056. case '4':
  8057. case '5':
  8058. case '6':
  8059. case '7':
  8060. case '8':
  8061. case '9':
  8062. {
  8063. add(current);
  8064. goto scan_number_any2;
  8065. }
  8066. default:
  8067. {
  8068. error_message = "invalid number; expected digit after exponent sign";
  8069. return token_type::parse_error;
  8070. }
  8071. }
  8072. scan_number_any2:
  8073. // we just parsed a number after the exponent or exponent sign
  8074. switch (get())
  8075. {
  8076. case '0':
  8077. case '1':
  8078. case '2':
  8079. case '3':
  8080. case '4':
  8081. case '5':
  8082. case '6':
  8083. case '7':
  8084. case '8':
  8085. case '9':
  8086. {
  8087. add(current);
  8088. goto scan_number_any2;
  8089. }
  8090. default:
  8091. goto scan_number_done;
  8092. }
  8093. scan_number_done:
  8094. // unget the character after the number (we only read it to know that
  8095. // we are done scanning a number)
  8096. unget();
  8097. char* endptr = nullptr;
  8098. errno = 0;
  8099. // try to parse integers first and fall back to floats
  8100. if (number_type == token_type::value_unsigned)
  8101. {
  8102. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  8103. // we checked the number format before
  8104. assert(endptr == token_buffer.data() + token_buffer.size());
  8105. if (errno == 0)
  8106. {
  8107. value_unsigned = static_cast<number_unsigned_t>(x);
  8108. if (value_unsigned == x)
  8109. {
  8110. return token_type::value_unsigned;
  8111. }
  8112. }
  8113. }
  8114. else if (number_type == token_type::value_integer)
  8115. {
  8116. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  8117. // we checked the number format before
  8118. assert(endptr == token_buffer.data() + token_buffer.size());
  8119. if (errno == 0)
  8120. {
  8121. value_integer = static_cast<number_integer_t>(x);
  8122. if (value_integer == x)
  8123. {
  8124. return token_type::value_integer;
  8125. }
  8126. }
  8127. }
  8128. // this code is reached if we parse a floating-point number or if an
  8129. // integer conversion above failed
  8130. strtof(value_float, token_buffer.data(), &endptr);
  8131. // we checked the number format before
  8132. assert(endptr == token_buffer.data() + token_buffer.size());
  8133. return token_type::value_float;
  8134. }
  8135. /*!
  8136. @param[in] literal_text the literal text to expect
  8137. @param[in] length the length of the passed literal text
  8138. @param[in] return_type the token type to return on success
  8139. */
  8140. JSON_HEDLEY_NON_NULL(2)
  8141. token_type scan_literal(const char* literal_text, const std::size_t length,
  8142. token_type return_type)
  8143. {
  8144. assert(current == literal_text[0]);
  8145. for (std::size_t i = 1; i < length; ++i)
  8146. {
  8147. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  8148. {
  8149. error_message = "invalid literal";
  8150. return token_type::parse_error;
  8151. }
  8152. }
  8153. return return_type;
  8154. }
  8155. /////////////////////
  8156. // input management
  8157. /////////////////////
  8158. /// reset token_buffer; current character is beginning of token
  8159. void reset() noexcept
  8160. {
  8161. token_buffer.clear();
  8162. token_string.clear();
  8163. token_string.push_back(std::char_traits<char>::to_char_type(current));
  8164. }
  8165. /*
  8166. @brief get next character from the input
  8167. This function provides the interface to the used input adapter. It does
  8168. not throw in case the input reached EOF, but returns a
  8169. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  8170. for use in error messages.
  8171. @return character read from the input
  8172. */
  8173. std::char_traits<char>::int_type get()
  8174. {
  8175. ++position.chars_read_total;
  8176. ++position.chars_read_current_line;
  8177. if (next_unget)
  8178. {
  8179. // just reset the next_unget variable and work with current
  8180. next_unget = false;
  8181. }
  8182. else
  8183. {
  8184. current = ia.get_character();
  8185. }
  8186. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  8187. {
  8188. token_string.push_back(std::char_traits<char>::to_char_type(current));
  8189. }
  8190. if (current == '\n')
  8191. {
  8192. ++position.lines_read;
  8193. position.chars_read_current_line = 0;
  8194. }
  8195. return current;
  8196. }
  8197. /*!
  8198. @brief unget current character (read it again on next get)
  8199. We implement unget by setting variable next_unget to true. The input is not
  8200. changed - we just simulate ungetting by modifying chars_read_total,
  8201. chars_read_current_line, and token_string. The next call to get() will
  8202. behave as if the unget character is read again.
  8203. */
  8204. void unget()
  8205. {
  8206. next_unget = true;
  8207. --position.chars_read_total;
  8208. // in case we "unget" a newline, we have to also decrement the lines_read
  8209. if (position.chars_read_current_line == 0)
  8210. {
  8211. if (position.lines_read > 0)
  8212. {
  8213. --position.lines_read;
  8214. }
  8215. }
  8216. else
  8217. {
  8218. --position.chars_read_current_line;
  8219. }
  8220. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  8221. {
  8222. assert(not token_string.empty());
  8223. token_string.pop_back();
  8224. }
  8225. }
  8226. /// add a character to token_buffer
  8227. void add(int c)
  8228. {
  8229. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  8230. }
  8231. public:
  8232. /////////////////////
  8233. // value getters
  8234. /////////////////////
  8235. /// return integer value
  8236. constexpr number_integer_t get_number_integer() const noexcept
  8237. {
  8238. return value_integer;
  8239. }
  8240. /// return unsigned integer value
  8241. constexpr number_unsigned_t get_number_unsigned() const noexcept
  8242. {
  8243. return value_unsigned;
  8244. }
  8245. /// return floating-point value
  8246. constexpr number_float_t get_number_float() const noexcept
  8247. {
  8248. return value_float;
  8249. }
  8250. /// return current string value (implicitly resets the token; useful only once)
  8251. string_t& get_string()
  8252. {
  8253. return token_buffer;
  8254. }
  8255. /////////////////////
  8256. // diagnostics
  8257. /////////////////////
  8258. /// return position of last read token
  8259. constexpr position_t get_position() const noexcept
  8260. {
  8261. return position;
  8262. }
  8263. /// return the last read token (for errors only). Will never contain EOF
  8264. /// (an arbitrary value that is not a valid char value, often -1), because
  8265. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  8266. std::string get_token_string() const
  8267. {
  8268. // escape control characters
  8269. std::string result;
  8270. for (const auto c : token_string)
  8271. {
  8272. if (static_cast<unsigned char>(c) <= '\x1F')
  8273. {
  8274. // escape control characters
  8275. std::array<char, 9> cs{{}};
  8276. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  8277. result += cs.data();
  8278. }
  8279. else
  8280. {
  8281. // add character as is
  8282. result.push_back(c);
  8283. }
  8284. }
  8285. return result;
  8286. }
  8287. /// return syntax error message
  8288. JSON_HEDLEY_RETURNS_NON_NULL
  8289. constexpr const char* get_error_message() const noexcept
  8290. {
  8291. return error_message;
  8292. }
  8293. /////////////////////
  8294. // actual scanner
  8295. /////////////////////
  8296. /*!
  8297. @brief skip the UTF-8 byte order mark
  8298. @return true iff there is no BOM or the correct BOM has been skipped
  8299. */
  8300. bool skip_bom()
  8301. {
  8302. if (get() == 0xEF)
  8303. {
  8304. // check if we completely parse the BOM
  8305. return get() == 0xBB and get() == 0xBF;
  8306. }
  8307. // the first character is not the beginning of the BOM; unget it to
  8308. // process is later
  8309. unget();
  8310. return true;
  8311. }
  8312. token_type scan()
  8313. {
  8314. // initially, skip the BOM
  8315. if (position.chars_read_total == 0 and not skip_bom())
  8316. {
  8317. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  8318. return token_type::parse_error;
  8319. }
  8320. // read next character and ignore whitespace
  8321. do
  8322. {
  8323. get();
  8324. }
  8325. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  8326. switch (current)
  8327. {
  8328. // structural characters
  8329. case '[':
  8330. return token_type::begin_array;
  8331. case ']':
  8332. return token_type::end_array;
  8333. case '{':
  8334. return token_type::begin_object;
  8335. case '}':
  8336. return token_type::end_object;
  8337. case ':':
  8338. return token_type::name_separator;
  8339. case ',':
  8340. return token_type::value_separator;
  8341. // literals
  8342. case 't':
  8343. return scan_literal("true", 4, token_type::literal_true);
  8344. case 'f':
  8345. return scan_literal("false", 5, token_type::literal_false);
  8346. case 'n':
  8347. return scan_literal("null", 4, token_type::literal_null);
  8348. // string
  8349. case '\"':
  8350. return scan_string();
  8351. // number
  8352. case '-':
  8353. case '0':
  8354. case '1':
  8355. case '2':
  8356. case '3':
  8357. case '4':
  8358. case '5':
  8359. case '6':
  8360. case '7':
  8361. case '8':
  8362. case '9':
  8363. return scan_number();
  8364. // end of input (the null byte is needed when parsing from
  8365. // string literals)
  8366. case '\0':
  8367. case std::char_traits<char>::eof():
  8368. return token_type::end_of_input;
  8369. // error
  8370. default:
  8371. error_message = "invalid literal";
  8372. return token_type::parse_error;
  8373. }
  8374. }
  8375. private:
  8376. /// input adapter
  8377. InputAdapterType ia;
  8378. /// the current character
  8379. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  8380. /// whether the next get() call should just return current
  8381. bool next_unget = false;
  8382. /// the start position of the current token
  8383. position_t position {};
  8384. /// raw input token string (for error messages)
  8385. std::vector<char> token_string {};
  8386. /// buffer for variable-length tokens (numbers, strings)
  8387. string_t token_buffer {};
  8388. /// a description of occurred lexer errors
  8389. const char* error_message = "";
  8390. // number values
  8391. number_integer_t value_integer = 0;
  8392. number_unsigned_t value_unsigned = 0;
  8393. number_float_t value_float = 0;
  8394. /// the decimal point
  8395. const char decimal_point_char = '.';
  8396. };
  8397. } // namespace detail
  8398. } // namespace nlohmann
  8399. // #include <nlohmann/detail/input/parser.hpp>
  8400. #include <cassert> // assert
  8401. #include <cmath> // isfinite
  8402. #include <cstdint> // uint8_t
  8403. #include <functional> // function
  8404. #include <string> // string
  8405. #include <utility> // move
  8406. #include <vector> // vector
  8407. // #include <nlohmann/detail/exceptions.hpp>
  8408. // #include <nlohmann/detail/input/input_adapters.hpp>
  8409. // #include <nlohmann/detail/input/json_sax.hpp>
  8410. // #include <nlohmann/detail/input/lexer.hpp>
  8411. // #include <nlohmann/detail/macro_scope.hpp>
  8412. // #include <nlohmann/detail/meta/is_sax.hpp>
  8413. // #include <nlohmann/detail/value_t.hpp>
  8414. namespace nlohmann
  8415. {
  8416. namespace detail
  8417. {
  8418. ////////////
  8419. // parser //
  8420. ////////////
  8421. enum class parse_event_t : uint8_t
  8422. {
  8423. /// the parser read `{` and started to process a JSON object
  8424. object_start,
  8425. /// the parser read `}` and finished processing a JSON object
  8426. object_end,
  8427. /// the parser read `[` and started to process a JSON array
  8428. array_start,
  8429. /// the parser read `]` and finished processing a JSON array
  8430. array_end,
  8431. /// the parser read a key of a value in an object
  8432. key,
  8433. /// the parser finished reading a JSON value
  8434. value
  8435. };
  8436. template<typename BasicJsonType>
  8437. using parser_callback_t =
  8438. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  8439. /*!
  8440. @brief syntax analysis
  8441. This class implements a recursive descent parser.
  8442. */
  8443. template<typename BasicJsonType, typename InputAdapterType>
  8444. class parser
  8445. {
  8446. using number_integer_t = typename BasicJsonType::number_integer_t;
  8447. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  8448. using number_float_t = typename BasicJsonType::number_float_t;
  8449. using string_t = typename BasicJsonType::string_t;
  8450. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  8451. using token_type = typename lexer_t::token_type;
  8452. public:
  8453. /// a parser reading from an input adapter
  8454. explicit parser(InputAdapterType&& adapter,
  8455. const parser_callback_t<BasicJsonType> cb = nullptr,
  8456. const bool allow_exceptions_ = true)
  8457. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  8458. {
  8459. // read first token
  8460. get_token();
  8461. }
  8462. /*!
  8463. @brief public parser interface
  8464. @param[in] strict whether to expect the last token to be EOF
  8465. @param[in,out] result parsed JSON value
  8466. @throw parse_error.101 in case of an unexpected token
  8467. @throw parse_error.102 if to_unicode fails or surrogate error
  8468. @throw parse_error.103 if to_unicode fails
  8469. */
  8470. void parse(const bool strict, BasicJsonType& result)
  8471. {
  8472. if (callback)
  8473. {
  8474. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  8475. sax_parse_internal(&sdp);
  8476. result.assert_invariant();
  8477. // in strict mode, input must be completely read
  8478. if (strict and (get_token() != token_type::end_of_input))
  8479. {
  8480. sdp.parse_error(m_lexer.get_position(),
  8481. m_lexer.get_token_string(),
  8482. parse_error::create(101, m_lexer.get_position(),
  8483. exception_message(token_type::end_of_input, "value")));
  8484. }
  8485. // in case of an error, return discarded value
  8486. if (sdp.is_errored())
  8487. {
  8488. result = value_t::discarded;
  8489. return;
  8490. }
  8491. // set top-level value to null if it was discarded by the callback
  8492. // function
  8493. if (result.is_discarded())
  8494. {
  8495. result = nullptr;
  8496. }
  8497. }
  8498. else
  8499. {
  8500. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  8501. sax_parse_internal(&sdp);
  8502. result.assert_invariant();
  8503. // in strict mode, input must be completely read
  8504. if (strict and (get_token() != token_type::end_of_input))
  8505. {
  8506. sdp.parse_error(m_lexer.get_position(),
  8507. m_lexer.get_token_string(),
  8508. parse_error::create(101, m_lexer.get_position(),
  8509. exception_message(token_type::end_of_input, "value")));
  8510. }
  8511. // in case of an error, return discarded value
  8512. if (sdp.is_errored())
  8513. {
  8514. result = value_t::discarded;
  8515. return;
  8516. }
  8517. }
  8518. }
  8519. /*!
  8520. @brief public accept interface
  8521. @param[in] strict whether to expect the last token to be EOF
  8522. @return whether the input is a proper JSON text
  8523. */
  8524. bool accept(const bool strict = true)
  8525. {
  8526. json_sax_acceptor<BasicJsonType> sax_acceptor;
  8527. return sax_parse(&sax_acceptor, strict);
  8528. }
  8529. template <typename SAX>
  8530. JSON_HEDLEY_NON_NULL(2)
  8531. bool sax_parse(SAX* sax, const bool strict = true)
  8532. {
  8533. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  8534. const bool result = sax_parse_internal(sax);
  8535. // strict mode: next byte must be EOF
  8536. if (result and strict and (get_token() != token_type::end_of_input))
  8537. {
  8538. return sax->parse_error(m_lexer.get_position(),
  8539. m_lexer.get_token_string(),
  8540. parse_error::create(101, m_lexer.get_position(),
  8541. exception_message(token_type::end_of_input, "value")));
  8542. }
  8543. return result;
  8544. }
  8545. private:
  8546. template <typename SAX>
  8547. JSON_HEDLEY_NON_NULL(2)
  8548. bool sax_parse_internal(SAX* sax)
  8549. {
  8550. // stack to remember the hierarchy of structured values we are parsing
  8551. // true = array; false = object
  8552. std::vector<bool> states;
  8553. // value to avoid a goto (see comment where set to true)
  8554. bool skip_to_state_evaluation = false;
  8555. while (true)
  8556. {
  8557. if (not skip_to_state_evaluation)
  8558. {
  8559. // invariant: get_token() was called before each iteration
  8560. switch (last_token)
  8561. {
  8562. case token_type::begin_object:
  8563. {
  8564. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  8565. {
  8566. return false;
  8567. }
  8568. // closing } -> we are done
  8569. if (get_token() == token_type::end_object)
  8570. {
  8571. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  8572. {
  8573. return false;
  8574. }
  8575. break;
  8576. }
  8577. // parse key
  8578. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  8579. {
  8580. return sax->parse_error(m_lexer.get_position(),
  8581. m_lexer.get_token_string(),
  8582. parse_error::create(101, m_lexer.get_position(),
  8583. exception_message(token_type::value_string, "object key")));
  8584. }
  8585. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  8586. {
  8587. return false;
  8588. }
  8589. // parse separator (:)
  8590. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8591. {
  8592. return sax->parse_error(m_lexer.get_position(),
  8593. m_lexer.get_token_string(),
  8594. parse_error::create(101, m_lexer.get_position(),
  8595. exception_message(token_type::name_separator, "object separator")));
  8596. }
  8597. // remember we are now inside an object
  8598. states.push_back(false);
  8599. // parse values
  8600. get_token();
  8601. continue;
  8602. }
  8603. case token_type::begin_array:
  8604. {
  8605. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  8606. {
  8607. return false;
  8608. }
  8609. // closing ] -> we are done
  8610. if (get_token() == token_type::end_array)
  8611. {
  8612. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  8613. {
  8614. return false;
  8615. }
  8616. break;
  8617. }
  8618. // remember we are now inside an array
  8619. states.push_back(true);
  8620. // parse values (no need to call get_token)
  8621. continue;
  8622. }
  8623. case token_type::value_float:
  8624. {
  8625. const auto res = m_lexer.get_number_float();
  8626. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  8627. {
  8628. return sax->parse_error(m_lexer.get_position(),
  8629. m_lexer.get_token_string(),
  8630. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  8631. }
  8632. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  8633. {
  8634. return false;
  8635. }
  8636. break;
  8637. }
  8638. case token_type::literal_false:
  8639. {
  8640. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  8641. {
  8642. return false;
  8643. }
  8644. break;
  8645. }
  8646. case token_type::literal_null:
  8647. {
  8648. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  8649. {
  8650. return false;
  8651. }
  8652. break;
  8653. }
  8654. case token_type::literal_true:
  8655. {
  8656. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  8657. {
  8658. return false;
  8659. }
  8660. break;
  8661. }
  8662. case token_type::value_integer:
  8663. {
  8664. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  8665. {
  8666. return false;
  8667. }
  8668. break;
  8669. }
  8670. case token_type::value_string:
  8671. {
  8672. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  8673. {
  8674. return false;
  8675. }
  8676. break;
  8677. }
  8678. case token_type::value_unsigned:
  8679. {
  8680. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  8681. {
  8682. return false;
  8683. }
  8684. break;
  8685. }
  8686. case token_type::parse_error:
  8687. {
  8688. // using "uninitialized" to avoid "expected" message
  8689. return sax->parse_error(m_lexer.get_position(),
  8690. m_lexer.get_token_string(),
  8691. parse_error::create(101, m_lexer.get_position(),
  8692. exception_message(token_type::uninitialized, "value")));
  8693. }
  8694. default: // the last token was unexpected
  8695. {
  8696. return sax->parse_error(m_lexer.get_position(),
  8697. m_lexer.get_token_string(),
  8698. parse_error::create(101, m_lexer.get_position(),
  8699. exception_message(token_type::literal_or_value, "value")));
  8700. }
  8701. }
  8702. }
  8703. else
  8704. {
  8705. skip_to_state_evaluation = false;
  8706. }
  8707. // we reached this line after we successfully parsed a value
  8708. if (states.empty())
  8709. {
  8710. // empty stack: we reached the end of the hierarchy: done
  8711. return true;
  8712. }
  8713. if (states.back()) // array
  8714. {
  8715. // comma -> next value
  8716. if (get_token() == token_type::value_separator)
  8717. {
  8718. // parse a new value
  8719. get_token();
  8720. continue;
  8721. }
  8722. // closing ]
  8723. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  8724. {
  8725. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  8726. {
  8727. return false;
  8728. }
  8729. // We are done with this array. Before we can parse a
  8730. // new value, we need to evaluate the new state first.
  8731. // By setting skip_to_state_evaluation to false, we
  8732. // are effectively jumping to the beginning of this if.
  8733. assert(not states.empty());
  8734. states.pop_back();
  8735. skip_to_state_evaluation = true;
  8736. continue;
  8737. }
  8738. return sax->parse_error(m_lexer.get_position(),
  8739. m_lexer.get_token_string(),
  8740. parse_error::create(101, m_lexer.get_position(),
  8741. exception_message(token_type::end_array, "array")));
  8742. }
  8743. else // object
  8744. {
  8745. // comma -> next value
  8746. if (get_token() == token_type::value_separator)
  8747. {
  8748. // parse key
  8749. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  8750. {
  8751. return sax->parse_error(m_lexer.get_position(),
  8752. m_lexer.get_token_string(),
  8753. parse_error::create(101, m_lexer.get_position(),
  8754. exception_message(token_type::value_string, "object key")));
  8755. }
  8756. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  8757. {
  8758. return false;
  8759. }
  8760. // parse separator (:)
  8761. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8762. {
  8763. return sax->parse_error(m_lexer.get_position(),
  8764. m_lexer.get_token_string(),
  8765. parse_error::create(101, m_lexer.get_position(),
  8766. exception_message(token_type::name_separator, "object separator")));
  8767. }
  8768. // parse values
  8769. get_token();
  8770. continue;
  8771. }
  8772. // closing }
  8773. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  8774. {
  8775. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  8776. {
  8777. return false;
  8778. }
  8779. // We are done with this object. Before we can parse a
  8780. // new value, we need to evaluate the new state first.
  8781. // By setting skip_to_state_evaluation to false, we
  8782. // are effectively jumping to the beginning of this if.
  8783. assert(not states.empty());
  8784. states.pop_back();
  8785. skip_to_state_evaluation = true;
  8786. continue;
  8787. }
  8788. return sax->parse_error(m_lexer.get_position(),
  8789. m_lexer.get_token_string(),
  8790. parse_error::create(101, m_lexer.get_position(),
  8791. exception_message(token_type::end_object, "object")));
  8792. }
  8793. }
  8794. }
  8795. /// get next token from lexer
  8796. token_type get_token()
  8797. {
  8798. return last_token = m_lexer.scan();
  8799. }
  8800. std::string exception_message(const token_type expected, const std::string& context)
  8801. {
  8802. std::string error_msg = "syntax error ";
  8803. if (not context.empty())
  8804. {
  8805. error_msg += "while parsing " + context + " ";
  8806. }
  8807. error_msg += "- ";
  8808. if (last_token == token_type::parse_error)
  8809. {
  8810. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  8811. m_lexer.get_token_string() + "'";
  8812. }
  8813. else
  8814. {
  8815. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  8816. }
  8817. if (expected != token_type::uninitialized)
  8818. {
  8819. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  8820. }
  8821. return error_msg;
  8822. }
  8823. private:
  8824. /// callback function
  8825. const parser_callback_t<BasicJsonType> callback = nullptr;
  8826. /// the type of the last read token
  8827. token_type last_token = token_type::uninitialized;
  8828. /// the lexer
  8829. lexer_t m_lexer;
  8830. /// whether to throw exceptions in case of errors
  8831. const bool allow_exceptions = true;
  8832. };
  8833. } // namespace detail
  8834. } // namespace nlohmann
  8835. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8836. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8837. #include <cstddef> // ptrdiff_t
  8838. #include <limits> // numeric_limits
  8839. namespace nlohmann
  8840. {
  8841. namespace detail
  8842. {
  8843. /*
  8844. @brief an iterator for primitive JSON types
  8845. This class models an iterator for primitive JSON types (boolean, number,
  8846. string). It's only purpose is to allow the iterator/const_iterator classes
  8847. to "iterate" over primitive values. Internally, the iterator is modeled by
  8848. a `difference_type` variable. Value begin_value (`0`) models the begin,
  8849. end_value (`1`) models past the end.
  8850. */
  8851. class primitive_iterator_t
  8852. {
  8853. private:
  8854. using difference_type = std::ptrdiff_t;
  8855. static constexpr difference_type begin_value = 0;
  8856. static constexpr difference_type end_value = begin_value + 1;
  8857. /// iterator as signed integer type
  8858. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  8859. public:
  8860. constexpr difference_type get_value() const noexcept
  8861. {
  8862. return m_it;
  8863. }
  8864. /// set iterator to a defined beginning
  8865. void set_begin() noexcept
  8866. {
  8867. m_it = begin_value;
  8868. }
  8869. /// set iterator to a defined past the end
  8870. void set_end() noexcept
  8871. {
  8872. m_it = end_value;
  8873. }
  8874. /// return whether the iterator can be dereferenced
  8875. constexpr bool is_begin() const noexcept
  8876. {
  8877. return m_it == begin_value;
  8878. }
  8879. /// return whether the iterator is at end
  8880. constexpr bool is_end() const noexcept
  8881. {
  8882. return m_it == end_value;
  8883. }
  8884. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8885. {
  8886. return lhs.m_it == rhs.m_it;
  8887. }
  8888. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8889. {
  8890. return lhs.m_it < rhs.m_it;
  8891. }
  8892. primitive_iterator_t operator+(difference_type n) noexcept
  8893. {
  8894. auto result = *this;
  8895. result += n;
  8896. return result;
  8897. }
  8898. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8899. {
  8900. return lhs.m_it - rhs.m_it;
  8901. }
  8902. primitive_iterator_t& operator++() noexcept
  8903. {
  8904. ++m_it;
  8905. return *this;
  8906. }
  8907. primitive_iterator_t const operator++(int) noexcept
  8908. {
  8909. auto result = *this;
  8910. ++m_it;
  8911. return result;
  8912. }
  8913. primitive_iterator_t& operator--() noexcept
  8914. {
  8915. --m_it;
  8916. return *this;
  8917. }
  8918. primitive_iterator_t const operator--(int) noexcept
  8919. {
  8920. auto result = *this;
  8921. --m_it;
  8922. return result;
  8923. }
  8924. primitive_iterator_t& operator+=(difference_type n) noexcept
  8925. {
  8926. m_it += n;
  8927. return *this;
  8928. }
  8929. primitive_iterator_t& operator-=(difference_type n) noexcept
  8930. {
  8931. m_it -= n;
  8932. return *this;
  8933. }
  8934. };
  8935. } // namespace detail
  8936. } // namespace nlohmann
  8937. namespace nlohmann
  8938. {
  8939. namespace detail
  8940. {
  8941. /*!
  8942. @brief an iterator value
  8943. @note This structure could easily be a union, but MSVC currently does not allow
  8944. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  8945. */
  8946. template<typename BasicJsonType> struct internal_iterator
  8947. {
  8948. /// iterator for JSON objects
  8949. typename BasicJsonType::object_t::iterator object_iterator {};
  8950. /// iterator for JSON arrays
  8951. typename BasicJsonType::array_t::iterator array_iterator {};
  8952. /// iterator for JSON binary arrays
  8953. typename BasicJsonType::binary_t::container_type::iterator binary_iterator {};
  8954. /// generic iterator for all other types
  8955. primitive_iterator_t primitive_iterator {};
  8956. };
  8957. } // namespace detail
  8958. } // namespace nlohmann
  8959. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8960. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8961. #include <type_traits> // conditional, is_const, remove_const
  8962. // #include <nlohmann/detail/boolean_operators.hpp>
  8963. // #include <nlohmann/detail/exceptions.hpp>
  8964. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8965. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8966. // #include <nlohmann/detail/macro_scope.hpp>
  8967. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8968. // #include <nlohmann/detail/meta/type_traits.hpp>
  8969. // #include <nlohmann/detail/value_t.hpp>
  8970. namespace nlohmann
  8971. {
  8972. namespace detail
  8973. {
  8974. // forward declare, to be able to friend it later on
  8975. template<typename IteratorType> class iteration_proxy;
  8976. template<typename IteratorType> class iteration_proxy_value;
  8977. /*!
  8978. @brief a template for a bidirectional iterator for the @ref basic_json class
  8979. This class implements a both iterators (iterator and const_iterator) for the
  8980. @ref basic_json class.
  8981. @note An iterator is called *initialized* when a pointer to a JSON value has
  8982. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8983. default-constructed, it is *uninitialized* and most methods are undefined.
  8984. **The library uses assertions to detect calls on uninitialized iterators.**
  8985. @requirement The class satisfies the following concept requirements:
  8986. -
  8987. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8988. The iterator that can be moved can be moved in both directions (i.e.
  8989. incremented and decremented).
  8990. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8991. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8992. */
  8993. template<typename BasicJsonType>
  8994. class iter_impl
  8995. {
  8996. /// allow basic_json to access private members
  8997. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8998. friend BasicJsonType;
  8999. friend iteration_proxy<iter_impl>;
  9000. friend iteration_proxy_value<iter_impl>;
  9001. using object_t = typename BasicJsonType::object_t;
  9002. using array_t = typename BasicJsonType::array_t;
  9003. // make sure BasicJsonType is basic_json or const basic_json
  9004. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  9005. "iter_impl only accepts (const) basic_json");
  9006. public:
  9007. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  9008. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  9009. /// A user-defined iterator should provide publicly accessible typedefs named
  9010. /// iterator_category, value_type, difference_type, pointer, and reference.
  9011. /// Note that value_type is required to be non-const, even for constant iterators.
  9012. using iterator_category = std::bidirectional_iterator_tag;
  9013. /// the type of the values when the iterator is dereferenced
  9014. using value_type = typename BasicJsonType::value_type;
  9015. /// a type to represent differences between iterators
  9016. using difference_type = typename BasicJsonType::difference_type;
  9017. /// defines a pointer to the type iterated over (value_type)
  9018. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  9019. typename BasicJsonType::const_pointer,
  9020. typename BasicJsonType::pointer>::type;
  9021. /// defines a reference to the type iterated over (value_type)
  9022. using reference =
  9023. typename std::conditional<std::is_const<BasicJsonType>::value,
  9024. typename BasicJsonType::const_reference,
  9025. typename BasicJsonType::reference>::type;
  9026. /// default constructor
  9027. iter_impl() = default;
  9028. /*!
  9029. @brief constructor for a given JSON instance
  9030. @param[in] object pointer to a JSON object for this iterator
  9031. @pre object != nullptr
  9032. @post The iterator is initialized; i.e. `m_object != nullptr`.
  9033. */
  9034. explicit iter_impl(pointer object) noexcept : m_object(object)
  9035. {
  9036. assert(m_object != nullptr);
  9037. switch (m_object->m_type)
  9038. {
  9039. case value_t::object:
  9040. {
  9041. m_it.object_iterator = typename object_t::iterator();
  9042. break;
  9043. }
  9044. case value_t::array:
  9045. {
  9046. m_it.array_iterator = typename array_t::iterator();
  9047. break;
  9048. }
  9049. default:
  9050. {
  9051. m_it.primitive_iterator = primitive_iterator_t();
  9052. break;
  9053. }
  9054. }
  9055. }
  9056. /*!
  9057. @note The conventional copy constructor and copy assignment are implicitly
  9058. defined. Combined with the following converting constructor and
  9059. assignment, they support: (1) copy from iterator to iterator, (2)
  9060. copy from const iterator to const iterator, and (3) conversion from
  9061. iterator to const iterator. However conversion from const iterator
  9062. to iterator is not defined.
  9063. */
  9064. /*!
  9065. @brief const copy constructor
  9066. @param[in] other const iterator to copy from
  9067. @note This copy constructor had to be defined explicitly to circumvent a bug
  9068. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  9069. information refer to: https://github.com/nlohmann/json/issues/1608
  9070. */
  9071. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  9072. : m_object(other.m_object), m_it(other.m_it)
  9073. {}
  9074. /*!
  9075. @brief converting assignment
  9076. @param[in] other const iterator to copy from
  9077. @return const/non-const iterator
  9078. @note It is not checked whether @a other is initialized.
  9079. */
  9080. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  9081. {
  9082. m_object = other.m_object;
  9083. m_it = other.m_it;
  9084. return *this;
  9085. }
  9086. /*!
  9087. @brief converting constructor
  9088. @param[in] other non-const iterator to copy from
  9089. @note It is not checked whether @a other is initialized.
  9090. */
  9091. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  9092. : m_object(other.m_object), m_it(other.m_it)
  9093. {}
  9094. /*!
  9095. @brief converting assignment
  9096. @param[in] other non-const iterator to copy from
  9097. @return const/non-const iterator
  9098. @note It is not checked whether @a other is initialized.
  9099. */
  9100. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  9101. {
  9102. m_object = other.m_object;
  9103. m_it = other.m_it;
  9104. return *this;
  9105. }
  9106. private:
  9107. /*!
  9108. @brief set the iterator to the first value
  9109. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9110. */
  9111. void set_begin() noexcept
  9112. {
  9113. assert(m_object != nullptr);
  9114. switch (m_object->m_type)
  9115. {
  9116. case value_t::object:
  9117. {
  9118. m_it.object_iterator = m_object->m_value.object->begin();
  9119. break;
  9120. }
  9121. case value_t::array:
  9122. {
  9123. m_it.array_iterator = m_object->m_value.array->begin();
  9124. break;
  9125. }
  9126. case value_t::null:
  9127. {
  9128. // set to end so begin()==end() is true: null is empty
  9129. m_it.primitive_iterator.set_end();
  9130. break;
  9131. }
  9132. default:
  9133. {
  9134. m_it.primitive_iterator.set_begin();
  9135. break;
  9136. }
  9137. }
  9138. }
  9139. /*!
  9140. @brief set the iterator past the last value
  9141. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9142. */
  9143. void set_end() noexcept
  9144. {
  9145. assert(m_object != nullptr);
  9146. switch (m_object->m_type)
  9147. {
  9148. case value_t::object:
  9149. {
  9150. m_it.object_iterator = m_object->m_value.object->end();
  9151. break;
  9152. }
  9153. case value_t::array:
  9154. {
  9155. m_it.array_iterator = m_object->m_value.array->end();
  9156. break;
  9157. }
  9158. default:
  9159. {
  9160. m_it.primitive_iterator.set_end();
  9161. break;
  9162. }
  9163. }
  9164. }
  9165. public:
  9166. /*!
  9167. @brief return a reference to the value pointed to by the iterator
  9168. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9169. */
  9170. reference operator*() const
  9171. {
  9172. assert(m_object != nullptr);
  9173. switch (m_object->m_type)
  9174. {
  9175. case value_t::object:
  9176. {
  9177. assert(m_it.object_iterator != m_object->m_value.object->end());
  9178. return m_it.object_iterator->second;
  9179. }
  9180. case value_t::array:
  9181. {
  9182. assert(m_it.array_iterator != m_object->m_value.array->end());
  9183. return *m_it.array_iterator;
  9184. }
  9185. case value_t::null:
  9186. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9187. default:
  9188. {
  9189. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9190. {
  9191. return *m_object;
  9192. }
  9193. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9194. }
  9195. }
  9196. }
  9197. /*!
  9198. @brief dereference the iterator
  9199. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9200. */
  9201. pointer operator->() const
  9202. {
  9203. assert(m_object != nullptr);
  9204. switch (m_object->m_type)
  9205. {
  9206. case value_t::object:
  9207. {
  9208. assert(m_it.object_iterator != m_object->m_value.object->end());
  9209. return &(m_it.object_iterator->second);
  9210. }
  9211. case value_t::array:
  9212. {
  9213. assert(m_it.array_iterator != m_object->m_value.array->end());
  9214. return &*m_it.array_iterator;
  9215. }
  9216. default:
  9217. {
  9218. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9219. {
  9220. return m_object;
  9221. }
  9222. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9223. }
  9224. }
  9225. }
  9226. /*!
  9227. @brief post-increment (it++)
  9228. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9229. */
  9230. iter_impl const operator++(int)
  9231. {
  9232. auto result = *this;
  9233. ++(*this);
  9234. return result;
  9235. }
  9236. /*!
  9237. @brief pre-increment (++it)
  9238. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9239. */
  9240. iter_impl& operator++()
  9241. {
  9242. assert(m_object != nullptr);
  9243. switch (m_object->m_type)
  9244. {
  9245. case value_t::object:
  9246. {
  9247. std::advance(m_it.object_iterator, 1);
  9248. break;
  9249. }
  9250. case value_t::array:
  9251. {
  9252. std::advance(m_it.array_iterator, 1);
  9253. break;
  9254. }
  9255. default:
  9256. {
  9257. ++m_it.primitive_iterator;
  9258. break;
  9259. }
  9260. }
  9261. return *this;
  9262. }
  9263. /*!
  9264. @brief post-decrement (it--)
  9265. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9266. */
  9267. iter_impl const operator--(int)
  9268. {
  9269. auto result = *this;
  9270. --(*this);
  9271. return result;
  9272. }
  9273. /*!
  9274. @brief pre-decrement (--it)
  9275. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9276. */
  9277. iter_impl& operator--()
  9278. {
  9279. assert(m_object != nullptr);
  9280. switch (m_object->m_type)
  9281. {
  9282. case value_t::object:
  9283. {
  9284. std::advance(m_it.object_iterator, -1);
  9285. break;
  9286. }
  9287. case value_t::array:
  9288. {
  9289. std::advance(m_it.array_iterator, -1);
  9290. break;
  9291. }
  9292. default:
  9293. {
  9294. --m_it.primitive_iterator;
  9295. break;
  9296. }
  9297. }
  9298. return *this;
  9299. }
  9300. /*!
  9301. @brief comparison: equal
  9302. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9303. */
  9304. bool operator==(const iter_impl& other) const
  9305. {
  9306. // if objects are not the same, the comparison is undefined
  9307. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9308. {
  9309. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9310. }
  9311. assert(m_object != nullptr);
  9312. switch (m_object->m_type)
  9313. {
  9314. case value_t::object:
  9315. return (m_it.object_iterator == other.m_it.object_iterator);
  9316. case value_t::array:
  9317. return (m_it.array_iterator == other.m_it.array_iterator);
  9318. default:
  9319. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  9320. }
  9321. }
  9322. /*!
  9323. @brief comparison: not equal
  9324. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9325. */
  9326. bool operator!=(const iter_impl& other) const
  9327. {
  9328. return not operator==(other);
  9329. }
  9330. /*!
  9331. @brief comparison: smaller
  9332. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9333. */
  9334. bool operator<(const iter_impl& other) const
  9335. {
  9336. // if objects are not the same, the comparison is undefined
  9337. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9338. {
  9339. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9340. }
  9341. assert(m_object != nullptr);
  9342. switch (m_object->m_type)
  9343. {
  9344. case value_t::object:
  9345. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  9346. case value_t::array:
  9347. return (m_it.array_iterator < other.m_it.array_iterator);
  9348. default:
  9349. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  9350. }
  9351. }
  9352. /*!
  9353. @brief comparison: less than or equal
  9354. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9355. */
  9356. bool operator<=(const iter_impl& other) const
  9357. {
  9358. return not other.operator < (*this);
  9359. }
  9360. /*!
  9361. @brief comparison: greater than
  9362. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9363. */
  9364. bool operator>(const iter_impl& other) const
  9365. {
  9366. return not operator<=(other);
  9367. }
  9368. /*!
  9369. @brief comparison: greater than or equal
  9370. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9371. */
  9372. bool operator>=(const iter_impl& other) const
  9373. {
  9374. return not operator<(other);
  9375. }
  9376. /*!
  9377. @brief add to iterator
  9378. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9379. */
  9380. iter_impl& operator+=(difference_type i)
  9381. {
  9382. assert(m_object != nullptr);
  9383. switch (m_object->m_type)
  9384. {
  9385. case value_t::object:
  9386. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9387. case value_t::array:
  9388. {
  9389. std::advance(m_it.array_iterator, i);
  9390. break;
  9391. }
  9392. default:
  9393. {
  9394. m_it.primitive_iterator += i;
  9395. break;
  9396. }
  9397. }
  9398. return *this;
  9399. }
  9400. /*!
  9401. @brief subtract from iterator
  9402. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9403. */
  9404. iter_impl& operator-=(difference_type i)
  9405. {
  9406. return operator+=(-i);
  9407. }
  9408. /*!
  9409. @brief add to iterator
  9410. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9411. */
  9412. iter_impl operator+(difference_type i) const
  9413. {
  9414. auto result = *this;
  9415. result += i;
  9416. return result;
  9417. }
  9418. /*!
  9419. @brief addition of distance and iterator
  9420. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9421. */
  9422. friend iter_impl operator+(difference_type i, const iter_impl& it)
  9423. {
  9424. auto result = it;
  9425. result += i;
  9426. return result;
  9427. }
  9428. /*!
  9429. @brief subtract from iterator
  9430. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9431. */
  9432. iter_impl operator-(difference_type i) const
  9433. {
  9434. auto result = *this;
  9435. result -= i;
  9436. return result;
  9437. }
  9438. /*!
  9439. @brief return difference
  9440. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9441. */
  9442. difference_type operator-(const iter_impl& other) const
  9443. {
  9444. assert(m_object != nullptr);
  9445. switch (m_object->m_type)
  9446. {
  9447. case value_t::object:
  9448. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9449. case value_t::array:
  9450. return m_it.array_iterator - other.m_it.array_iterator;
  9451. default:
  9452. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  9453. }
  9454. }
  9455. /*!
  9456. @brief access to successor
  9457. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9458. */
  9459. reference operator[](difference_type n) const
  9460. {
  9461. assert(m_object != nullptr);
  9462. switch (m_object->m_type)
  9463. {
  9464. case value_t::object:
  9465. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  9466. case value_t::array:
  9467. return *std::next(m_it.array_iterator, n);
  9468. case value_t::null:
  9469. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9470. default:
  9471. {
  9472. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  9473. {
  9474. return *m_object;
  9475. }
  9476. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9477. }
  9478. }
  9479. }
  9480. /*!
  9481. @brief return the key of an object iterator
  9482. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9483. */
  9484. const typename object_t::key_type& key() const
  9485. {
  9486. assert(m_object != nullptr);
  9487. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  9488. {
  9489. return m_it.object_iterator->first;
  9490. }
  9491. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  9492. }
  9493. /*!
  9494. @brief return the value of an iterator
  9495. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9496. */
  9497. reference value() const
  9498. {
  9499. return operator*();
  9500. }
  9501. private:
  9502. /// associated JSON instance
  9503. pointer m_object = nullptr;
  9504. /// the actual iterator of the associated instance
  9505. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  9506. };
  9507. } // namespace detail
  9508. } // namespace nlohmann
  9509. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  9510. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  9511. #include <cstddef> // ptrdiff_t
  9512. #include <iterator> // reverse_iterator
  9513. #include <utility> // declval
  9514. namespace nlohmann
  9515. {
  9516. namespace detail
  9517. {
  9518. //////////////////////
  9519. // reverse_iterator //
  9520. //////////////////////
  9521. /*!
  9522. @brief a template for a reverse iterator class
  9523. @tparam Base the base iterator type to reverse. Valid types are @ref
  9524. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  9525. create @ref const_reverse_iterator).
  9526. @requirement The class satisfies the following concept requirements:
  9527. -
  9528. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9529. The iterator that can be moved can be moved in both directions (i.e.
  9530. incremented and decremented).
  9531. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  9532. It is possible to write to the pointed-to element (only if @a Base is
  9533. @ref iterator).
  9534. @since version 1.0.0
  9535. */
  9536. template<typename Base>
  9537. class json_reverse_iterator : public std::reverse_iterator<Base>
  9538. {
  9539. public:
  9540. using difference_type = std::ptrdiff_t;
  9541. /// shortcut to the reverse iterator adapter
  9542. using base_iterator = std::reverse_iterator<Base>;
  9543. /// the reference type for the pointed-to element
  9544. using reference = typename Base::reference;
  9545. /// create reverse iterator from iterator
  9546. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  9547. : base_iterator(it) {}
  9548. /// create reverse iterator from base class
  9549. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  9550. /// post-increment (it++)
  9551. json_reverse_iterator const operator++(int)
  9552. {
  9553. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  9554. }
  9555. /// pre-increment (++it)
  9556. json_reverse_iterator& operator++()
  9557. {
  9558. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  9559. }
  9560. /// post-decrement (it--)
  9561. json_reverse_iterator const operator--(int)
  9562. {
  9563. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  9564. }
  9565. /// pre-decrement (--it)
  9566. json_reverse_iterator& operator--()
  9567. {
  9568. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  9569. }
  9570. /// add to iterator
  9571. json_reverse_iterator& operator+=(difference_type i)
  9572. {
  9573. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  9574. }
  9575. /// add to iterator
  9576. json_reverse_iterator operator+(difference_type i) const
  9577. {
  9578. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  9579. }
  9580. /// subtract from iterator
  9581. json_reverse_iterator operator-(difference_type i) const
  9582. {
  9583. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  9584. }
  9585. /// return difference
  9586. difference_type operator-(const json_reverse_iterator& other) const
  9587. {
  9588. return base_iterator(*this) - base_iterator(other);
  9589. }
  9590. /// access to successor
  9591. reference operator[](difference_type n) const
  9592. {
  9593. return *(this->operator+(n));
  9594. }
  9595. /// return the key of an object iterator
  9596. auto key() const -> decltype(std::declval<Base>().key())
  9597. {
  9598. auto it = --this->base();
  9599. return it.key();
  9600. }
  9601. /// return the value of an iterator
  9602. reference value() const
  9603. {
  9604. auto it = --this->base();
  9605. return it.operator * ();
  9606. }
  9607. };
  9608. } // namespace detail
  9609. } // namespace nlohmann
  9610. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9611. // #include <nlohmann/detail/json_pointer.hpp>
  9612. #include <algorithm> // all_of
  9613. #include <cassert> // assert
  9614. #include <cctype> // isdigit
  9615. #include <numeric> // accumulate
  9616. #include <string> // string
  9617. #include <utility> // move
  9618. #include <vector> // vector
  9619. // #include <nlohmann/detail/exceptions.hpp>
  9620. // #include <nlohmann/detail/macro_scope.hpp>
  9621. // #include <nlohmann/detail/value_t.hpp>
  9622. namespace nlohmann
  9623. {
  9624. template<typename BasicJsonType>
  9625. class json_pointer
  9626. {
  9627. // allow basic_json to access private members
  9628. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  9629. friend class basic_json;
  9630. public:
  9631. /*!
  9632. @brief create JSON pointer
  9633. Create a JSON pointer according to the syntax described in
  9634. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  9635. @param[in] s string representing the JSON pointer; if omitted, the empty
  9636. string is assumed which references the whole JSON value
  9637. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  9638. not begin with a slash (`/`); see example below
  9639. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  9640. not followed by `0` (representing `~`) or `1` (representing `/`); see
  9641. example below
  9642. @liveexample{The example shows the construction several valid JSON pointers
  9643. as well as the exceptional behavior.,json_pointer}
  9644. @since version 2.0.0
  9645. */
  9646. explicit json_pointer(const std::string& s = "")
  9647. : reference_tokens(split(s))
  9648. {}
  9649. /*!
  9650. @brief return a string representation of the JSON pointer
  9651. @invariant For each JSON pointer `ptr`, it holds:
  9652. @code {.cpp}
  9653. ptr == json_pointer(ptr.to_string());
  9654. @endcode
  9655. @return a string representation of the JSON pointer
  9656. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  9657. @since version 2.0.0
  9658. */
  9659. std::string to_string() const
  9660. {
  9661. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  9662. std::string{},
  9663. [](const std::string & a, const std::string & b)
  9664. {
  9665. return a + "/" + escape(b);
  9666. });
  9667. }
  9668. /// @copydoc to_string()
  9669. operator std::string() const
  9670. {
  9671. return to_string();
  9672. }
  9673. /*!
  9674. @brief append another JSON pointer at the end of this JSON pointer
  9675. @param[in] ptr JSON pointer to append
  9676. @return JSON pointer with @a ptr appended
  9677. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9678. @complexity Linear in the length of @a ptr.
  9679. @sa @ref operator/=(std::string) to append a reference token
  9680. @sa @ref operator/=(std::size_t) to append an array index
  9681. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  9682. @since version 3.6.0
  9683. */
  9684. json_pointer& operator/=(const json_pointer& ptr)
  9685. {
  9686. reference_tokens.insert(reference_tokens.end(),
  9687. ptr.reference_tokens.begin(),
  9688. ptr.reference_tokens.end());
  9689. return *this;
  9690. }
  9691. /*!
  9692. @brief append an unescaped reference token at the end of this JSON pointer
  9693. @param[in] token reference token to append
  9694. @return JSON pointer with @a token appended without escaping @a token
  9695. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9696. @complexity Amortized constant.
  9697. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9698. @sa @ref operator/=(std::size_t) to append an array index
  9699. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  9700. @since version 3.6.0
  9701. */
  9702. json_pointer& operator/=(std::string token)
  9703. {
  9704. push_back(std::move(token));
  9705. return *this;
  9706. }
  9707. /*!
  9708. @brief append an array index at the end of this JSON pointer
  9709. @param[in] array_idx array index to append
  9710. @return JSON pointer with @a array_idx appended
  9711. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9712. @complexity Amortized constant.
  9713. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9714. @sa @ref operator/=(std::string) to append a reference token
  9715. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  9716. @since version 3.6.0
  9717. */
  9718. json_pointer& operator/=(std::size_t array_idx)
  9719. {
  9720. return *this /= std::to_string(array_idx);
  9721. }
  9722. /*!
  9723. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  9724. @param[in] lhs JSON pointer
  9725. @param[in] rhs JSON pointer
  9726. @return a new JSON pointer with @a rhs appended to @a lhs
  9727. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9728. @complexity Linear in the length of @a lhs and @a rhs.
  9729. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9730. @since version 3.6.0
  9731. */
  9732. friend json_pointer operator/(const json_pointer& lhs,
  9733. const json_pointer& rhs)
  9734. {
  9735. return json_pointer(lhs) /= rhs;
  9736. }
  9737. /*!
  9738. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  9739. @param[in] ptr JSON pointer
  9740. @param[in] token reference token
  9741. @return a new JSON pointer with unescaped @a token appended to @a ptr
  9742. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9743. @complexity Linear in the length of @a ptr.
  9744. @sa @ref operator/=(std::string) to append a reference token
  9745. @since version 3.6.0
  9746. */
  9747. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  9748. {
  9749. return json_pointer(ptr) /= std::move(token);
  9750. }
  9751. /*!
  9752. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  9753. @param[in] ptr JSON pointer
  9754. @param[in] array_idx array index
  9755. @return a new JSON pointer with @a array_idx appended to @a ptr
  9756. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9757. @complexity Linear in the length of @a ptr.
  9758. @sa @ref operator/=(std::size_t) to append an array index
  9759. @since version 3.6.0
  9760. */
  9761. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  9762. {
  9763. return json_pointer(ptr) /= array_idx;
  9764. }
  9765. /*!
  9766. @brief returns the parent of this JSON pointer
  9767. @return parent of this JSON pointer; in case this JSON pointer is the root,
  9768. the root itself is returned
  9769. @complexity Linear in the length of the JSON pointer.
  9770. @liveexample{The example shows the result of `parent_pointer` for different
  9771. JSON Pointers.,json_pointer__parent_pointer}
  9772. @since version 3.6.0
  9773. */
  9774. json_pointer parent_pointer() const
  9775. {
  9776. if (empty())
  9777. {
  9778. return *this;
  9779. }
  9780. json_pointer res = *this;
  9781. res.pop_back();
  9782. return res;
  9783. }
  9784. /*!
  9785. @brief remove last reference token
  9786. @pre not `empty()`
  9787. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  9788. @complexity Constant.
  9789. @throw out_of_range.405 if JSON pointer has no parent
  9790. @since version 3.6.0
  9791. */
  9792. void pop_back()
  9793. {
  9794. if (JSON_HEDLEY_UNLIKELY(empty()))
  9795. {
  9796. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9797. }
  9798. reference_tokens.pop_back();
  9799. }
  9800. /*!
  9801. @brief return last reference token
  9802. @pre not `empty()`
  9803. @return last reference token
  9804. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  9805. @complexity Constant.
  9806. @throw out_of_range.405 if JSON pointer has no parent
  9807. @since version 3.6.0
  9808. */
  9809. const std::string& back() const
  9810. {
  9811. if (JSON_HEDLEY_UNLIKELY(empty()))
  9812. {
  9813. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9814. }
  9815. return reference_tokens.back();
  9816. }
  9817. /*!
  9818. @brief append an unescaped token at the end of the reference pointer
  9819. @param[in] token token to add
  9820. @complexity Amortized constant.
  9821. @liveexample{The example shows the result of `push_back` for different
  9822. JSON Pointers.,json_pointer__push_back}
  9823. @since version 3.6.0
  9824. */
  9825. void push_back(const std::string& token)
  9826. {
  9827. reference_tokens.push_back(token);
  9828. }
  9829. /// @copydoc push_back(const std::string&)
  9830. void push_back(std::string&& token)
  9831. {
  9832. reference_tokens.push_back(std::move(token));
  9833. }
  9834. /*!
  9835. @brief return whether pointer points to the root document
  9836. @return true iff the JSON pointer points to the root document
  9837. @complexity Constant.
  9838. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9839. @liveexample{The example shows the result of `empty` for different JSON
  9840. Pointers.,json_pointer__empty}
  9841. @since version 3.6.0
  9842. */
  9843. bool empty() const noexcept
  9844. {
  9845. return reference_tokens.empty();
  9846. }
  9847. private:
  9848. /*!
  9849. @param[in] s reference token to be converted into an array index
  9850. @return integer representation of @a s
  9851. @throw out_of_range.404 if string @a s could not be converted to an integer
  9852. */
  9853. static int array_index(const std::string& s)
  9854. {
  9855. // error condition (cf. RFC 6901, Sect. 4)
  9856. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 and s[0] == '0'))
  9857. {
  9858. JSON_THROW(detail::parse_error::create(106, 0,
  9859. "array index '" + s +
  9860. "' must not begin with '0'"));
  9861. }
  9862. // error condition (cf. RFC 6901, Sect. 4)
  9863. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 and not (s[0] >= '1' and s[0] <= '9')))
  9864. {
  9865. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number"));
  9866. }
  9867. std::size_t processed_chars = 0;
  9868. int res = 0;
  9869. JSON_TRY
  9870. {
  9871. res = std::stoi(s, &processed_chars);
  9872. }
  9873. JSON_CATCH(std::out_of_range&)
  9874. {
  9875. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9876. }
  9877. // check if the string was completely read
  9878. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  9879. {
  9880. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9881. }
  9882. return res;
  9883. }
  9884. json_pointer top() const
  9885. {
  9886. if (JSON_HEDLEY_UNLIKELY(empty()))
  9887. {
  9888. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9889. }
  9890. json_pointer result = *this;
  9891. result.reference_tokens = {reference_tokens[0]};
  9892. return result;
  9893. }
  9894. /*!
  9895. @brief create and return a reference to the pointed to value
  9896. @complexity Linear in the number of reference tokens.
  9897. @throw parse_error.109 if array index is not a number
  9898. @throw type_error.313 if value cannot be unflattened
  9899. */
  9900. BasicJsonType& get_and_create(BasicJsonType& j) const
  9901. {
  9902. using size_type = typename BasicJsonType::size_type;
  9903. auto result = &j;
  9904. // in case no reference tokens exist, return a reference to the JSON value
  9905. // j which will be overwritten by a primitive value
  9906. for (const auto& reference_token : reference_tokens)
  9907. {
  9908. switch (result->type())
  9909. {
  9910. case detail::value_t::null:
  9911. {
  9912. if (reference_token == "0")
  9913. {
  9914. // start a new array if reference token is 0
  9915. result = &result->operator[](0);
  9916. }
  9917. else
  9918. {
  9919. // start a new object otherwise
  9920. result = &result->operator[](reference_token);
  9921. }
  9922. break;
  9923. }
  9924. case detail::value_t::object:
  9925. {
  9926. // create an entry in the object
  9927. result = &result->operator[](reference_token);
  9928. break;
  9929. }
  9930. case detail::value_t::array:
  9931. {
  9932. // create an entry in the array
  9933. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  9934. break;
  9935. }
  9936. /*
  9937. The following code is only reached if there exists a reference
  9938. token _and_ the current value is primitive. In this case, we have
  9939. an error situation, because primitive values may only occur as
  9940. single value; that is, with an empty list of reference tokens.
  9941. */
  9942. default:
  9943. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  9944. }
  9945. }
  9946. return *result;
  9947. }
  9948. /*!
  9949. @brief return a reference to the pointed to value
  9950. @note This version does not throw if a value is not present, but tries to
  9951. create nested values instead. For instance, calling this function
  9952. with pointer `"/this/that"` on a null value is equivalent to calling
  9953. `operator[]("this").operator[]("that")` on that value, effectively
  9954. changing the null value to an object.
  9955. @param[in] ptr a JSON value
  9956. @return reference to the JSON value pointed to by the JSON pointer
  9957. @complexity Linear in the length of the JSON pointer.
  9958. @throw parse_error.106 if an array index begins with '0'
  9959. @throw parse_error.109 if an array index was not a number
  9960. @throw out_of_range.404 if the JSON pointer can not be resolved
  9961. */
  9962. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  9963. {
  9964. using size_type = typename BasicJsonType::size_type;
  9965. for (const auto& reference_token : reference_tokens)
  9966. {
  9967. // convert null values to arrays or objects before continuing
  9968. if (ptr->is_null())
  9969. {
  9970. // check if reference token is a number
  9971. const bool nums =
  9972. std::all_of(reference_token.begin(), reference_token.end(),
  9973. [](const unsigned char x)
  9974. {
  9975. return std::isdigit(x);
  9976. });
  9977. // change value to array for numbers or "-" or to object otherwise
  9978. *ptr = (nums or reference_token == "-")
  9979. ? detail::value_t::array
  9980. : detail::value_t::object;
  9981. }
  9982. switch (ptr->type())
  9983. {
  9984. case detail::value_t::object:
  9985. {
  9986. // use unchecked object access
  9987. ptr = &ptr->operator[](reference_token);
  9988. break;
  9989. }
  9990. case detail::value_t::array:
  9991. {
  9992. if (reference_token == "-")
  9993. {
  9994. // explicitly treat "-" as index beyond the end
  9995. ptr = &ptr->operator[](ptr->m_value.array->size());
  9996. }
  9997. else
  9998. {
  9999. // convert array index to number; unchecked access
  10000. ptr = &ptr->operator[](
  10001. static_cast<size_type>(array_index(reference_token)));
  10002. }
  10003. break;
  10004. }
  10005. default:
  10006. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10007. }
  10008. }
  10009. return *ptr;
  10010. }
  10011. /*!
  10012. @throw parse_error.106 if an array index begins with '0'
  10013. @throw parse_error.109 if an array index was not a number
  10014. @throw out_of_range.402 if the array index '-' is used
  10015. @throw out_of_range.404 if the JSON pointer can not be resolved
  10016. */
  10017. BasicJsonType& get_checked(BasicJsonType* ptr) const
  10018. {
  10019. using size_type = typename BasicJsonType::size_type;
  10020. for (const auto& reference_token : reference_tokens)
  10021. {
  10022. switch (ptr->type())
  10023. {
  10024. case detail::value_t::object:
  10025. {
  10026. // note: at performs range check
  10027. ptr = &ptr->at(reference_token);
  10028. break;
  10029. }
  10030. case detail::value_t::array:
  10031. {
  10032. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10033. {
  10034. // "-" always fails the range check
  10035. JSON_THROW(detail::out_of_range::create(402,
  10036. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10037. ") is out of range"));
  10038. }
  10039. // note: at performs range check
  10040. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  10041. break;
  10042. }
  10043. default:
  10044. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10045. }
  10046. }
  10047. return *ptr;
  10048. }
  10049. /*!
  10050. @brief return a const reference to the pointed to value
  10051. @param[in] ptr a JSON value
  10052. @return const reference to the JSON value pointed to by the JSON
  10053. pointer
  10054. @throw parse_error.106 if an array index begins with '0'
  10055. @throw parse_error.109 if an array index was not a number
  10056. @throw out_of_range.402 if the array index '-' is used
  10057. @throw out_of_range.404 if the JSON pointer can not be resolved
  10058. */
  10059. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  10060. {
  10061. using size_type = typename BasicJsonType::size_type;
  10062. for (const auto& reference_token : reference_tokens)
  10063. {
  10064. switch (ptr->type())
  10065. {
  10066. case detail::value_t::object:
  10067. {
  10068. // use unchecked object access
  10069. ptr = &ptr->operator[](reference_token);
  10070. break;
  10071. }
  10072. case detail::value_t::array:
  10073. {
  10074. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10075. {
  10076. // "-" cannot be used for const access
  10077. JSON_THROW(detail::out_of_range::create(402,
  10078. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10079. ") is out of range"));
  10080. }
  10081. // use unchecked array access
  10082. ptr = &ptr->operator[](
  10083. static_cast<size_type>(array_index(reference_token)));
  10084. break;
  10085. }
  10086. default:
  10087. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10088. }
  10089. }
  10090. return *ptr;
  10091. }
  10092. /*!
  10093. @throw parse_error.106 if an array index begins with '0'
  10094. @throw parse_error.109 if an array index was not a number
  10095. @throw out_of_range.402 if the array index '-' is used
  10096. @throw out_of_range.404 if the JSON pointer can not be resolved
  10097. */
  10098. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  10099. {
  10100. using size_type = typename BasicJsonType::size_type;
  10101. for (const auto& reference_token : reference_tokens)
  10102. {
  10103. switch (ptr->type())
  10104. {
  10105. case detail::value_t::object:
  10106. {
  10107. // note: at performs range check
  10108. ptr = &ptr->at(reference_token);
  10109. break;
  10110. }
  10111. case detail::value_t::array:
  10112. {
  10113. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10114. {
  10115. // "-" always fails the range check
  10116. JSON_THROW(detail::out_of_range::create(402,
  10117. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10118. ") is out of range"));
  10119. }
  10120. // note: at performs range check
  10121. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  10122. break;
  10123. }
  10124. default:
  10125. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10126. }
  10127. }
  10128. return *ptr;
  10129. }
  10130. /*!
  10131. @throw parse_error.106 if an array index begins with '0'
  10132. @throw parse_error.109 if an array index was not a number
  10133. */
  10134. bool contains(const BasicJsonType* ptr) const
  10135. {
  10136. using size_type = typename BasicJsonType::size_type;
  10137. for (const auto& reference_token : reference_tokens)
  10138. {
  10139. switch (ptr->type())
  10140. {
  10141. case detail::value_t::object:
  10142. {
  10143. if (not ptr->contains(reference_token))
  10144. {
  10145. // we did not find the key in the object
  10146. return false;
  10147. }
  10148. ptr = &ptr->operator[](reference_token);
  10149. break;
  10150. }
  10151. case detail::value_t::array:
  10152. {
  10153. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10154. {
  10155. // "-" always fails the range check
  10156. return false;
  10157. }
  10158. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 and not ("0" <= reference_token and reference_token <= "9")))
  10159. {
  10160. // invalid char
  10161. return false;
  10162. }
  10163. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  10164. {
  10165. if (JSON_HEDLEY_UNLIKELY(not ('1' <= reference_token[0] and reference_token[0] <= '9')))
  10166. {
  10167. // first char should be between '1' and '9'
  10168. return false;
  10169. }
  10170. for (std::size_t i = 1; i < reference_token.size(); i++)
  10171. {
  10172. if (JSON_HEDLEY_UNLIKELY(not ('0' <= reference_token[i] and reference_token[i] <= '9')))
  10173. {
  10174. // other char should be between '0' and '9'
  10175. return false;
  10176. }
  10177. }
  10178. }
  10179. const auto idx = static_cast<size_type>(array_index(reference_token));
  10180. if (idx >= ptr->size())
  10181. {
  10182. // index out of range
  10183. return false;
  10184. }
  10185. ptr = &ptr->operator[](idx);
  10186. break;
  10187. }
  10188. default:
  10189. {
  10190. // we do not expect primitive values if there is still a
  10191. // reference token to process
  10192. return false;
  10193. }
  10194. }
  10195. }
  10196. // no reference token left means we found a primitive value
  10197. return true;
  10198. }
  10199. /*!
  10200. @brief split the string input to reference tokens
  10201. @note This function is only called by the json_pointer constructor.
  10202. All exceptions below are documented there.
  10203. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10204. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10205. */
  10206. static std::vector<std::string> split(const std::string& reference_string)
  10207. {
  10208. std::vector<std::string> result;
  10209. // special case: empty reference string -> no reference tokens
  10210. if (reference_string.empty())
  10211. {
  10212. return result;
  10213. }
  10214. // check if nonempty reference string begins with slash
  10215. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  10216. {
  10217. JSON_THROW(detail::parse_error::create(107, 1,
  10218. "JSON pointer must be empty or begin with '/' - was: '" +
  10219. reference_string + "'"));
  10220. }
  10221. // extract the reference tokens:
  10222. // - slash: position of the last read slash (or end of string)
  10223. // - start: position after the previous slash
  10224. for (
  10225. // search for the first slash after the first character
  10226. std::size_t slash = reference_string.find_first_of('/', 1),
  10227. // set the beginning of the first reference token
  10228. start = 1;
  10229. // we can stop if start == 0 (if slash == std::string::npos)
  10230. start != 0;
  10231. // set the beginning of the next reference token
  10232. // (will eventually be 0 if slash == std::string::npos)
  10233. start = (slash == std::string::npos) ? 0 : slash + 1,
  10234. // find next slash
  10235. slash = reference_string.find_first_of('/', start))
  10236. {
  10237. // use the text between the beginning of the reference token
  10238. // (start) and the last slash (slash).
  10239. auto reference_token = reference_string.substr(start, slash - start);
  10240. // check reference tokens are properly escaped
  10241. for (std::size_t pos = reference_token.find_first_of('~');
  10242. pos != std::string::npos;
  10243. pos = reference_token.find_first_of('~', pos + 1))
  10244. {
  10245. assert(reference_token[pos] == '~');
  10246. // ~ must be followed by 0 or 1
  10247. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  10248. (reference_token[pos + 1] != '0' and
  10249. reference_token[pos + 1] != '1')))
  10250. {
  10251. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  10252. }
  10253. }
  10254. // finally, store the reference token
  10255. unescape(reference_token);
  10256. result.push_back(reference_token);
  10257. }
  10258. return result;
  10259. }
  10260. /*!
  10261. @brief replace all occurrences of a substring by another string
  10262. @param[in,out] s the string to manipulate; changed so that all
  10263. occurrences of @a f are replaced with @a t
  10264. @param[in] f the substring to replace with @a t
  10265. @param[in] t the string to replace @a f
  10266. @pre The search string @a f must not be empty. **This precondition is
  10267. enforced with an assertion.**
  10268. @since version 2.0.0
  10269. */
  10270. static void replace_substring(std::string& s, const std::string& f,
  10271. const std::string& t)
  10272. {
  10273. assert(not f.empty());
  10274. for (auto pos = s.find(f); // find first occurrence of f
  10275. pos != std::string::npos; // make sure f was found
  10276. s.replace(pos, f.size(), t), // replace with t, and
  10277. pos = s.find(f, pos + t.size())) // find next occurrence of f
  10278. {}
  10279. }
  10280. /// escape "~" to "~0" and "/" to "~1"
  10281. static std::string escape(std::string s)
  10282. {
  10283. replace_substring(s, "~", "~0");
  10284. replace_substring(s, "/", "~1");
  10285. return s;
  10286. }
  10287. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  10288. static void unescape(std::string& s)
  10289. {
  10290. replace_substring(s, "~1", "/");
  10291. replace_substring(s, "~0", "~");
  10292. }
  10293. /*!
  10294. @param[in] reference_string the reference string to the current value
  10295. @param[in] value the value to consider
  10296. @param[in,out] result the result object to insert values to
  10297. @note Empty objects or arrays are flattened to `null`.
  10298. */
  10299. static void flatten(const std::string& reference_string,
  10300. const BasicJsonType& value,
  10301. BasicJsonType& result)
  10302. {
  10303. switch (value.type())
  10304. {
  10305. case detail::value_t::array:
  10306. {
  10307. if (value.m_value.array->empty())
  10308. {
  10309. // flatten empty array as null
  10310. result[reference_string] = nullptr;
  10311. }
  10312. else
  10313. {
  10314. // iterate array and use index as reference string
  10315. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  10316. {
  10317. flatten(reference_string + "/" + std::to_string(i),
  10318. value.m_value.array->operator[](i), result);
  10319. }
  10320. }
  10321. break;
  10322. }
  10323. case detail::value_t::object:
  10324. {
  10325. if (value.m_value.object->empty())
  10326. {
  10327. // flatten empty object as null
  10328. result[reference_string] = nullptr;
  10329. }
  10330. else
  10331. {
  10332. // iterate object and use keys as reference string
  10333. for (const auto& element : *value.m_value.object)
  10334. {
  10335. flatten(reference_string + "/" + escape(element.first), element.second, result);
  10336. }
  10337. }
  10338. break;
  10339. }
  10340. default:
  10341. {
  10342. // add primitive value with its reference string
  10343. result[reference_string] = value;
  10344. break;
  10345. }
  10346. }
  10347. }
  10348. /*!
  10349. @param[in] value flattened JSON
  10350. @return unflattened JSON
  10351. @throw parse_error.109 if array index is not a number
  10352. @throw type_error.314 if value is not an object
  10353. @throw type_error.315 if object values are not primitive
  10354. @throw type_error.313 if value cannot be unflattened
  10355. */
  10356. static BasicJsonType
  10357. unflatten(const BasicJsonType& value)
  10358. {
  10359. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  10360. {
  10361. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  10362. }
  10363. BasicJsonType result;
  10364. // iterate the JSON object values
  10365. for (const auto& element : *value.m_value.object)
  10366. {
  10367. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  10368. {
  10369. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  10370. }
  10371. // assign value to reference pointed to by JSON pointer; Note that if
  10372. // the JSON pointer is "" (i.e., points to the whole value), function
  10373. // get_and_create returns a reference to result itself. An assignment
  10374. // will then create a primitive value.
  10375. json_pointer(element.first).get_and_create(result) = element.second;
  10376. }
  10377. return result;
  10378. }
  10379. /*!
  10380. @brief compares two JSON pointers for equality
  10381. @param[in] lhs JSON pointer to compare
  10382. @param[in] rhs JSON pointer to compare
  10383. @return whether @a lhs is equal to @a rhs
  10384. @complexity Linear in the length of the JSON pointer
  10385. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10386. */
  10387. friend bool operator==(json_pointer const& lhs,
  10388. json_pointer const& rhs) noexcept
  10389. {
  10390. return lhs.reference_tokens == rhs.reference_tokens;
  10391. }
  10392. /*!
  10393. @brief compares two JSON pointers for inequality
  10394. @param[in] lhs JSON pointer to compare
  10395. @param[in] rhs JSON pointer to compare
  10396. @return whether @a lhs is not equal @a rhs
  10397. @complexity Linear in the length of the JSON pointer
  10398. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10399. */
  10400. friend bool operator!=(json_pointer const& lhs,
  10401. json_pointer const& rhs) noexcept
  10402. {
  10403. return not (lhs == rhs);
  10404. }
  10405. /// the reference tokens
  10406. std::vector<std::string> reference_tokens;
  10407. };
  10408. } // namespace nlohmann
  10409. // #include <nlohmann/detail/json_ref.hpp>
  10410. #include <initializer_list>
  10411. #include <utility>
  10412. // #include <nlohmann/detail/meta/type_traits.hpp>
  10413. namespace nlohmann
  10414. {
  10415. namespace detail
  10416. {
  10417. template<typename BasicJsonType>
  10418. class json_ref
  10419. {
  10420. public:
  10421. using value_type = BasicJsonType;
  10422. json_ref(value_type&& value)
  10423. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  10424. {}
  10425. json_ref(const value_type& value)
  10426. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  10427. {}
  10428. json_ref(std::initializer_list<json_ref> init)
  10429. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  10430. {}
  10431. template <
  10432. class... Args,
  10433. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  10434. json_ref(Args && ... args)
  10435. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  10436. is_rvalue(true) {}
  10437. // class should be movable only
  10438. json_ref(json_ref&&) = default;
  10439. json_ref(const json_ref&) = delete;
  10440. json_ref& operator=(const json_ref&) = delete;
  10441. json_ref& operator=(json_ref&&) = delete;
  10442. ~json_ref() = default;
  10443. value_type moved_or_copied() const
  10444. {
  10445. if (is_rvalue)
  10446. {
  10447. return std::move(*value_ref);
  10448. }
  10449. return *value_ref;
  10450. }
  10451. value_type const& operator*() const
  10452. {
  10453. return *static_cast<value_type const*>(value_ref);
  10454. }
  10455. value_type const* operator->() const
  10456. {
  10457. return static_cast<value_type const*>(value_ref);
  10458. }
  10459. private:
  10460. mutable value_type owned_value = nullptr;
  10461. value_type* value_ref = nullptr;
  10462. const bool is_rvalue;
  10463. };
  10464. } // namespace detail
  10465. } // namespace nlohmann
  10466. // #include <nlohmann/detail/macro_scope.hpp>
  10467. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10468. // #include <nlohmann/detail/meta/type_traits.hpp>
  10469. // #include <nlohmann/detail/output/binary_writer.hpp>
  10470. #include <algorithm> // reverse
  10471. #include <array> // array
  10472. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  10473. #include <cstring> // memcpy
  10474. #include <limits> // numeric_limits
  10475. #include <string> // string
  10476. #include <cmath> // isnan, isinf
  10477. // #include <nlohmann/detail/input/binary_reader.hpp>
  10478. // #include <nlohmann/detail/macro_scope.hpp>
  10479. // #include <nlohmann/detail/output/output_adapters.hpp>
  10480. #include <algorithm> // copy
  10481. #include <cstddef> // size_t
  10482. #include <ios> // streamsize
  10483. #include <iterator> // back_inserter
  10484. #include <memory> // shared_ptr, make_shared
  10485. #include <ostream> // basic_ostream
  10486. #include <string> // basic_string
  10487. #include <vector> // vector
  10488. // #include <nlohmann/detail/macro_scope.hpp>
  10489. namespace nlohmann
  10490. {
  10491. namespace detail
  10492. {
  10493. /// abstract output adapter interface
  10494. template<typename CharType> struct output_adapter_protocol
  10495. {
  10496. virtual void write_character(CharType c) = 0;
  10497. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  10498. virtual ~output_adapter_protocol() = default;
  10499. };
  10500. /// a type to simplify interfaces
  10501. template<typename CharType>
  10502. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  10503. /// output adapter for byte vectors
  10504. template<typename CharType>
  10505. class output_vector_adapter : public output_adapter_protocol<CharType>
  10506. {
  10507. public:
  10508. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  10509. : v(vec)
  10510. {}
  10511. void write_character(CharType c) override
  10512. {
  10513. v.push_back(c);
  10514. }
  10515. JSON_HEDLEY_NON_NULL(2)
  10516. void write_characters(const CharType* s, std::size_t length) override
  10517. {
  10518. std::copy(s, s + length, std::back_inserter(v));
  10519. }
  10520. private:
  10521. std::vector<CharType>& v;
  10522. };
  10523. /// output adapter for output streams
  10524. template<typename CharType>
  10525. class output_stream_adapter : public output_adapter_protocol<CharType>
  10526. {
  10527. public:
  10528. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  10529. : stream(s)
  10530. {}
  10531. void write_character(CharType c) override
  10532. {
  10533. stream.put(c);
  10534. }
  10535. JSON_HEDLEY_NON_NULL(2)
  10536. void write_characters(const CharType* s, std::size_t length) override
  10537. {
  10538. stream.write(s, static_cast<std::streamsize>(length));
  10539. }
  10540. private:
  10541. std::basic_ostream<CharType>& stream;
  10542. };
  10543. /// output adapter for basic_string
  10544. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10545. class output_string_adapter : public output_adapter_protocol<CharType>
  10546. {
  10547. public:
  10548. explicit output_string_adapter(StringType& s) noexcept
  10549. : str(s)
  10550. {}
  10551. void write_character(CharType c) override
  10552. {
  10553. str.push_back(c);
  10554. }
  10555. JSON_HEDLEY_NON_NULL(2)
  10556. void write_characters(const CharType* s, std::size_t length) override
  10557. {
  10558. str.append(s, length);
  10559. }
  10560. private:
  10561. StringType& str;
  10562. };
  10563. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10564. class output_adapter
  10565. {
  10566. public:
  10567. output_adapter(std::vector<CharType>& vec)
  10568. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  10569. output_adapter(std::basic_ostream<CharType>& s)
  10570. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  10571. output_adapter(StringType& s)
  10572. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  10573. operator output_adapter_t<CharType>()
  10574. {
  10575. return oa;
  10576. }
  10577. private:
  10578. output_adapter_t<CharType> oa = nullptr;
  10579. };
  10580. } // namespace detail
  10581. } // namespace nlohmann
  10582. namespace nlohmann
  10583. {
  10584. namespace detail
  10585. {
  10586. ///////////////////
  10587. // binary writer //
  10588. ///////////////////
  10589. /*!
  10590. @brief serialization to CBOR and MessagePack values
  10591. */
  10592. template<typename BasicJsonType, typename CharType>
  10593. class binary_writer
  10594. {
  10595. using string_t = typename BasicJsonType::string_t;
  10596. using binary_t = typename BasicJsonType::binary_t;
  10597. public:
  10598. /*!
  10599. @brief create a binary writer
  10600. @param[in] adapter output adapter to write to
  10601. */
  10602. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  10603. {
  10604. assert(oa);
  10605. }
  10606. /*!
  10607. @param[in] j JSON value to serialize
  10608. @pre j.type() == value_t::object
  10609. */
  10610. void write_bson(const BasicJsonType& j)
  10611. {
  10612. switch (j.type())
  10613. {
  10614. case value_t::object:
  10615. {
  10616. write_bson_object(*j.m_value.object);
  10617. break;
  10618. }
  10619. default:
  10620. {
  10621. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  10622. }
  10623. }
  10624. }
  10625. /*!
  10626. @param[in] j JSON value to serialize
  10627. */
  10628. void write_cbor(const BasicJsonType& j)
  10629. {
  10630. switch (j.type())
  10631. {
  10632. case value_t::null:
  10633. {
  10634. oa->write_character(to_char_type(0xF6));
  10635. break;
  10636. }
  10637. case value_t::boolean:
  10638. {
  10639. oa->write_character(j.m_value.boolean
  10640. ? to_char_type(0xF5)
  10641. : to_char_type(0xF4));
  10642. break;
  10643. }
  10644. case value_t::number_integer:
  10645. {
  10646. if (j.m_value.number_integer >= 0)
  10647. {
  10648. // CBOR does not differentiate between positive signed
  10649. // integers and unsigned integers. Therefore, we used the
  10650. // code from the value_t::number_unsigned case here.
  10651. if (j.m_value.number_integer <= 0x17)
  10652. {
  10653. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10654. }
  10655. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10656. {
  10657. oa->write_character(to_char_type(0x18));
  10658. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10659. }
  10660. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  10661. {
  10662. oa->write_character(to_char_type(0x19));
  10663. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10664. }
  10665. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  10666. {
  10667. oa->write_character(to_char_type(0x1A));
  10668. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10669. }
  10670. else
  10671. {
  10672. oa->write_character(to_char_type(0x1B));
  10673. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10674. }
  10675. }
  10676. else
  10677. {
  10678. // The conversions below encode the sign in the first
  10679. // byte, and the value is converted to a positive number.
  10680. const auto positive_number = -1 - j.m_value.number_integer;
  10681. if (j.m_value.number_integer >= -24)
  10682. {
  10683. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  10684. }
  10685. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  10686. {
  10687. oa->write_character(to_char_type(0x38));
  10688. write_number(static_cast<std::uint8_t>(positive_number));
  10689. }
  10690. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  10691. {
  10692. oa->write_character(to_char_type(0x39));
  10693. write_number(static_cast<std::uint16_t>(positive_number));
  10694. }
  10695. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  10696. {
  10697. oa->write_character(to_char_type(0x3A));
  10698. write_number(static_cast<std::uint32_t>(positive_number));
  10699. }
  10700. else
  10701. {
  10702. oa->write_character(to_char_type(0x3B));
  10703. write_number(static_cast<std::uint64_t>(positive_number));
  10704. }
  10705. }
  10706. break;
  10707. }
  10708. case value_t::number_unsigned:
  10709. {
  10710. if (j.m_value.number_unsigned <= 0x17)
  10711. {
  10712. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10713. }
  10714. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10715. {
  10716. oa->write_character(to_char_type(0x18));
  10717. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10718. }
  10719. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10720. {
  10721. oa->write_character(to_char_type(0x19));
  10722. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  10723. }
  10724. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10725. {
  10726. oa->write_character(to_char_type(0x1A));
  10727. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  10728. }
  10729. else
  10730. {
  10731. oa->write_character(to_char_type(0x1B));
  10732. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  10733. }
  10734. break;
  10735. }
  10736. case value_t::number_float:
  10737. {
  10738. if (std::isnan(j.m_value.number_float))
  10739. {
  10740. // NaN is 0xf97e00 in CBOR
  10741. oa->write_character(to_char_type(0xF9));
  10742. oa->write_character(to_char_type(0x7E));
  10743. oa->write_character(to_char_type(0x00));
  10744. }
  10745. else if (std::isinf(j.m_value.number_float))
  10746. {
  10747. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  10748. oa->write_character(to_char_type(0xf9));
  10749. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  10750. oa->write_character(to_char_type(0x00));
  10751. }
  10752. else
  10753. {
  10754. if (static_cast<double>(j.m_value.number_float) >= static_cast<double>(std::numeric_limits<float>::lowest()) and
  10755. static_cast<double>(j.m_value.number_float) <= static_cast<double>((std::numeric_limits<float>::max)()) and
  10756. static_cast<double>(static_cast<float>(j.m_value.number_float)) == static_cast<double>(j.m_value.number_float))
  10757. {
  10758. oa->write_character(get_cbor_float_prefix(static_cast<float>(j.m_value.number_float)));
  10759. write_number(static_cast<float>(j.m_value.number_float));
  10760. }
  10761. else
  10762. {
  10763. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  10764. write_number(j.m_value.number_float);
  10765. }
  10766. }
  10767. break;
  10768. }
  10769. case value_t::string:
  10770. {
  10771. // step 1: write control byte and the string length
  10772. const auto N = j.m_value.string->size();
  10773. if (N <= 0x17)
  10774. {
  10775. write_number(static_cast<std::uint8_t>(0x60 + N));
  10776. }
  10777. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10778. {
  10779. oa->write_character(to_char_type(0x78));
  10780. write_number(static_cast<std::uint8_t>(N));
  10781. }
  10782. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10783. {
  10784. oa->write_character(to_char_type(0x79));
  10785. write_number(static_cast<std::uint16_t>(N));
  10786. }
  10787. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10788. {
  10789. oa->write_character(to_char_type(0x7A));
  10790. write_number(static_cast<std::uint32_t>(N));
  10791. }
  10792. // LCOV_EXCL_START
  10793. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10794. {
  10795. oa->write_character(to_char_type(0x7B));
  10796. write_number(static_cast<std::uint64_t>(N));
  10797. }
  10798. // LCOV_EXCL_STOP
  10799. // step 2: write the string
  10800. oa->write_characters(
  10801. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10802. j.m_value.string->size());
  10803. break;
  10804. }
  10805. case value_t::array:
  10806. {
  10807. // step 1: write control byte and the array size
  10808. const auto N = j.m_value.array->size();
  10809. if (N <= 0x17)
  10810. {
  10811. write_number(static_cast<std::uint8_t>(0x80 + N));
  10812. }
  10813. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10814. {
  10815. oa->write_character(to_char_type(0x98));
  10816. write_number(static_cast<std::uint8_t>(N));
  10817. }
  10818. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10819. {
  10820. oa->write_character(to_char_type(0x99));
  10821. write_number(static_cast<std::uint16_t>(N));
  10822. }
  10823. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10824. {
  10825. oa->write_character(to_char_type(0x9A));
  10826. write_number(static_cast<std::uint32_t>(N));
  10827. }
  10828. // LCOV_EXCL_START
  10829. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10830. {
  10831. oa->write_character(to_char_type(0x9B));
  10832. write_number(static_cast<std::uint64_t>(N));
  10833. }
  10834. // LCOV_EXCL_STOP
  10835. // step 2: write each element
  10836. for (const auto& el : *j.m_value.array)
  10837. {
  10838. write_cbor(el);
  10839. }
  10840. break;
  10841. }
  10842. case value_t::binary:
  10843. {
  10844. // step 1: write control byte and the binary array size
  10845. const auto N = j.m_value.binary->size();
  10846. if (N <= 0x17)
  10847. {
  10848. write_number(static_cast<std::uint8_t>(0x40 + N));
  10849. }
  10850. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10851. {
  10852. oa->write_character(to_char_type(0x58));
  10853. write_number(static_cast<std::uint8_t>(N));
  10854. }
  10855. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10856. {
  10857. oa->write_character(to_char_type(0x59));
  10858. write_number(static_cast<std::uint16_t>(N));
  10859. }
  10860. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10861. {
  10862. oa->write_character(to_char_type(0x5A));
  10863. write_number(static_cast<std::uint32_t>(N));
  10864. }
  10865. // LCOV_EXCL_START
  10866. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10867. {
  10868. oa->write_character(to_char_type(0x5B));
  10869. write_number(static_cast<std::uint64_t>(N));
  10870. }
  10871. // LCOV_EXCL_STOP
  10872. // step 2: write each element
  10873. oa->write_characters(
  10874. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  10875. N);
  10876. break;
  10877. }
  10878. case value_t::object:
  10879. {
  10880. // step 1: write control byte and the object size
  10881. const auto N = j.m_value.object->size();
  10882. if (N <= 0x17)
  10883. {
  10884. write_number(static_cast<std::uint8_t>(0xA0 + N));
  10885. }
  10886. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10887. {
  10888. oa->write_character(to_char_type(0xB8));
  10889. write_number(static_cast<std::uint8_t>(N));
  10890. }
  10891. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10892. {
  10893. oa->write_character(to_char_type(0xB9));
  10894. write_number(static_cast<std::uint16_t>(N));
  10895. }
  10896. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10897. {
  10898. oa->write_character(to_char_type(0xBA));
  10899. write_number(static_cast<std::uint32_t>(N));
  10900. }
  10901. // LCOV_EXCL_START
  10902. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10903. {
  10904. oa->write_character(to_char_type(0xBB));
  10905. write_number(static_cast<std::uint64_t>(N));
  10906. }
  10907. // LCOV_EXCL_STOP
  10908. // step 2: write each element
  10909. for (const auto& el : *j.m_value.object)
  10910. {
  10911. write_cbor(el.first);
  10912. write_cbor(el.second);
  10913. }
  10914. break;
  10915. }
  10916. default:
  10917. break;
  10918. }
  10919. }
  10920. /*!
  10921. @param[in] j JSON value to serialize
  10922. */
  10923. void write_msgpack(const BasicJsonType& j)
  10924. {
  10925. switch (j.type())
  10926. {
  10927. case value_t::null: // nil
  10928. {
  10929. oa->write_character(to_char_type(0xC0));
  10930. break;
  10931. }
  10932. case value_t::boolean: // true and false
  10933. {
  10934. oa->write_character(j.m_value.boolean
  10935. ? to_char_type(0xC3)
  10936. : to_char_type(0xC2));
  10937. break;
  10938. }
  10939. case value_t::number_integer:
  10940. {
  10941. if (j.m_value.number_integer >= 0)
  10942. {
  10943. // MessagePack does not differentiate between positive
  10944. // signed integers and unsigned integers. Therefore, we used
  10945. // the code from the value_t::number_unsigned case here.
  10946. if (j.m_value.number_unsigned < 128)
  10947. {
  10948. // positive fixnum
  10949. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10950. }
  10951. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10952. {
  10953. // uint 8
  10954. oa->write_character(to_char_type(0xCC));
  10955. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10956. }
  10957. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10958. {
  10959. // uint 16
  10960. oa->write_character(to_char_type(0xCD));
  10961. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10962. }
  10963. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10964. {
  10965. // uint 32
  10966. oa->write_character(to_char_type(0xCE));
  10967. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10968. }
  10969. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10970. {
  10971. // uint 64
  10972. oa->write_character(to_char_type(0xCF));
  10973. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10974. }
  10975. }
  10976. else
  10977. {
  10978. if (j.m_value.number_integer >= -32)
  10979. {
  10980. // negative fixnum
  10981. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10982. }
  10983. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10984. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10985. {
  10986. // int 8
  10987. oa->write_character(to_char_type(0xD0));
  10988. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10989. }
  10990. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10991. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10992. {
  10993. // int 16
  10994. oa->write_character(to_char_type(0xD1));
  10995. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10996. }
  10997. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10998. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10999. {
  11000. // int 32
  11001. oa->write_character(to_char_type(0xD2));
  11002. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  11003. }
  11004. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  11005. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  11006. {
  11007. // int 64
  11008. oa->write_character(to_char_type(0xD3));
  11009. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  11010. }
  11011. }
  11012. break;
  11013. }
  11014. case value_t::number_unsigned:
  11015. {
  11016. if (j.m_value.number_unsigned < 128)
  11017. {
  11018. // positive fixnum
  11019. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11020. }
  11021. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11022. {
  11023. // uint 8
  11024. oa->write_character(to_char_type(0xCC));
  11025. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11026. }
  11027. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11028. {
  11029. // uint 16
  11030. oa->write_character(to_char_type(0xCD));
  11031. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11032. }
  11033. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11034. {
  11035. // uint 32
  11036. oa->write_character(to_char_type(0xCE));
  11037. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11038. }
  11039. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  11040. {
  11041. // uint 64
  11042. oa->write_character(to_char_type(0xCF));
  11043. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11044. }
  11045. break;
  11046. }
  11047. case value_t::number_float:
  11048. {
  11049. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  11050. write_number(j.m_value.number_float);
  11051. break;
  11052. }
  11053. case value_t::string:
  11054. {
  11055. // step 1: write control byte and the string length
  11056. const auto N = j.m_value.string->size();
  11057. if (N <= 31)
  11058. {
  11059. // fixstr
  11060. write_number(static_cast<std::uint8_t>(0xA0 | N));
  11061. }
  11062. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11063. {
  11064. // str 8
  11065. oa->write_character(to_char_type(0xD9));
  11066. write_number(static_cast<std::uint8_t>(N));
  11067. }
  11068. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11069. {
  11070. // str 16
  11071. oa->write_character(to_char_type(0xDA));
  11072. write_number(static_cast<std::uint16_t>(N));
  11073. }
  11074. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11075. {
  11076. // str 32
  11077. oa->write_character(to_char_type(0xDB));
  11078. write_number(static_cast<std::uint32_t>(N));
  11079. }
  11080. // step 2: write the string
  11081. oa->write_characters(
  11082. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11083. j.m_value.string->size());
  11084. break;
  11085. }
  11086. case value_t::array:
  11087. {
  11088. // step 1: write control byte and the array size
  11089. const auto N = j.m_value.array->size();
  11090. if (N <= 15)
  11091. {
  11092. // fixarray
  11093. write_number(static_cast<std::uint8_t>(0x90 | N));
  11094. }
  11095. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11096. {
  11097. // array 16
  11098. oa->write_character(to_char_type(0xDC));
  11099. write_number(static_cast<std::uint16_t>(N));
  11100. }
  11101. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11102. {
  11103. // array 32
  11104. oa->write_character(to_char_type(0xDD));
  11105. write_number(static_cast<std::uint32_t>(N));
  11106. }
  11107. // step 2: write each element
  11108. for (const auto& el : *j.m_value.array)
  11109. {
  11110. write_msgpack(el);
  11111. }
  11112. break;
  11113. }
  11114. case value_t::binary:
  11115. {
  11116. // step 0: determine if the binary type has a set subtype to
  11117. // determine whether or not to use the ext or fixext types
  11118. const bool use_ext = j.m_value.binary->has_subtype();
  11119. // step 1: write control byte and the byte string length
  11120. const auto N = j.m_value.binary->size();
  11121. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11122. {
  11123. std::uint8_t output_type;
  11124. bool fixed = true;
  11125. if (use_ext)
  11126. {
  11127. switch (N)
  11128. {
  11129. case 1:
  11130. output_type = 0xD4; // fixext 1
  11131. break;
  11132. case 2:
  11133. output_type = 0xD5; // fixext 2
  11134. break;
  11135. case 4:
  11136. output_type = 0xD6; // fixext 4
  11137. break;
  11138. case 8:
  11139. output_type = 0xD7; // fixext 8
  11140. break;
  11141. case 16:
  11142. output_type = 0xD8; // fixext 16
  11143. break;
  11144. default:
  11145. output_type = 0xC7; // ext 8
  11146. fixed = false;
  11147. break;
  11148. }
  11149. }
  11150. else
  11151. {
  11152. output_type = 0xC4; // bin 8
  11153. fixed = false;
  11154. }
  11155. oa->write_character(to_char_type(output_type));
  11156. if (not fixed)
  11157. {
  11158. write_number(static_cast<std::uint8_t>(N));
  11159. }
  11160. }
  11161. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11162. {
  11163. std::uint8_t output_type;
  11164. if (use_ext)
  11165. {
  11166. output_type = 0xC8; // ext 16
  11167. }
  11168. else
  11169. {
  11170. output_type = 0xC5; // bin 16
  11171. }
  11172. oa->write_character(to_char_type(output_type));
  11173. write_number(static_cast<std::uint16_t>(N));
  11174. }
  11175. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11176. {
  11177. std::uint8_t output_type;
  11178. if (use_ext)
  11179. {
  11180. output_type = 0xC9; // ext 32
  11181. }
  11182. else
  11183. {
  11184. output_type = 0xC6; // bin 32
  11185. }
  11186. oa->write_character(to_char_type(output_type));
  11187. write_number(static_cast<std::uint32_t>(N));
  11188. }
  11189. // step 1.5: if this is an ext type, write the subtype
  11190. if (use_ext)
  11191. {
  11192. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  11193. }
  11194. // step 2: write the byte string
  11195. oa->write_characters(
  11196. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11197. N);
  11198. break;
  11199. }
  11200. case value_t::object:
  11201. {
  11202. // step 1: write control byte and the object size
  11203. const auto N = j.m_value.object->size();
  11204. if (N <= 15)
  11205. {
  11206. // fixmap
  11207. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  11208. }
  11209. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11210. {
  11211. // map 16
  11212. oa->write_character(to_char_type(0xDE));
  11213. write_number(static_cast<std::uint16_t>(N));
  11214. }
  11215. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11216. {
  11217. // map 32
  11218. oa->write_character(to_char_type(0xDF));
  11219. write_number(static_cast<std::uint32_t>(N));
  11220. }
  11221. // step 2: write each element
  11222. for (const auto& el : *j.m_value.object)
  11223. {
  11224. write_msgpack(el.first);
  11225. write_msgpack(el.second);
  11226. }
  11227. break;
  11228. }
  11229. default:
  11230. break;
  11231. }
  11232. }
  11233. /*!
  11234. @param[in] j JSON value to serialize
  11235. @param[in] use_count whether to use '#' prefixes (optimized format)
  11236. @param[in] use_type whether to use '$' prefixes (optimized format)
  11237. @param[in] add_prefix whether prefixes need to be used for this value
  11238. */
  11239. void write_ubjson(const BasicJsonType& j, const bool use_count,
  11240. const bool use_type, const bool add_prefix = true)
  11241. {
  11242. switch (j.type())
  11243. {
  11244. case value_t::null:
  11245. {
  11246. if (add_prefix)
  11247. {
  11248. oa->write_character(to_char_type('Z'));
  11249. }
  11250. break;
  11251. }
  11252. case value_t::boolean:
  11253. {
  11254. if (add_prefix)
  11255. {
  11256. oa->write_character(j.m_value.boolean
  11257. ? to_char_type('T')
  11258. : to_char_type('F'));
  11259. }
  11260. break;
  11261. }
  11262. case value_t::number_integer:
  11263. {
  11264. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  11265. break;
  11266. }
  11267. case value_t::number_unsigned:
  11268. {
  11269. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  11270. break;
  11271. }
  11272. case value_t::number_float:
  11273. {
  11274. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  11275. break;
  11276. }
  11277. case value_t::string:
  11278. {
  11279. if (add_prefix)
  11280. {
  11281. oa->write_character(to_char_type('S'));
  11282. }
  11283. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  11284. oa->write_characters(
  11285. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11286. j.m_value.string->size());
  11287. break;
  11288. }
  11289. case value_t::array:
  11290. {
  11291. if (add_prefix)
  11292. {
  11293. oa->write_character(to_char_type('['));
  11294. }
  11295. bool prefix_required = true;
  11296. if (use_type and not j.m_value.array->empty())
  11297. {
  11298. assert(use_count);
  11299. const CharType first_prefix = ubjson_prefix(j.front());
  11300. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  11301. [this, first_prefix](const BasicJsonType & v)
  11302. {
  11303. return ubjson_prefix(v) == first_prefix;
  11304. });
  11305. if (same_prefix)
  11306. {
  11307. prefix_required = false;
  11308. oa->write_character(to_char_type('$'));
  11309. oa->write_character(first_prefix);
  11310. }
  11311. }
  11312. if (use_count)
  11313. {
  11314. oa->write_character(to_char_type('#'));
  11315. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  11316. }
  11317. for (const auto& el : *j.m_value.array)
  11318. {
  11319. write_ubjson(el, use_count, use_type, prefix_required);
  11320. }
  11321. if (not use_count)
  11322. {
  11323. oa->write_character(to_char_type(']'));
  11324. }
  11325. break;
  11326. }
  11327. case value_t::binary:
  11328. {
  11329. if (add_prefix)
  11330. {
  11331. oa->write_character(to_char_type('['));
  11332. }
  11333. if (use_type and not j.m_value.binary->empty())
  11334. {
  11335. assert(use_count);
  11336. oa->write_character(to_char_type('$'));
  11337. oa->write_character('U');
  11338. }
  11339. if (use_count)
  11340. {
  11341. oa->write_character(to_char_type('#'));
  11342. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  11343. }
  11344. if (use_type)
  11345. {
  11346. oa->write_characters(
  11347. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11348. j.m_value.binary->size());
  11349. }
  11350. else
  11351. {
  11352. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  11353. {
  11354. oa->write_character(to_char_type('U'));
  11355. oa->write_character(j.m_value.binary->data()[i]);
  11356. }
  11357. }
  11358. if (not use_count)
  11359. {
  11360. oa->write_character(to_char_type(']'));
  11361. }
  11362. break;
  11363. }
  11364. case value_t::object:
  11365. {
  11366. if (add_prefix)
  11367. {
  11368. oa->write_character(to_char_type('{'));
  11369. }
  11370. bool prefix_required = true;
  11371. if (use_type and not j.m_value.object->empty())
  11372. {
  11373. assert(use_count);
  11374. const CharType first_prefix = ubjson_prefix(j.front());
  11375. const bool same_prefix = std::all_of(j.begin(), j.end(),
  11376. [this, first_prefix](const BasicJsonType & v)
  11377. {
  11378. return ubjson_prefix(v) == first_prefix;
  11379. });
  11380. if (same_prefix)
  11381. {
  11382. prefix_required = false;
  11383. oa->write_character(to_char_type('$'));
  11384. oa->write_character(first_prefix);
  11385. }
  11386. }
  11387. if (use_count)
  11388. {
  11389. oa->write_character(to_char_type('#'));
  11390. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  11391. }
  11392. for (const auto& el : *j.m_value.object)
  11393. {
  11394. write_number_with_ubjson_prefix(el.first.size(), true);
  11395. oa->write_characters(
  11396. reinterpret_cast<const CharType*>(el.first.c_str()),
  11397. el.first.size());
  11398. write_ubjson(el.second, use_count, use_type, prefix_required);
  11399. }
  11400. if (not use_count)
  11401. {
  11402. oa->write_character(to_char_type('}'));
  11403. }
  11404. break;
  11405. }
  11406. default:
  11407. break;
  11408. }
  11409. }
  11410. private:
  11411. //////////
  11412. // BSON //
  11413. //////////
  11414. /*!
  11415. @return The size of a BSON document entry header, including the id marker
  11416. and the entry name size (and its null-terminator).
  11417. */
  11418. static std::size_t calc_bson_entry_header_size(const string_t& name)
  11419. {
  11420. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  11421. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  11422. {
  11423. JSON_THROW(out_of_range::create(409,
  11424. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  11425. }
  11426. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  11427. }
  11428. /*!
  11429. @brief Writes the given @a element_type and @a name to the output adapter
  11430. */
  11431. void write_bson_entry_header(const string_t& name,
  11432. const std::uint8_t element_type)
  11433. {
  11434. oa->write_character(to_char_type(element_type)); // boolean
  11435. oa->write_characters(
  11436. reinterpret_cast<const CharType*>(name.c_str()),
  11437. name.size() + 1u);
  11438. }
  11439. /*!
  11440. @brief Writes a BSON element with key @a name and boolean value @a value
  11441. */
  11442. void write_bson_boolean(const string_t& name,
  11443. const bool value)
  11444. {
  11445. write_bson_entry_header(name, 0x08);
  11446. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  11447. }
  11448. /*!
  11449. @brief Writes a BSON element with key @a name and double value @a value
  11450. */
  11451. void write_bson_double(const string_t& name,
  11452. const double value)
  11453. {
  11454. write_bson_entry_header(name, 0x01);
  11455. write_number<double, true>(value);
  11456. }
  11457. /*!
  11458. @return The size of the BSON-encoded string in @a value
  11459. */
  11460. static std::size_t calc_bson_string_size(const string_t& value)
  11461. {
  11462. return sizeof(std::int32_t) + value.size() + 1ul;
  11463. }
  11464. /*!
  11465. @brief Writes a BSON element with key @a name and string value @a value
  11466. */
  11467. void write_bson_string(const string_t& name,
  11468. const string_t& value)
  11469. {
  11470. write_bson_entry_header(name, 0x02);
  11471. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  11472. oa->write_characters(
  11473. reinterpret_cast<const CharType*>(value.c_str()),
  11474. value.size() + 1);
  11475. }
  11476. /*!
  11477. @brief Writes a BSON element with key @a name and null value
  11478. */
  11479. void write_bson_null(const string_t& name)
  11480. {
  11481. write_bson_entry_header(name, 0x0A);
  11482. }
  11483. /*!
  11484. @return The size of the BSON-encoded integer @a value
  11485. */
  11486. static std::size_t calc_bson_integer_size(const std::int64_t value)
  11487. {
  11488. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  11489. ? sizeof(std::int32_t)
  11490. : sizeof(std::int64_t);
  11491. }
  11492. /*!
  11493. @brief Writes a BSON element with key @a name and integer @a value
  11494. */
  11495. void write_bson_integer(const string_t& name,
  11496. const std::int64_t value)
  11497. {
  11498. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  11499. {
  11500. write_bson_entry_header(name, 0x10); // int32
  11501. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11502. }
  11503. else
  11504. {
  11505. write_bson_entry_header(name, 0x12); // int64
  11506. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11507. }
  11508. }
  11509. /*!
  11510. @return The size of the BSON-encoded unsigned integer in @a j
  11511. */
  11512. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  11513. {
  11514. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11515. ? sizeof(std::int32_t)
  11516. : sizeof(std::int64_t);
  11517. }
  11518. /*!
  11519. @brief Writes a BSON element with key @a name and unsigned @a value
  11520. */
  11521. void write_bson_unsigned(const string_t& name,
  11522. const std::uint64_t value)
  11523. {
  11524. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11525. {
  11526. write_bson_entry_header(name, 0x10 /* int32 */);
  11527. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11528. }
  11529. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11530. {
  11531. write_bson_entry_header(name, 0x12 /* int64 */);
  11532. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11533. }
  11534. else
  11535. {
  11536. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  11537. }
  11538. }
  11539. /*!
  11540. @brief Writes a BSON element with key @a name and object @a value
  11541. */
  11542. void write_bson_object_entry(const string_t& name,
  11543. const typename BasicJsonType::object_t& value)
  11544. {
  11545. write_bson_entry_header(name, 0x03); // object
  11546. write_bson_object(value);
  11547. }
  11548. /*!
  11549. @return The size of the BSON-encoded array @a value
  11550. */
  11551. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  11552. {
  11553. std::size_t array_index = 0ul;
  11554. 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)
  11555. {
  11556. return result + calc_bson_element_size(std::to_string(array_index++), el);
  11557. });
  11558. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  11559. }
  11560. /*!
  11561. @return The size of the BSON-encoded binary array @a value
  11562. */
  11563. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  11564. {
  11565. return sizeof(std::int32_t) + value.size() + 1ul;
  11566. }
  11567. /*!
  11568. @brief Writes a BSON element with key @a name and array @a value
  11569. */
  11570. void write_bson_array(const string_t& name,
  11571. const typename BasicJsonType::array_t& value)
  11572. {
  11573. write_bson_entry_header(name, 0x04); // array
  11574. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  11575. std::size_t array_index = 0ul;
  11576. for (const auto& el : value)
  11577. {
  11578. write_bson_element(std::to_string(array_index++), el);
  11579. }
  11580. oa->write_character(to_char_type(0x00));
  11581. }
  11582. /*!
  11583. @brief Writes a BSON element with key @a name and binary value @a value
  11584. */
  11585. void write_bson_binary(const string_t& name,
  11586. const binary_t& value)
  11587. {
  11588. write_bson_entry_header(name, 0x05);
  11589. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  11590. write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00));
  11591. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  11592. }
  11593. /*!
  11594. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  11595. @return The calculated size for the BSON document entry for @a j with the given @a name.
  11596. */
  11597. static std::size_t calc_bson_element_size(const string_t& name,
  11598. const BasicJsonType& j)
  11599. {
  11600. const auto header_size = calc_bson_entry_header_size(name);
  11601. switch (j.type())
  11602. {
  11603. case value_t::object:
  11604. return header_size + calc_bson_object_size(*j.m_value.object);
  11605. case value_t::array:
  11606. return header_size + calc_bson_array_size(*j.m_value.array);
  11607. case value_t::binary:
  11608. return header_size + calc_bson_binary_size(*j.m_value.binary);
  11609. case value_t::boolean:
  11610. return header_size + 1ul;
  11611. case value_t::number_float:
  11612. return header_size + 8ul;
  11613. case value_t::number_integer:
  11614. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  11615. case value_t::number_unsigned:
  11616. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  11617. case value_t::string:
  11618. return header_size + calc_bson_string_size(*j.m_value.string);
  11619. case value_t::null:
  11620. return header_size + 0ul;
  11621. // LCOV_EXCL_START
  11622. default:
  11623. assert(false);
  11624. return 0ul;
  11625. // LCOV_EXCL_STOP
  11626. }
  11627. }
  11628. /*!
  11629. @brief Serializes the JSON value @a j to BSON and associates it with the
  11630. key @a name.
  11631. @param name The name to associate with the JSON entity @a j within the
  11632. current BSON document
  11633. @return The size of the BSON entry
  11634. */
  11635. void write_bson_element(const string_t& name,
  11636. const BasicJsonType& j)
  11637. {
  11638. switch (j.type())
  11639. {
  11640. case value_t::object:
  11641. return write_bson_object_entry(name, *j.m_value.object);
  11642. case value_t::array:
  11643. return write_bson_array(name, *j.m_value.array);
  11644. case value_t::binary:
  11645. return write_bson_binary(name, *j.m_value.binary);
  11646. case value_t::boolean:
  11647. return write_bson_boolean(name, j.m_value.boolean);
  11648. case value_t::number_float:
  11649. return write_bson_double(name, j.m_value.number_float);
  11650. case value_t::number_integer:
  11651. return write_bson_integer(name, j.m_value.number_integer);
  11652. case value_t::number_unsigned:
  11653. return write_bson_unsigned(name, j.m_value.number_unsigned);
  11654. case value_t::string:
  11655. return write_bson_string(name, *j.m_value.string);
  11656. case value_t::null:
  11657. return write_bson_null(name);
  11658. // LCOV_EXCL_START
  11659. default:
  11660. assert(false);
  11661. return;
  11662. // LCOV_EXCL_STOP
  11663. }
  11664. }
  11665. /*!
  11666. @brief Calculates the size of the BSON serialization of the given
  11667. JSON-object @a j.
  11668. @param[in] j JSON value to serialize
  11669. @pre j.type() == value_t::object
  11670. */
  11671. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  11672. {
  11673. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  11674. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  11675. {
  11676. return result += calc_bson_element_size(el.first, el.second);
  11677. });
  11678. return sizeof(std::int32_t) + document_size + 1ul;
  11679. }
  11680. /*!
  11681. @param[in] j JSON value to serialize
  11682. @pre j.type() == value_t::object
  11683. */
  11684. void write_bson_object(const typename BasicJsonType::object_t& value)
  11685. {
  11686. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  11687. for (const auto& el : value)
  11688. {
  11689. write_bson_element(el.first, el.second);
  11690. }
  11691. oa->write_character(to_char_type(0x00));
  11692. }
  11693. //////////
  11694. // CBOR //
  11695. //////////
  11696. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  11697. {
  11698. return to_char_type(0xFA); // Single-Precision Float
  11699. }
  11700. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  11701. {
  11702. return to_char_type(0xFB); // Double-Precision Float
  11703. }
  11704. /////////////
  11705. // MsgPack //
  11706. /////////////
  11707. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  11708. {
  11709. return to_char_type(0xCA); // float 32
  11710. }
  11711. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  11712. {
  11713. return to_char_type(0xCB); // float 64
  11714. }
  11715. ////////////
  11716. // UBJSON //
  11717. ////////////
  11718. // UBJSON: write number (floating point)
  11719. template<typename NumberType, typename std::enable_if<
  11720. std::is_floating_point<NumberType>::value, int>::type = 0>
  11721. void write_number_with_ubjson_prefix(const NumberType n,
  11722. const bool add_prefix)
  11723. {
  11724. if (add_prefix)
  11725. {
  11726. oa->write_character(get_ubjson_float_prefix(n));
  11727. }
  11728. write_number(n);
  11729. }
  11730. // UBJSON: write number (unsigned integer)
  11731. template<typename NumberType, typename std::enable_if<
  11732. std::is_unsigned<NumberType>::value, int>::type = 0>
  11733. void write_number_with_ubjson_prefix(const NumberType n,
  11734. const bool add_prefix)
  11735. {
  11736. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11737. {
  11738. if (add_prefix)
  11739. {
  11740. oa->write_character(to_char_type('i')); // int8
  11741. }
  11742. write_number(static_cast<std::uint8_t>(n));
  11743. }
  11744. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  11745. {
  11746. if (add_prefix)
  11747. {
  11748. oa->write_character(to_char_type('U')); // uint8
  11749. }
  11750. write_number(static_cast<std::uint8_t>(n));
  11751. }
  11752. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11753. {
  11754. if (add_prefix)
  11755. {
  11756. oa->write_character(to_char_type('I')); // int16
  11757. }
  11758. write_number(static_cast<std::int16_t>(n));
  11759. }
  11760. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11761. {
  11762. if (add_prefix)
  11763. {
  11764. oa->write_character(to_char_type('l')); // int32
  11765. }
  11766. write_number(static_cast<std::int32_t>(n));
  11767. }
  11768. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11769. {
  11770. if (add_prefix)
  11771. {
  11772. oa->write_character(to_char_type('L')); // int64
  11773. }
  11774. write_number(static_cast<std::int64_t>(n));
  11775. }
  11776. else
  11777. {
  11778. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11779. }
  11780. }
  11781. // UBJSON: write number (signed integer)
  11782. template<typename NumberType, typename std::enable_if<
  11783. std::is_signed<NumberType>::value and
  11784. not std::is_floating_point<NumberType>::value, int>::type = 0>
  11785. void write_number_with_ubjson_prefix(const NumberType n,
  11786. const bool add_prefix)
  11787. {
  11788. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  11789. {
  11790. if (add_prefix)
  11791. {
  11792. oa->write_character(to_char_type('i')); // int8
  11793. }
  11794. write_number(static_cast<std::int8_t>(n));
  11795. }
  11796. 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)()))
  11797. {
  11798. if (add_prefix)
  11799. {
  11800. oa->write_character(to_char_type('U')); // uint8
  11801. }
  11802. write_number(static_cast<std::uint8_t>(n));
  11803. }
  11804. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  11805. {
  11806. if (add_prefix)
  11807. {
  11808. oa->write_character(to_char_type('I')); // int16
  11809. }
  11810. write_number(static_cast<std::int16_t>(n));
  11811. }
  11812. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  11813. {
  11814. if (add_prefix)
  11815. {
  11816. oa->write_character(to_char_type('l')); // int32
  11817. }
  11818. write_number(static_cast<std::int32_t>(n));
  11819. }
  11820. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  11821. {
  11822. if (add_prefix)
  11823. {
  11824. oa->write_character(to_char_type('L')); // int64
  11825. }
  11826. write_number(static_cast<std::int64_t>(n));
  11827. }
  11828. // LCOV_EXCL_START
  11829. else
  11830. {
  11831. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11832. }
  11833. // LCOV_EXCL_STOP
  11834. }
  11835. /*!
  11836. @brief determine the type prefix of container values
  11837. @note This function does not need to be 100% accurate when it comes to
  11838. integer limits. In case a number exceeds the limits of int64_t,
  11839. this will be detected by a later call to function
  11840. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  11841. value that does not fit the previous limits.
  11842. */
  11843. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  11844. {
  11845. switch (j.type())
  11846. {
  11847. case value_t::null:
  11848. return 'Z';
  11849. case value_t::boolean:
  11850. return j.m_value.boolean ? 'T' : 'F';
  11851. case value_t::number_integer:
  11852. {
  11853. 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)())
  11854. {
  11855. return 'i';
  11856. }
  11857. 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)())
  11858. {
  11859. return 'U';
  11860. }
  11861. 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)())
  11862. {
  11863. return 'I';
  11864. }
  11865. 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)())
  11866. {
  11867. return 'l';
  11868. }
  11869. // no check and assume int64_t (see note above)
  11870. return 'L';
  11871. }
  11872. case value_t::number_unsigned:
  11873. {
  11874. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11875. {
  11876. return 'i';
  11877. }
  11878. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  11879. {
  11880. return 'U';
  11881. }
  11882. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11883. {
  11884. return 'I';
  11885. }
  11886. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11887. {
  11888. return 'l';
  11889. }
  11890. // no check and assume int64_t (see note above)
  11891. return 'L';
  11892. }
  11893. case value_t::number_float:
  11894. return get_ubjson_float_prefix(j.m_value.number_float);
  11895. case value_t::string:
  11896. return 'S';
  11897. case value_t::array: // fallthrough
  11898. case value_t::binary:
  11899. return '[';
  11900. case value_t::object:
  11901. return '{';
  11902. default: // discarded values
  11903. return 'N';
  11904. }
  11905. }
  11906. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  11907. {
  11908. return 'd'; // float 32
  11909. }
  11910. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  11911. {
  11912. return 'D'; // float 64
  11913. }
  11914. ///////////////////////
  11915. // Utility functions //
  11916. ///////////////////////
  11917. /*
  11918. @brief write a number to output input
  11919. @param[in] n number of type @a NumberType
  11920. @tparam NumberType the type of the number
  11921. @tparam OutputIsLittleEndian Set to true if output data is
  11922. required to be little endian
  11923. @note This function needs to respect the system's endianess, because bytes
  11924. in CBOR, MessagePack, and UBJSON are stored in network order (big
  11925. endian) and therefore need reordering on little endian systems.
  11926. */
  11927. template<typename NumberType, bool OutputIsLittleEndian = false>
  11928. void write_number(const NumberType n)
  11929. {
  11930. // step 1: write number to array of length NumberType
  11931. std::array<CharType, sizeof(NumberType)> vec;
  11932. std::memcpy(vec.data(), &n, sizeof(NumberType));
  11933. // step 2: write array to output (with possible reordering)
  11934. if (is_little_endian != OutputIsLittleEndian)
  11935. {
  11936. // reverse byte order prior to conversion if necessary
  11937. std::reverse(vec.begin(), vec.end());
  11938. }
  11939. oa->write_characters(vec.data(), sizeof(NumberType));
  11940. }
  11941. public:
  11942. // The following to_char_type functions are implement the conversion
  11943. // between uint8_t and CharType. In case CharType is not unsigned,
  11944. // such a conversion is required to allow values greater than 128.
  11945. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  11946. template < typename C = CharType,
  11947. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  11948. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  11949. {
  11950. return *reinterpret_cast<char*>(&x);
  11951. }
  11952. template < typename C = CharType,
  11953. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  11954. static CharType to_char_type(std::uint8_t x) noexcept
  11955. {
  11956. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  11957. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  11958. CharType result;
  11959. std::memcpy(&result, &x, sizeof(x));
  11960. return result;
  11961. }
  11962. template<typename C = CharType,
  11963. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  11964. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  11965. {
  11966. return x;
  11967. }
  11968. template < typename InputCharType, typename C = CharType,
  11969. enable_if_t <
  11970. std::is_signed<C>::value and
  11971. std::is_signed<char>::value and
  11972. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  11973. > * = nullptr >
  11974. static constexpr CharType to_char_type(InputCharType x) noexcept
  11975. {
  11976. return x;
  11977. }
  11978. private:
  11979. /// whether we can assume little endianess
  11980. const bool is_little_endian = little_endianess();
  11981. /// the output
  11982. output_adapter_t<CharType> oa = nullptr;
  11983. };
  11984. } // namespace detail
  11985. } // namespace nlohmann
  11986. // #include <nlohmann/detail/output/output_adapters.hpp>
  11987. // #include <nlohmann/detail/output/serializer.hpp>
  11988. #include <algorithm> // reverse, remove, fill, find, none_of
  11989. #include <array> // array
  11990. #include <cassert> // assert
  11991. #include <clocale> // localeconv, lconv
  11992. #include <cmath> // labs, isfinite, isnan, signbit
  11993. #include <cstddef> // size_t, ptrdiff_t
  11994. #include <cstdint> // uint8_t
  11995. #include <cstdio> // snprintf
  11996. #include <limits> // numeric_limits
  11997. #include <string> // string
  11998. #include <type_traits> // is_same
  11999. #include <utility> // move
  12000. // #include <nlohmann/detail/boolean_operators.hpp>
  12001. // #include <nlohmann/detail/conversions/to_chars.hpp>
  12002. #include <array> // array
  12003. #include <cassert> // assert
  12004. #include <cmath> // signbit, isfinite
  12005. #include <cstdint> // intN_t, uintN_t
  12006. #include <cstring> // memcpy, memmove
  12007. #include <limits> // numeric_limits
  12008. #include <type_traits> // conditional
  12009. // #include <nlohmann/detail/boolean_operators.hpp>
  12010. // #include <nlohmann/detail/macro_scope.hpp>
  12011. namespace nlohmann
  12012. {
  12013. namespace detail
  12014. {
  12015. /*!
  12016. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  12017. conversion.
  12018. This implementation is a slightly modified version of the reference
  12019. implementation which may be obtained from
  12020. http://florian.loitsch.com/publications (bench.tar.gz).
  12021. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  12022. For a detailed description of the algorithm see:
  12023. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  12024. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  12025. Language Design and Implementation, PLDI 2010
  12026. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  12027. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  12028. Design and Implementation, PLDI 1996
  12029. */
  12030. namespace dtoa_impl
  12031. {
  12032. template <typename Target, typename Source>
  12033. Target reinterpret_bits(const Source source)
  12034. {
  12035. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  12036. Target target;
  12037. std::memcpy(&target, &source, sizeof(Source));
  12038. return target;
  12039. }
  12040. struct diyfp // f * 2^e
  12041. {
  12042. static constexpr int kPrecision = 64; // = q
  12043. std::uint64_t f = 0;
  12044. int e = 0;
  12045. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  12046. /*!
  12047. @brief returns x - y
  12048. @pre x.e == y.e and x.f >= y.f
  12049. */
  12050. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  12051. {
  12052. assert(x.e == y.e);
  12053. assert(x.f >= y.f);
  12054. return {x.f - y.f, x.e};
  12055. }
  12056. /*!
  12057. @brief returns x * y
  12058. @note The result is rounded. (Only the upper q bits are returned.)
  12059. */
  12060. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  12061. {
  12062. static_assert(kPrecision == 64, "internal error");
  12063. // Computes:
  12064. // f = round((x.f * y.f) / 2^q)
  12065. // e = x.e + y.e + q
  12066. // Emulate the 64-bit * 64-bit multiplication:
  12067. //
  12068. // p = u * v
  12069. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  12070. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  12071. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  12072. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  12073. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  12074. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  12075. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  12076. //
  12077. // (Since Q might be larger than 2^32 - 1)
  12078. //
  12079. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  12080. //
  12081. // (Q_hi + H does not overflow a 64-bit int)
  12082. //
  12083. // = p_lo + 2^64 p_hi
  12084. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  12085. const std::uint64_t u_hi = x.f >> 32u;
  12086. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  12087. const std::uint64_t v_hi = y.f >> 32u;
  12088. const std::uint64_t p0 = u_lo * v_lo;
  12089. const std::uint64_t p1 = u_lo * v_hi;
  12090. const std::uint64_t p2 = u_hi * v_lo;
  12091. const std::uint64_t p3 = u_hi * v_hi;
  12092. const std::uint64_t p0_hi = p0 >> 32u;
  12093. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  12094. const std::uint64_t p1_hi = p1 >> 32u;
  12095. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  12096. const std::uint64_t p2_hi = p2 >> 32u;
  12097. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  12098. // The full product might now be computed as
  12099. //
  12100. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  12101. // p_lo = p0_lo + (Q << 32)
  12102. //
  12103. // But in this particular case here, the full p_lo is not required.
  12104. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  12105. // Q_hi + 1 does not overflow).
  12106. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  12107. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  12108. return {h, x.e + y.e + 64};
  12109. }
  12110. /*!
  12111. @brief normalize x such that the significand is >= 2^(q-1)
  12112. @pre x.f != 0
  12113. */
  12114. static diyfp normalize(diyfp x) noexcept
  12115. {
  12116. assert(x.f != 0);
  12117. while ((x.f >> 63u) == 0)
  12118. {
  12119. x.f <<= 1u;
  12120. x.e--;
  12121. }
  12122. return x;
  12123. }
  12124. /*!
  12125. @brief normalize x such that the result has the exponent E
  12126. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  12127. */
  12128. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  12129. {
  12130. const int delta = x.e - target_exponent;
  12131. assert(delta >= 0);
  12132. assert(((x.f << delta) >> delta) == x.f);
  12133. return {x.f << delta, target_exponent};
  12134. }
  12135. };
  12136. struct boundaries
  12137. {
  12138. diyfp w;
  12139. diyfp minus;
  12140. diyfp plus;
  12141. };
  12142. /*!
  12143. Compute the (normalized) diyfp representing the input number 'value' and its
  12144. boundaries.
  12145. @pre value must be finite and positive
  12146. */
  12147. template <typename FloatType>
  12148. boundaries compute_boundaries(FloatType value)
  12149. {
  12150. assert(std::isfinite(value));
  12151. assert(value > 0);
  12152. // Convert the IEEE representation into a diyfp.
  12153. //
  12154. // If v is denormal:
  12155. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  12156. // If v is normalized:
  12157. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  12158. static_assert(std::numeric_limits<FloatType>::is_iec559,
  12159. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  12160. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  12161. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  12162. constexpr int kMinExp = 1 - kBias;
  12163. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  12164. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  12165. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  12166. const std::uint64_t E = bits >> (kPrecision - 1);
  12167. const std::uint64_t F = bits & (kHiddenBit - 1);
  12168. const bool is_denormal = E == 0;
  12169. const diyfp v = is_denormal
  12170. ? diyfp(F, kMinExp)
  12171. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  12172. // Compute the boundaries m- and m+ of the floating-point value
  12173. // v = f * 2^e.
  12174. //
  12175. // Determine v- and v+, the floating-point predecessor and successor if v,
  12176. // respectively.
  12177. //
  12178. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  12179. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  12180. //
  12181. // v+ = v + 2^e
  12182. //
  12183. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  12184. // between m- and m+ round to v, regardless of how the input rounding
  12185. // algorithm breaks ties.
  12186. //
  12187. // ---+-------------+-------------+-------------+-------------+--- (A)
  12188. // v- m- v m+ v+
  12189. //
  12190. // -----------------+------+------+-------------+-------------+--- (B)
  12191. // v- m- v m+ v+
  12192. const bool lower_boundary_is_closer = F == 0 and E > 1;
  12193. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  12194. const diyfp m_minus = lower_boundary_is_closer
  12195. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  12196. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  12197. // Determine the normalized w+ = m+.
  12198. const diyfp w_plus = diyfp::normalize(m_plus);
  12199. // Determine w- = m- such that e_(w-) = e_(w+).
  12200. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  12201. return {diyfp::normalize(v), w_minus, w_plus};
  12202. }
  12203. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  12204. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  12205. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  12206. //
  12207. // alpha <= e = e_c + e_w + q <= gamma
  12208. //
  12209. // or
  12210. //
  12211. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  12212. // <= f_c * f_w * 2^gamma
  12213. //
  12214. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  12215. //
  12216. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  12217. //
  12218. // or
  12219. //
  12220. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  12221. //
  12222. // The choice of (alpha,gamma) determines the size of the table and the form of
  12223. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  12224. // in practice:
  12225. //
  12226. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  12227. // processed independently: An integral part p1, and a fractional part p2:
  12228. //
  12229. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  12230. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  12231. // = p1 + p2 * 2^e
  12232. //
  12233. // The conversion of p1 into decimal form requires a series of divisions and
  12234. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  12235. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  12236. // achieved by choosing
  12237. //
  12238. // -e >= 32 or e <= -32 := gamma
  12239. //
  12240. // In order to convert the fractional part
  12241. //
  12242. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12243. //
  12244. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  12245. // d[-i] are extracted in order:
  12246. //
  12247. // (10 * p2) div 2^-e = d[-1]
  12248. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  12249. //
  12250. // The multiplication by 10 must not overflow. It is sufficient to choose
  12251. //
  12252. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  12253. //
  12254. // Since p2 = f mod 2^-e < 2^-e,
  12255. //
  12256. // -e <= 60 or e >= -60 := alpha
  12257. constexpr int kAlpha = -60;
  12258. constexpr int kGamma = -32;
  12259. struct cached_power // c = f * 2^e ~= 10^k
  12260. {
  12261. std::uint64_t f;
  12262. int e;
  12263. int k;
  12264. };
  12265. /*!
  12266. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  12267. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  12268. satisfies (Definition 3.2 from [1])
  12269. alpha <= e_c + e + q <= gamma.
  12270. */
  12271. inline cached_power get_cached_power_for_binary_exponent(int e)
  12272. {
  12273. // Now
  12274. //
  12275. // alpha <= e_c + e + q <= gamma (1)
  12276. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  12277. //
  12278. // and since the c's are normalized, 2^(q-1) <= f_c,
  12279. //
  12280. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  12281. // ==> 2^(alpha - e - 1) <= c
  12282. //
  12283. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  12284. //
  12285. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  12286. // = ceil( (alpha - e - 1) * log_10(2) )
  12287. //
  12288. // From the paper:
  12289. // "In theory the result of the procedure could be wrong since c is rounded,
  12290. // and the computation itself is approximated [...]. In practice, however,
  12291. // this simple function is sufficient."
  12292. //
  12293. // For IEEE double precision floating-point numbers converted into
  12294. // normalized diyfp's w = f * 2^e, with q = 64,
  12295. //
  12296. // e >= -1022 (min IEEE exponent)
  12297. // -52 (p - 1)
  12298. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  12299. // -11 (normalize the diyfp)
  12300. // = -1137
  12301. //
  12302. // and
  12303. //
  12304. // e <= +1023 (max IEEE exponent)
  12305. // -52 (p - 1)
  12306. // -11 (normalize the diyfp)
  12307. // = 960
  12308. //
  12309. // This binary exponent range [-1137,960] results in a decimal exponent
  12310. // range [-307,324]. One does not need to store a cached power for each
  12311. // k in this range. For each such k it suffices to find a cached power
  12312. // such that the exponent of the product lies in [alpha,gamma].
  12313. // This implies that the difference of the decimal exponents of adjacent
  12314. // table entries must be less than or equal to
  12315. //
  12316. // floor( (gamma - alpha) * log_10(2) ) = 8.
  12317. //
  12318. // (A smaller distance gamma-alpha would require a larger table.)
  12319. // NB:
  12320. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  12321. constexpr int kCachedPowersMinDecExp = -300;
  12322. constexpr int kCachedPowersDecStep = 8;
  12323. static constexpr std::array<cached_power, 79> kCachedPowers =
  12324. {
  12325. {
  12326. { 0xAB70FE17C79AC6CA, -1060, -300 },
  12327. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  12328. { 0xBE5691EF416BD60C, -1007, -284 },
  12329. { 0x8DD01FAD907FFC3C, -980, -276 },
  12330. { 0xD3515C2831559A83, -954, -268 },
  12331. { 0x9D71AC8FADA6C9B5, -927, -260 },
  12332. { 0xEA9C227723EE8BCB, -901, -252 },
  12333. { 0xAECC49914078536D, -874, -244 },
  12334. { 0x823C12795DB6CE57, -847, -236 },
  12335. { 0xC21094364DFB5637, -821, -228 },
  12336. { 0x9096EA6F3848984F, -794, -220 },
  12337. { 0xD77485CB25823AC7, -768, -212 },
  12338. { 0xA086CFCD97BF97F4, -741, -204 },
  12339. { 0xEF340A98172AACE5, -715, -196 },
  12340. { 0xB23867FB2A35B28E, -688, -188 },
  12341. { 0x84C8D4DFD2C63F3B, -661, -180 },
  12342. { 0xC5DD44271AD3CDBA, -635, -172 },
  12343. { 0x936B9FCEBB25C996, -608, -164 },
  12344. { 0xDBAC6C247D62A584, -582, -156 },
  12345. { 0xA3AB66580D5FDAF6, -555, -148 },
  12346. { 0xF3E2F893DEC3F126, -529, -140 },
  12347. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  12348. { 0x87625F056C7C4A8B, -475, -124 },
  12349. { 0xC9BCFF6034C13053, -449, -116 },
  12350. { 0x964E858C91BA2655, -422, -108 },
  12351. { 0xDFF9772470297EBD, -396, -100 },
  12352. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  12353. { 0xF8A95FCF88747D94, -343, -84 },
  12354. { 0xB94470938FA89BCF, -316, -76 },
  12355. { 0x8A08F0F8BF0F156B, -289, -68 },
  12356. { 0xCDB02555653131B6, -263, -60 },
  12357. { 0x993FE2C6D07B7FAC, -236, -52 },
  12358. { 0xE45C10C42A2B3B06, -210, -44 },
  12359. { 0xAA242499697392D3, -183, -36 },
  12360. { 0xFD87B5F28300CA0E, -157, -28 },
  12361. { 0xBCE5086492111AEB, -130, -20 },
  12362. { 0x8CBCCC096F5088CC, -103, -12 },
  12363. { 0xD1B71758E219652C, -77, -4 },
  12364. { 0x9C40000000000000, -50, 4 },
  12365. { 0xE8D4A51000000000, -24, 12 },
  12366. { 0xAD78EBC5AC620000, 3, 20 },
  12367. { 0x813F3978F8940984, 30, 28 },
  12368. { 0xC097CE7BC90715B3, 56, 36 },
  12369. { 0x8F7E32CE7BEA5C70, 83, 44 },
  12370. { 0xD5D238A4ABE98068, 109, 52 },
  12371. { 0x9F4F2726179A2245, 136, 60 },
  12372. { 0xED63A231D4C4FB27, 162, 68 },
  12373. { 0xB0DE65388CC8ADA8, 189, 76 },
  12374. { 0x83C7088E1AAB65DB, 216, 84 },
  12375. { 0xC45D1DF942711D9A, 242, 92 },
  12376. { 0x924D692CA61BE758, 269, 100 },
  12377. { 0xDA01EE641A708DEA, 295, 108 },
  12378. { 0xA26DA3999AEF774A, 322, 116 },
  12379. { 0xF209787BB47D6B85, 348, 124 },
  12380. { 0xB454E4A179DD1877, 375, 132 },
  12381. { 0x865B86925B9BC5C2, 402, 140 },
  12382. { 0xC83553C5C8965D3D, 428, 148 },
  12383. { 0x952AB45CFA97A0B3, 455, 156 },
  12384. { 0xDE469FBD99A05FE3, 481, 164 },
  12385. { 0xA59BC234DB398C25, 508, 172 },
  12386. { 0xF6C69A72A3989F5C, 534, 180 },
  12387. { 0xB7DCBF5354E9BECE, 561, 188 },
  12388. { 0x88FCF317F22241E2, 588, 196 },
  12389. { 0xCC20CE9BD35C78A5, 614, 204 },
  12390. { 0x98165AF37B2153DF, 641, 212 },
  12391. { 0xE2A0B5DC971F303A, 667, 220 },
  12392. { 0xA8D9D1535CE3B396, 694, 228 },
  12393. { 0xFB9B7CD9A4A7443C, 720, 236 },
  12394. { 0xBB764C4CA7A44410, 747, 244 },
  12395. { 0x8BAB8EEFB6409C1A, 774, 252 },
  12396. { 0xD01FEF10A657842C, 800, 260 },
  12397. { 0x9B10A4E5E9913129, 827, 268 },
  12398. { 0xE7109BFBA19C0C9D, 853, 276 },
  12399. { 0xAC2820D9623BF429, 880, 284 },
  12400. { 0x80444B5E7AA7CF85, 907, 292 },
  12401. { 0xBF21E44003ACDD2D, 933, 300 },
  12402. { 0x8E679C2F5E44FF8F, 960, 308 },
  12403. { 0xD433179D9C8CB841, 986, 316 },
  12404. { 0x9E19DB92B4E31BA9, 1013, 324 },
  12405. }
  12406. };
  12407. // This computation gives exactly the same results for k as
  12408. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  12409. // for |e| <= 1500, but doesn't require floating-point operations.
  12410. // NB: log_10(2) ~= 78913 / 2^18
  12411. assert(e >= -1500);
  12412. assert(e <= 1500);
  12413. const int f = kAlpha - e - 1;
  12414. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  12415. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  12416. assert(index >= 0);
  12417. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  12418. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  12419. assert(kAlpha <= cached.e + e + 64);
  12420. assert(kGamma >= cached.e + e + 64);
  12421. return cached;
  12422. }
  12423. /*!
  12424. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  12425. For n == 0, returns 1 and sets pow10 := 1.
  12426. */
  12427. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  12428. {
  12429. // LCOV_EXCL_START
  12430. if (n >= 1000000000)
  12431. {
  12432. pow10 = 1000000000;
  12433. return 10;
  12434. }
  12435. // LCOV_EXCL_STOP
  12436. else if (n >= 100000000)
  12437. {
  12438. pow10 = 100000000;
  12439. return 9;
  12440. }
  12441. else if (n >= 10000000)
  12442. {
  12443. pow10 = 10000000;
  12444. return 8;
  12445. }
  12446. else if (n >= 1000000)
  12447. {
  12448. pow10 = 1000000;
  12449. return 7;
  12450. }
  12451. else if (n >= 100000)
  12452. {
  12453. pow10 = 100000;
  12454. return 6;
  12455. }
  12456. else if (n >= 10000)
  12457. {
  12458. pow10 = 10000;
  12459. return 5;
  12460. }
  12461. else if (n >= 1000)
  12462. {
  12463. pow10 = 1000;
  12464. return 4;
  12465. }
  12466. else if (n >= 100)
  12467. {
  12468. pow10 = 100;
  12469. return 3;
  12470. }
  12471. else if (n >= 10)
  12472. {
  12473. pow10 = 10;
  12474. return 2;
  12475. }
  12476. else
  12477. {
  12478. pow10 = 1;
  12479. return 1;
  12480. }
  12481. }
  12482. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  12483. std::uint64_t rest, std::uint64_t ten_k)
  12484. {
  12485. assert(len >= 1);
  12486. assert(dist <= delta);
  12487. assert(rest <= delta);
  12488. assert(ten_k > 0);
  12489. // <--------------------------- delta ---->
  12490. // <---- dist --------->
  12491. // --------------[------------------+-------------------]--------------
  12492. // M- w M+
  12493. //
  12494. // ten_k
  12495. // <------>
  12496. // <---- rest ---->
  12497. // --------------[------------------+----+--------------]--------------
  12498. // w V
  12499. // = buf * 10^k
  12500. //
  12501. // ten_k represents a unit-in-the-last-place in the decimal representation
  12502. // stored in buf.
  12503. // Decrement buf by ten_k while this takes buf closer to w.
  12504. // The tests are written in this order to avoid overflow in unsigned
  12505. // integer arithmetic.
  12506. while (rest < dist
  12507. and delta - rest >= ten_k
  12508. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  12509. {
  12510. assert(buf[len - 1] != '0');
  12511. buf[len - 1]--;
  12512. rest += ten_k;
  12513. }
  12514. }
  12515. /*!
  12516. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  12517. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  12518. */
  12519. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  12520. diyfp M_minus, diyfp w, diyfp M_plus)
  12521. {
  12522. static_assert(kAlpha >= -60, "internal error");
  12523. static_assert(kGamma <= -32, "internal error");
  12524. // Generates the digits (and the exponent) of a decimal floating-point
  12525. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  12526. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  12527. //
  12528. // <--------------------------- delta ---->
  12529. // <---- dist --------->
  12530. // --------------[------------------+-------------------]--------------
  12531. // M- w M+
  12532. //
  12533. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  12534. // V is in [M-,M+].
  12535. assert(M_plus.e >= kAlpha);
  12536. assert(M_plus.e <= kGamma);
  12537. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  12538. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  12539. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  12540. //
  12541. // M+ = f * 2^e
  12542. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  12543. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  12544. // = p1 + p2 * 2^e
  12545. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  12546. 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.)
  12547. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  12548. // 1)
  12549. //
  12550. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  12551. assert(p1 > 0);
  12552. std::uint32_t pow10;
  12553. const int k = find_largest_pow10(p1, pow10);
  12554. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  12555. //
  12556. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  12557. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  12558. //
  12559. // M+ = p1 + p2 * 2^e
  12560. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  12561. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  12562. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  12563. //
  12564. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  12565. //
  12566. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  12567. //
  12568. // but stop as soon as
  12569. //
  12570. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  12571. int n = k;
  12572. while (n > 0)
  12573. {
  12574. // Invariants:
  12575. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  12576. // pow10 = 10^(n-1) <= p1 < 10^n
  12577. //
  12578. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  12579. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  12580. //
  12581. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  12582. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  12583. //
  12584. assert(d <= 9);
  12585. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12586. //
  12587. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  12588. //
  12589. p1 = r;
  12590. n--;
  12591. //
  12592. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  12593. // pow10 = 10^n
  12594. //
  12595. // Now check if enough digits have been generated.
  12596. // Compute
  12597. //
  12598. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  12599. //
  12600. // Note:
  12601. // Since rest and delta share the same exponent e, it suffices to
  12602. // compare the significands.
  12603. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  12604. if (rest <= delta)
  12605. {
  12606. // V = buffer * 10^n, with M- <= V <= M+.
  12607. decimal_exponent += n;
  12608. // We may now just stop. But instead look if the buffer could be
  12609. // decremented to bring V closer to w.
  12610. //
  12611. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  12612. // The rounding procedure works with diyfp's with an implicit
  12613. // exponent of e.
  12614. //
  12615. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  12616. //
  12617. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  12618. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  12619. return;
  12620. }
  12621. pow10 /= 10;
  12622. //
  12623. // pow10 = 10^(n-1) <= p1 < 10^n
  12624. // Invariants restored.
  12625. }
  12626. // 2)
  12627. //
  12628. // The digits of the integral part have been generated:
  12629. //
  12630. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  12631. // = buffer + p2 * 2^e
  12632. //
  12633. // Now generate the digits of the fractional part p2 * 2^e.
  12634. //
  12635. // Note:
  12636. // No decimal point is generated: the exponent is adjusted instead.
  12637. //
  12638. // p2 actually represents the fraction
  12639. //
  12640. // p2 * 2^e
  12641. // = p2 / 2^-e
  12642. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12643. //
  12644. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  12645. //
  12646. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  12647. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  12648. //
  12649. // using
  12650. //
  12651. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  12652. // = ( d) * 2^-e + ( r)
  12653. //
  12654. // or
  12655. // 10^m * p2 * 2^e = d + r * 2^e
  12656. //
  12657. // i.e.
  12658. //
  12659. // M+ = buffer + p2 * 2^e
  12660. // = buffer + 10^-m * (d + r * 2^e)
  12661. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  12662. //
  12663. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  12664. assert(p2 > delta);
  12665. int m = 0;
  12666. for (;;)
  12667. {
  12668. // Invariant:
  12669. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  12670. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  12671. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  12672. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  12673. //
  12674. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  12675. p2 *= 10;
  12676. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  12677. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  12678. //
  12679. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  12680. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  12681. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12682. //
  12683. assert(d <= 9);
  12684. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12685. //
  12686. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12687. //
  12688. p2 = r;
  12689. m++;
  12690. //
  12691. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  12692. // Invariant restored.
  12693. // Check if enough digits have been generated.
  12694. //
  12695. // 10^-m * p2 * 2^e <= delta * 2^e
  12696. // p2 * 2^e <= 10^m * delta * 2^e
  12697. // p2 <= 10^m * delta
  12698. delta *= 10;
  12699. dist *= 10;
  12700. if (p2 <= delta)
  12701. {
  12702. break;
  12703. }
  12704. }
  12705. // V = buffer * 10^-m, with M- <= V <= M+.
  12706. decimal_exponent -= m;
  12707. // 1 ulp in the decimal representation is now 10^-m.
  12708. // Since delta and dist are now scaled by 10^m, we need to do the
  12709. // same with ulp in order to keep the units in sync.
  12710. //
  12711. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  12712. //
  12713. const std::uint64_t ten_m = one.f;
  12714. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  12715. // By construction this algorithm generates the shortest possible decimal
  12716. // number (Loitsch, Theorem 6.2) which rounds back to w.
  12717. // For an input number of precision p, at least
  12718. //
  12719. // N = 1 + ceil(p * log_10(2))
  12720. //
  12721. // decimal digits are sufficient to identify all binary floating-point
  12722. // numbers (Matula, "In-and-Out conversions").
  12723. // This implies that the algorithm does not produce more than N decimal
  12724. // digits.
  12725. //
  12726. // N = 17 for p = 53 (IEEE double precision)
  12727. // N = 9 for p = 24 (IEEE single precision)
  12728. }
  12729. /*!
  12730. v = buf * 10^decimal_exponent
  12731. len is the length of the buffer (number of decimal digits)
  12732. The buffer must be large enough, i.e. >= max_digits10.
  12733. */
  12734. JSON_HEDLEY_NON_NULL(1)
  12735. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  12736. diyfp m_minus, diyfp v, diyfp m_plus)
  12737. {
  12738. assert(m_plus.e == m_minus.e);
  12739. assert(m_plus.e == v.e);
  12740. // --------(-----------------------+-----------------------)-------- (A)
  12741. // m- v m+
  12742. //
  12743. // --------------------(-----------+-----------------------)-------- (B)
  12744. // m- v m+
  12745. //
  12746. // First scale v (and m- and m+) such that the exponent is in the range
  12747. // [alpha, gamma].
  12748. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  12749. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  12750. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  12751. const diyfp w = diyfp::mul(v, c_minus_k);
  12752. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  12753. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  12754. // ----(---+---)---------------(---+---)---------------(---+---)----
  12755. // w- w w+
  12756. // = c*m- = c*v = c*m+
  12757. //
  12758. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  12759. // w+ are now off by a small amount.
  12760. // In fact:
  12761. //
  12762. // w - v * 10^k < 1 ulp
  12763. //
  12764. // To account for this inaccuracy, add resp. subtract 1 ulp.
  12765. //
  12766. // --------+---[---------------(---+---)---------------]---+--------
  12767. // w- M- w M+ w+
  12768. //
  12769. // Now any number in [M-, M+] (bounds included) will round to w when input,
  12770. // regardless of how the input rounding algorithm breaks ties.
  12771. //
  12772. // And digit_gen generates the shortest possible such number in [M-, M+].
  12773. // Note that this does not mean that Grisu2 always generates the shortest
  12774. // possible number in the interval (m-, m+).
  12775. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  12776. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  12777. decimal_exponent = -cached.k; // = -(-k) = k
  12778. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  12779. }
  12780. /*!
  12781. v = buf * 10^decimal_exponent
  12782. len is the length of the buffer (number of decimal digits)
  12783. The buffer must be large enough, i.e. >= max_digits10.
  12784. */
  12785. template <typename FloatType>
  12786. JSON_HEDLEY_NON_NULL(1)
  12787. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  12788. {
  12789. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  12790. "internal error: not enough precision");
  12791. assert(std::isfinite(value));
  12792. assert(value > 0);
  12793. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  12794. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  12795. // decimal representations are not exactly "short".
  12796. //
  12797. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  12798. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  12799. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  12800. // does.
  12801. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  12802. // representation using the corresponding std::from_chars function recovers value exactly". That
  12803. // indicates that single precision floating-point numbers should be recovered using
  12804. // 'std::strtof'.
  12805. //
  12806. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  12807. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  12808. // value is off by 1 ulp.
  12809. #if 0
  12810. const boundaries w = compute_boundaries(static_cast<double>(value));
  12811. #else
  12812. const boundaries w = compute_boundaries(value);
  12813. #endif
  12814. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  12815. }
  12816. /*!
  12817. @brief appends a decimal representation of e to buf
  12818. @return a pointer to the element following the exponent.
  12819. @pre -1000 < e < 1000
  12820. */
  12821. JSON_HEDLEY_NON_NULL(1)
  12822. JSON_HEDLEY_RETURNS_NON_NULL
  12823. inline char* append_exponent(char* buf, int e)
  12824. {
  12825. assert(e > -1000);
  12826. assert(e < 1000);
  12827. if (e < 0)
  12828. {
  12829. e = -e;
  12830. *buf++ = '-';
  12831. }
  12832. else
  12833. {
  12834. *buf++ = '+';
  12835. }
  12836. auto k = static_cast<std::uint32_t>(e);
  12837. if (k < 10)
  12838. {
  12839. // Always print at least two digits in the exponent.
  12840. // This is for compatibility with printf("%g").
  12841. *buf++ = '0';
  12842. *buf++ = static_cast<char>('0' + k);
  12843. }
  12844. else if (k < 100)
  12845. {
  12846. *buf++ = static_cast<char>('0' + k / 10);
  12847. k %= 10;
  12848. *buf++ = static_cast<char>('0' + k);
  12849. }
  12850. else
  12851. {
  12852. *buf++ = static_cast<char>('0' + k / 100);
  12853. k %= 100;
  12854. *buf++ = static_cast<char>('0' + k / 10);
  12855. k %= 10;
  12856. *buf++ = static_cast<char>('0' + k);
  12857. }
  12858. return buf;
  12859. }
  12860. /*!
  12861. @brief prettify v = buf * 10^decimal_exponent
  12862. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  12863. notation. Otherwise it will be printed in exponential notation.
  12864. @pre min_exp < 0
  12865. @pre max_exp > 0
  12866. */
  12867. JSON_HEDLEY_NON_NULL(1)
  12868. JSON_HEDLEY_RETURNS_NON_NULL
  12869. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  12870. int min_exp, int max_exp)
  12871. {
  12872. assert(min_exp < 0);
  12873. assert(max_exp > 0);
  12874. const int k = len;
  12875. const int n = len + decimal_exponent;
  12876. // v = buf * 10^(n-k)
  12877. // k is the length of the buffer (number of decimal digits)
  12878. // n is the position of the decimal point relative to the start of the buffer.
  12879. if (k <= n and n <= max_exp)
  12880. {
  12881. // digits[000]
  12882. // len <= max_exp + 2
  12883. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  12884. // Make it look like a floating-point number (#362, #378)
  12885. buf[n + 0] = '.';
  12886. buf[n + 1] = '0';
  12887. return buf + (static_cast<size_t>(n) + 2);
  12888. }
  12889. if (0 < n and n <= max_exp)
  12890. {
  12891. // dig.its
  12892. // len <= max_digits10 + 1
  12893. assert(k > n);
  12894. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  12895. buf[n] = '.';
  12896. return buf + (static_cast<size_t>(k) + 1U);
  12897. }
  12898. if (min_exp < n and n <= 0)
  12899. {
  12900. // 0.[000]digits
  12901. // len <= 2 + (-min_exp - 1) + max_digits10
  12902. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  12903. buf[0] = '0';
  12904. buf[1] = '.';
  12905. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  12906. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  12907. }
  12908. if (k == 1)
  12909. {
  12910. // dE+123
  12911. // len <= 1 + 5
  12912. buf += 1;
  12913. }
  12914. else
  12915. {
  12916. // d.igitsE+123
  12917. // len <= max_digits10 + 1 + 5
  12918. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  12919. buf[1] = '.';
  12920. buf += 1 + static_cast<size_t>(k);
  12921. }
  12922. *buf++ = 'e';
  12923. return append_exponent(buf, n - 1);
  12924. }
  12925. } // namespace dtoa_impl
  12926. /*!
  12927. @brief generates a decimal representation of the floating-point number value in [first, last).
  12928. The format of the resulting decimal representation is similar to printf's %g
  12929. format. Returns an iterator pointing past-the-end of the decimal representation.
  12930. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  12931. @note The buffer must be large enough.
  12932. @note The result is NOT null-terminated.
  12933. */
  12934. template <typename FloatType>
  12935. JSON_HEDLEY_NON_NULL(1, 2)
  12936. JSON_HEDLEY_RETURNS_NON_NULL
  12937. char* to_chars(char* first, const char* last, FloatType value)
  12938. {
  12939. static_cast<void>(last); // maybe unused - fix warning
  12940. assert(std::isfinite(value));
  12941. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  12942. if (std::signbit(value))
  12943. {
  12944. value = -value;
  12945. *first++ = '-';
  12946. }
  12947. if (value == 0) // +-0
  12948. {
  12949. *first++ = '0';
  12950. // Make it look like a floating-point number (#362, #378)
  12951. *first++ = '.';
  12952. *first++ = '0';
  12953. return first;
  12954. }
  12955. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  12956. // Compute v = buffer * 10^decimal_exponent.
  12957. // The decimal digits are stored in the buffer, which needs to be interpreted
  12958. // as an unsigned decimal integer.
  12959. // len is the length of the buffer, i.e. the number of decimal digits.
  12960. int len = 0;
  12961. int decimal_exponent = 0;
  12962. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  12963. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  12964. // Format the buffer like printf("%.*g", prec, value)
  12965. constexpr int kMinExp = -4;
  12966. // Use digits10 here to increase compatibility with version 2.
  12967. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  12968. assert(last - first >= kMaxExp + 2);
  12969. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  12970. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  12971. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  12972. }
  12973. } // namespace detail
  12974. } // namespace nlohmann
  12975. // #include <nlohmann/detail/exceptions.hpp>
  12976. // #include <nlohmann/detail/macro_scope.hpp>
  12977. // #include <nlohmann/detail/meta/cpp_future.hpp>
  12978. // #include <nlohmann/detail/output/binary_writer.hpp>
  12979. // #include <nlohmann/detail/output/output_adapters.hpp>
  12980. // #include <nlohmann/detail/value_t.hpp>
  12981. namespace nlohmann
  12982. {
  12983. namespace detail
  12984. {
  12985. ///////////////////
  12986. // serialization //
  12987. ///////////////////
  12988. /// how to treat decoding errors
  12989. enum class error_handler_t
  12990. {
  12991. strict, ///< throw a type_error exception in case of invalid UTF-8
  12992. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  12993. ignore ///< ignore invalid UTF-8 sequences
  12994. };
  12995. template<typename BasicJsonType>
  12996. class serializer
  12997. {
  12998. using string_t = typename BasicJsonType::string_t;
  12999. using number_float_t = typename BasicJsonType::number_float_t;
  13000. using number_integer_t = typename BasicJsonType::number_integer_t;
  13001. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13002. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  13003. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  13004. static constexpr std::uint8_t UTF8_REJECT = 1;
  13005. public:
  13006. /*!
  13007. @param[in] s output stream to serialize to
  13008. @param[in] ichar indentation character to use
  13009. @param[in] error_handler_ how to react on decoding errors
  13010. */
  13011. serializer(output_adapter_t<char> s, const char ichar,
  13012. error_handler_t error_handler_ = error_handler_t::strict)
  13013. : o(std::move(s))
  13014. , loc(std::localeconv())
  13015. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  13016. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  13017. , indent_char(ichar)
  13018. , indent_string(512, indent_char)
  13019. , error_handler(error_handler_)
  13020. {}
  13021. // delete because of pointer members
  13022. serializer(const serializer&) = delete;
  13023. serializer& operator=(const serializer&) = delete;
  13024. serializer(serializer&&) = delete;
  13025. serializer& operator=(serializer&&) = delete;
  13026. ~serializer() = default;
  13027. /*!
  13028. @brief internal implementation of the serialization function
  13029. This function is called by the public member function dump and organizes
  13030. the serialization internally. The indentation level is propagated as
  13031. additional parameter. In case of arrays and objects, the function is
  13032. called recursively.
  13033. - strings and object keys are escaped using `escape_string()`
  13034. - integer numbers are converted implicitly via `operator<<`
  13035. - floating-point numbers are converted to a string using `"%g"` format
  13036. - binary values are serialized as objects containing the subtype and the
  13037. byte array
  13038. @param[in] val value to serialize
  13039. @param[in] pretty_print whether the output shall be pretty-printed
  13040. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  13041. in the output are escaped with `\uXXXX` sequences, and the result consists
  13042. of ASCII characters only.
  13043. @param[in] indent_step the indent level
  13044. @param[in] current_indent the current indent level (only used internally)
  13045. */
  13046. void dump(const BasicJsonType& val,
  13047. const bool pretty_print,
  13048. const bool ensure_ascii,
  13049. const unsigned int indent_step,
  13050. const unsigned int current_indent = 0)
  13051. {
  13052. switch (val.m_type)
  13053. {
  13054. case value_t::object:
  13055. {
  13056. if (val.m_value.object->empty())
  13057. {
  13058. o->write_characters("{}", 2);
  13059. return;
  13060. }
  13061. if (pretty_print)
  13062. {
  13063. o->write_characters("{\n", 2);
  13064. // variable to hold indentation for recursive calls
  13065. const auto new_indent = current_indent + indent_step;
  13066. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13067. {
  13068. indent_string.resize(indent_string.size() * 2, ' ');
  13069. }
  13070. // first n-1 elements
  13071. auto i = val.m_value.object->cbegin();
  13072. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  13073. {
  13074. o->write_characters(indent_string.c_str(), new_indent);
  13075. o->write_character('\"');
  13076. dump_escaped(i->first, ensure_ascii);
  13077. o->write_characters("\": ", 3);
  13078. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  13079. o->write_characters(",\n", 2);
  13080. }
  13081. // last element
  13082. assert(i != val.m_value.object->cend());
  13083. assert(std::next(i) == val.m_value.object->cend());
  13084. o->write_characters(indent_string.c_str(), new_indent);
  13085. o->write_character('\"');
  13086. dump_escaped(i->first, ensure_ascii);
  13087. o->write_characters("\": ", 3);
  13088. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  13089. o->write_character('\n');
  13090. o->write_characters(indent_string.c_str(), current_indent);
  13091. o->write_character('}');
  13092. }
  13093. else
  13094. {
  13095. o->write_character('{');
  13096. // first n-1 elements
  13097. auto i = val.m_value.object->cbegin();
  13098. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  13099. {
  13100. o->write_character('\"');
  13101. dump_escaped(i->first, ensure_ascii);
  13102. o->write_characters("\":", 2);
  13103. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  13104. o->write_character(',');
  13105. }
  13106. // last element
  13107. assert(i != val.m_value.object->cend());
  13108. assert(std::next(i) == val.m_value.object->cend());
  13109. o->write_character('\"');
  13110. dump_escaped(i->first, ensure_ascii);
  13111. o->write_characters("\":", 2);
  13112. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  13113. o->write_character('}');
  13114. }
  13115. return;
  13116. }
  13117. case value_t::array:
  13118. {
  13119. if (val.m_value.array->empty())
  13120. {
  13121. o->write_characters("[]", 2);
  13122. return;
  13123. }
  13124. if (pretty_print)
  13125. {
  13126. o->write_characters("[\n", 2);
  13127. // variable to hold indentation for recursive calls
  13128. const auto new_indent = current_indent + indent_step;
  13129. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13130. {
  13131. indent_string.resize(indent_string.size() * 2, ' ');
  13132. }
  13133. // first n-1 elements
  13134. for (auto i = val.m_value.array->cbegin();
  13135. i != val.m_value.array->cend() - 1; ++i)
  13136. {
  13137. o->write_characters(indent_string.c_str(), new_indent);
  13138. dump(*i, true, ensure_ascii, indent_step, new_indent);
  13139. o->write_characters(",\n", 2);
  13140. }
  13141. // last element
  13142. assert(not val.m_value.array->empty());
  13143. o->write_characters(indent_string.c_str(), new_indent);
  13144. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  13145. o->write_character('\n');
  13146. o->write_characters(indent_string.c_str(), current_indent);
  13147. o->write_character(']');
  13148. }
  13149. else
  13150. {
  13151. o->write_character('[');
  13152. // first n-1 elements
  13153. for (auto i = val.m_value.array->cbegin();
  13154. i != val.m_value.array->cend() - 1; ++i)
  13155. {
  13156. dump(*i, false, ensure_ascii, indent_step, current_indent);
  13157. o->write_character(',');
  13158. }
  13159. // last element
  13160. assert(not val.m_value.array->empty());
  13161. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  13162. o->write_character(']');
  13163. }
  13164. return;
  13165. }
  13166. case value_t::string:
  13167. {
  13168. o->write_character('\"');
  13169. dump_escaped(*val.m_value.string, ensure_ascii);
  13170. o->write_character('\"');
  13171. return;
  13172. }
  13173. case value_t::binary:
  13174. {
  13175. if (pretty_print)
  13176. {
  13177. o->write_characters("{\n", 2);
  13178. // variable to hold indentation for recursive calls
  13179. const auto new_indent = current_indent + indent_step;
  13180. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13181. {
  13182. indent_string.resize(indent_string.size() * 2, ' ');
  13183. }
  13184. o->write_characters(indent_string.c_str(), new_indent);
  13185. o->write_characters("\"bytes\": [", 10);
  13186. if (not val.m_value.binary->empty())
  13187. {
  13188. for (auto i = val.m_value.binary->cbegin();
  13189. i != val.m_value.binary->cend() - 1; ++i)
  13190. {
  13191. dump_integer(*i);
  13192. o->write_characters(", ", 2);
  13193. }
  13194. dump_integer(val.m_value.binary->back());
  13195. }
  13196. o->write_characters("],\n", 3);
  13197. o->write_characters(indent_string.c_str(), new_indent);
  13198. o->write_characters("\"subtype\": ", 11);
  13199. if (val.m_value.binary->has_subtype())
  13200. {
  13201. dump_integer(val.m_value.binary->subtype());
  13202. }
  13203. else
  13204. {
  13205. o->write_characters("null", 4);
  13206. }
  13207. o->write_character('\n');
  13208. o->write_characters(indent_string.c_str(), current_indent);
  13209. o->write_character('}');
  13210. }
  13211. else
  13212. {
  13213. o->write_characters("{\"bytes\":[", 10);
  13214. if (not val.m_value.binary->empty())
  13215. {
  13216. for (auto i = val.m_value.binary->cbegin();
  13217. i != val.m_value.binary->cend() - 1; ++i)
  13218. {
  13219. dump_integer(*i);
  13220. o->write_character(',');
  13221. }
  13222. dump_integer(val.m_value.binary->back());
  13223. }
  13224. o->write_characters("],\"subtype\":", 12);
  13225. if (val.m_value.binary->has_subtype())
  13226. {
  13227. dump_integer(val.m_value.binary->subtype());
  13228. o->write_character('}');
  13229. }
  13230. else
  13231. {
  13232. o->write_characters("null}", 5);
  13233. }
  13234. }
  13235. return;
  13236. }
  13237. case value_t::boolean:
  13238. {
  13239. if (val.m_value.boolean)
  13240. {
  13241. o->write_characters("true", 4);
  13242. }
  13243. else
  13244. {
  13245. o->write_characters("false", 5);
  13246. }
  13247. return;
  13248. }
  13249. case value_t::number_integer:
  13250. {
  13251. dump_integer(val.m_value.number_integer);
  13252. return;
  13253. }
  13254. case value_t::number_unsigned:
  13255. {
  13256. dump_integer(val.m_value.number_unsigned);
  13257. return;
  13258. }
  13259. case value_t::number_float:
  13260. {
  13261. dump_float(val.m_value.number_float);
  13262. return;
  13263. }
  13264. case value_t::discarded:
  13265. {
  13266. o->write_characters("<discarded>", 11);
  13267. return;
  13268. }
  13269. case value_t::null:
  13270. {
  13271. o->write_characters("null", 4);
  13272. return;
  13273. }
  13274. default: // LCOV_EXCL_LINE
  13275. assert(false); // LCOV_EXCL_LINE
  13276. }
  13277. }
  13278. private:
  13279. /*!
  13280. @brief dump escaped string
  13281. Escape a string by replacing certain special characters by a sequence of an
  13282. escape character (backslash) and another character and other control
  13283. characters by a sequence of "\u" followed by a four-digit hex
  13284. representation. The escaped string is written to output stream @a o.
  13285. @param[in] s the string to escape
  13286. @param[in] ensure_ascii whether to escape non-ASCII characters with
  13287. \uXXXX sequences
  13288. @complexity Linear in the length of string @a s.
  13289. */
  13290. void dump_escaped(const string_t& s, const bool ensure_ascii)
  13291. {
  13292. std::uint32_t codepoint;
  13293. std::uint8_t state = UTF8_ACCEPT;
  13294. std::size_t bytes = 0; // number of bytes written to string_buffer
  13295. // number of bytes written at the point of the last valid byte
  13296. std::size_t bytes_after_last_accept = 0;
  13297. std::size_t undumped_chars = 0;
  13298. for (std::size_t i = 0; i < s.size(); ++i)
  13299. {
  13300. const auto byte = static_cast<uint8_t>(s[i]);
  13301. switch (decode(state, codepoint, byte))
  13302. {
  13303. case UTF8_ACCEPT: // decode found a new code point
  13304. {
  13305. switch (codepoint)
  13306. {
  13307. case 0x08: // backspace
  13308. {
  13309. string_buffer[bytes++] = '\\';
  13310. string_buffer[bytes++] = 'b';
  13311. break;
  13312. }
  13313. case 0x09: // horizontal tab
  13314. {
  13315. string_buffer[bytes++] = '\\';
  13316. string_buffer[bytes++] = 't';
  13317. break;
  13318. }
  13319. case 0x0A: // newline
  13320. {
  13321. string_buffer[bytes++] = '\\';
  13322. string_buffer[bytes++] = 'n';
  13323. break;
  13324. }
  13325. case 0x0C: // formfeed
  13326. {
  13327. string_buffer[bytes++] = '\\';
  13328. string_buffer[bytes++] = 'f';
  13329. break;
  13330. }
  13331. case 0x0D: // carriage return
  13332. {
  13333. string_buffer[bytes++] = '\\';
  13334. string_buffer[bytes++] = 'r';
  13335. break;
  13336. }
  13337. case 0x22: // quotation mark
  13338. {
  13339. string_buffer[bytes++] = '\\';
  13340. string_buffer[bytes++] = '\"';
  13341. break;
  13342. }
  13343. case 0x5C: // reverse solidus
  13344. {
  13345. string_buffer[bytes++] = '\\';
  13346. string_buffer[bytes++] = '\\';
  13347. break;
  13348. }
  13349. default:
  13350. {
  13351. // escape control characters (0x00..0x1F) or, if
  13352. // ensure_ascii parameter is used, non-ASCII characters
  13353. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  13354. {
  13355. if (codepoint <= 0xFFFF)
  13356. {
  13357. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  13358. static_cast<std::uint16_t>(codepoint));
  13359. bytes += 6;
  13360. }
  13361. else
  13362. {
  13363. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  13364. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  13365. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  13366. bytes += 12;
  13367. }
  13368. }
  13369. else
  13370. {
  13371. // copy byte to buffer (all previous bytes
  13372. // been copied have in default case above)
  13373. string_buffer[bytes++] = s[i];
  13374. }
  13375. break;
  13376. }
  13377. }
  13378. // write buffer and reset index; there must be 13 bytes
  13379. // left, as this is the maximal number of bytes to be
  13380. // written ("\uxxxx\uxxxx\0") for one code point
  13381. if (string_buffer.size() - bytes < 13)
  13382. {
  13383. o->write_characters(string_buffer.data(), bytes);
  13384. bytes = 0;
  13385. }
  13386. // remember the byte position of this accept
  13387. bytes_after_last_accept = bytes;
  13388. undumped_chars = 0;
  13389. break;
  13390. }
  13391. case UTF8_REJECT: // decode found invalid UTF-8 byte
  13392. {
  13393. switch (error_handler)
  13394. {
  13395. case error_handler_t::strict:
  13396. {
  13397. std::string sn(3, '\0');
  13398. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  13399. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  13400. }
  13401. case error_handler_t::ignore:
  13402. case error_handler_t::replace:
  13403. {
  13404. // in case we saw this character the first time, we
  13405. // would like to read it again, because the byte
  13406. // may be OK for itself, but just not OK for the
  13407. // previous sequence
  13408. if (undumped_chars > 0)
  13409. {
  13410. --i;
  13411. }
  13412. // reset length buffer to the last accepted index;
  13413. // thus removing/ignoring the invalid characters
  13414. bytes = bytes_after_last_accept;
  13415. if (error_handler == error_handler_t::replace)
  13416. {
  13417. // add a replacement character
  13418. if (ensure_ascii)
  13419. {
  13420. string_buffer[bytes++] = '\\';
  13421. string_buffer[bytes++] = 'u';
  13422. string_buffer[bytes++] = 'f';
  13423. string_buffer[bytes++] = 'f';
  13424. string_buffer[bytes++] = 'f';
  13425. string_buffer[bytes++] = 'd';
  13426. }
  13427. else
  13428. {
  13429. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  13430. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  13431. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  13432. }
  13433. // write buffer and reset index; there must be 13 bytes
  13434. // left, as this is the maximal number of bytes to be
  13435. // written ("\uxxxx\uxxxx\0") for one code point
  13436. if (string_buffer.size() - bytes < 13)
  13437. {
  13438. o->write_characters(string_buffer.data(), bytes);
  13439. bytes = 0;
  13440. }
  13441. bytes_after_last_accept = bytes;
  13442. }
  13443. undumped_chars = 0;
  13444. // continue processing the string
  13445. state = UTF8_ACCEPT;
  13446. break;
  13447. }
  13448. default: // LCOV_EXCL_LINE
  13449. assert(false); // LCOV_EXCL_LINE
  13450. }
  13451. break;
  13452. }
  13453. default: // decode found yet incomplete multi-byte code point
  13454. {
  13455. if (not ensure_ascii)
  13456. {
  13457. // code point will not be escaped - copy byte to buffer
  13458. string_buffer[bytes++] = s[i];
  13459. }
  13460. ++undumped_chars;
  13461. break;
  13462. }
  13463. }
  13464. }
  13465. // we finished processing the string
  13466. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  13467. {
  13468. // write buffer
  13469. if (bytes > 0)
  13470. {
  13471. o->write_characters(string_buffer.data(), bytes);
  13472. }
  13473. }
  13474. else
  13475. {
  13476. // we finish reading, but do not accept: string was incomplete
  13477. switch (error_handler)
  13478. {
  13479. case error_handler_t::strict:
  13480. {
  13481. std::string sn(3, '\0');
  13482. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  13483. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  13484. }
  13485. case error_handler_t::ignore:
  13486. {
  13487. // write all accepted bytes
  13488. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13489. break;
  13490. }
  13491. case error_handler_t::replace:
  13492. {
  13493. // write all accepted bytes
  13494. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13495. // add a replacement character
  13496. if (ensure_ascii)
  13497. {
  13498. o->write_characters("\\ufffd", 6);
  13499. }
  13500. else
  13501. {
  13502. o->write_characters("\xEF\xBF\xBD", 3);
  13503. }
  13504. break;
  13505. }
  13506. default: // LCOV_EXCL_LINE
  13507. assert(false); // LCOV_EXCL_LINE
  13508. }
  13509. }
  13510. }
  13511. /*!
  13512. @brief count digits
  13513. Count the number of decimal (base 10) digits for an input unsigned integer.
  13514. @param[in] x unsigned integer number to count its digits
  13515. @return number of decimal digits
  13516. */
  13517. inline unsigned int count_digits(number_unsigned_t x) noexcept
  13518. {
  13519. unsigned int n_digits = 1;
  13520. for (;;)
  13521. {
  13522. if (x < 10)
  13523. {
  13524. return n_digits;
  13525. }
  13526. if (x < 100)
  13527. {
  13528. return n_digits + 1;
  13529. }
  13530. if (x < 1000)
  13531. {
  13532. return n_digits + 2;
  13533. }
  13534. if (x < 10000)
  13535. {
  13536. return n_digits + 3;
  13537. }
  13538. x = x / 10000u;
  13539. n_digits += 4;
  13540. }
  13541. }
  13542. /*!
  13543. @brief dump an integer
  13544. Dump a given integer to output stream @a o. Works internally with
  13545. @a number_buffer.
  13546. @param[in] x integer number (signed or unsigned) to dump
  13547. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  13548. */
  13549. template<typename NumberType, detail::enable_if_t<
  13550. std::is_same<NumberType, number_unsigned_t>::value or
  13551. std::is_same<NumberType, number_integer_t>::value or
  13552. std::is_same<NumberType, binary_char_t>::value,
  13553. int> = 0>
  13554. void dump_integer(NumberType x)
  13555. {
  13556. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  13557. {
  13558. {
  13559. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  13560. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  13561. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  13562. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  13563. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  13564. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  13565. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  13566. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  13567. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  13568. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  13569. }
  13570. };
  13571. // special case for "0"
  13572. if (x == 0)
  13573. {
  13574. o->write_character('0');
  13575. return;
  13576. }
  13577. // use a pointer to fill the buffer
  13578. auto buffer_ptr = number_buffer.begin();
  13579. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  13580. number_unsigned_t abs_value;
  13581. unsigned int n_chars;
  13582. if (is_negative)
  13583. {
  13584. *buffer_ptr = '-';
  13585. abs_value = remove_sign(static_cast<number_integer_t>(x));
  13586. // account one more byte for the minus sign
  13587. n_chars = 1 + count_digits(abs_value);
  13588. }
  13589. else
  13590. {
  13591. abs_value = static_cast<number_unsigned_t>(x);
  13592. n_chars = count_digits(abs_value);
  13593. }
  13594. // spare 1 byte for '\0'
  13595. assert(n_chars < number_buffer.size() - 1);
  13596. // jump to the end to generate the string from backward
  13597. // so we later avoid reversing the result
  13598. buffer_ptr += n_chars;
  13599. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  13600. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  13601. while (abs_value >= 100)
  13602. {
  13603. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  13604. abs_value /= 100;
  13605. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13606. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13607. }
  13608. if (abs_value >= 10)
  13609. {
  13610. const auto digits_index = static_cast<unsigned>(abs_value);
  13611. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13612. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13613. }
  13614. else
  13615. {
  13616. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  13617. }
  13618. o->write_characters(number_buffer.data(), n_chars);
  13619. }
  13620. /*!
  13621. @brief dump a floating-point number
  13622. Dump a given floating-point number to output stream @a o. Works internally
  13623. with @a number_buffer.
  13624. @param[in] x floating-point number to dump
  13625. */
  13626. void dump_float(number_float_t x)
  13627. {
  13628. // NaN / inf
  13629. if (not std::isfinite(x))
  13630. {
  13631. o->write_characters("null", 4);
  13632. return;
  13633. }
  13634. // If number_float_t is an IEEE-754 single or double precision number,
  13635. // use the Grisu2 algorithm to produce short numbers which are
  13636. // guaranteed to round-trip, using strtof and strtod, resp.
  13637. //
  13638. // NB: The test below works if <long double> == <double>.
  13639. static constexpr bool is_ieee_single_or_double
  13640. = (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
  13641. (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);
  13642. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  13643. }
  13644. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  13645. {
  13646. char* begin = number_buffer.data();
  13647. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  13648. o->write_characters(begin, static_cast<size_t>(end - begin));
  13649. }
  13650. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  13651. {
  13652. // get number of digits for a float -> text -> float round-trip
  13653. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  13654. // the actual conversion
  13655. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  13656. // negative value indicates an error
  13657. assert(len > 0);
  13658. // check if buffer was large enough
  13659. assert(static_cast<std::size_t>(len) < number_buffer.size());
  13660. // erase thousands separator
  13661. if (thousands_sep != '\0')
  13662. {
  13663. const auto end = std::remove(number_buffer.begin(),
  13664. number_buffer.begin() + len, thousands_sep);
  13665. std::fill(end, number_buffer.end(), '\0');
  13666. assert((end - number_buffer.begin()) <= len);
  13667. len = (end - number_buffer.begin());
  13668. }
  13669. // convert decimal point to '.'
  13670. if (decimal_point != '\0' and decimal_point != '.')
  13671. {
  13672. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  13673. if (dec_pos != number_buffer.end())
  13674. {
  13675. *dec_pos = '.';
  13676. }
  13677. }
  13678. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  13679. // determine if need to append ".0"
  13680. const bool value_is_int_like =
  13681. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  13682. [](char c)
  13683. {
  13684. return c == '.' or c == 'e';
  13685. });
  13686. if (value_is_int_like)
  13687. {
  13688. o->write_characters(".0", 2);
  13689. }
  13690. }
  13691. /*!
  13692. @brief check whether a string is UTF-8 encoded
  13693. The function checks each byte of a string whether it is UTF-8 encoded. The
  13694. result of the check is stored in the @a state parameter. The function must
  13695. be called initially with state 0 (accept). State 1 means the string must
  13696. be rejected, because the current byte is not allowed. If the string is
  13697. completely processed, but the state is non-zero, the string ended
  13698. prematurely; that is, the last byte indicated more bytes should have
  13699. followed.
  13700. @param[in,out] state the state of the decoding
  13701. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  13702. @param[in] byte next byte to decode
  13703. @return new state
  13704. @note The function has been edited: a std::array is used.
  13705. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  13706. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  13707. */
  13708. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  13709. {
  13710. static const std::array<std::uint8_t, 400> utf8d =
  13711. {
  13712. {
  13713. 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
  13714. 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
  13715. 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
  13716. 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
  13717. 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
  13718. 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
  13719. 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
  13720. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  13721. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  13722. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  13723. 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
  13724. 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
  13725. 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
  13726. 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
  13727. }
  13728. };
  13729. const std::uint8_t type = utf8d[byte];
  13730. codep = (state != UTF8_ACCEPT)
  13731. ? (byte & 0x3fu) | (codep << 6u)
  13732. : (0xFFu >> type) & (byte);
  13733. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  13734. assert(index < 400);
  13735. state = utf8d[index];
  13736. return state;
  13737. }
  13738. /*
  13739. * Overload to make the compiler happy while it is instantiating
  13740. * dump_integer for number_unsigned_t.
  13741. * Must never be called.
  13742. */
  13743. number_unsigned_t remove_sign(number_unsigned_t x)
  13744. {
  13745. assert(false); // LCOV_EXCL_LINE
  13746. return x; // LCOV_EXCL_LINE
  13747. }
  13748. /*
  13749. * Helper function for dump_integer
  13750. *
  13751. * This function takes a negative signed integer and returns its absolute
  13752. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  13753. * not directly remove the sign of an arbitrary signed integer as the
  13754. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  13755. * #1708 for details.
  13756. */
  13757. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  13758. {
  13759. assert(x < 0 and x < (std::numeric_limits<number_integer_t>::max)());
  13760. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  13761. }
  13762. private:
  13763. /// the output of the serializer
  13764. output_adapter_t<char> o = nullptr;
  13765. /// a (hopefully) large enough character buffer
  13766. std::array<char, 64> number_buffer{{}};
  13767. /// the locale
  13768. const std::lconv* loc = nullptr;
  13769. /// the locale's thousand separator character
  13770. const char thousands_sep = '\0';
  13771. /// the locale's decimal point character
  13772. const char decimal_point = '\0';
  13773. /// string buffer
  13774. std::array<char, 512> string_buffer{{}};
  13775. /// the indentation character
  13776. const char indent_char;
  13777. /// the indentation string
  13778. string_t indent_string;
  13779. /// error_handler how to react on decoding errors
  13780. const error_handler_t error_handler;
  13781. };
  13782. } // namespace detail
  13783. } // namespace nlohmann
  13784. // #include <nlohmann/detail/value_t.hpp>
  13785. // #include <nlohmann/json_fwd.hpp>
  13786. /*!
  13787. @brief namespace for Niels Lohmann
  13788. @see https://github.com/nlohmann
  13789. @since version 1.0.0
  13790. */
  13791. namespace nlohmann
  13792. {
  13793. /*!
  13794. @brief a class to store JSON values
  13795. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  13796. in @ref object_t)
  13797. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  13798. in @ref array_t)
  13799. @tparam StringType type for JSON strings and object keys (`std::string` by
  13800. default; will be used in @ref string_t)
  13801. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  13802. in @ref boolean_t)
  13803. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  13804. default; will be used in @ref number_integer_t)
  13805. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  13806. `uint64_t` by default; will be used in @ref number_unsigned_t)
  13807. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  13808. default; will be used in @ref number_float_t)
  13809. @tparam BinaryType type for packed binary data for compatibility with binary
  13810. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  13811. @ref binary_t)
  13812. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  13813. default)
  13814. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  13815. and `from_json()` (@ref adl_serializer by default)
  13816. @requirement The class satisfies the following concept requirements:
  13817. - Basic
  13818. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  13819. JSON values can be default constructed. The result will be a JSON null
  13820. value.
  13821. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  13822. A JSON value can be constructed from an rvalue argument.
  13823. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  13824. A JSON value can be copy-constructed from an lvalue expression.
  13825. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  13826. A JSON value van be assigned from an rvalue argument.
  13827. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  13828. A JSON value can be copy-assigned from an lvalue expression.
  13829. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  13830. JSON values can be destructed.
  13831. - Layout
  13832. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  13833. JSON values have
  13834. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  13835. All non-static data members are private and standard layout types, the
  13836. class has no virtual functions or (virtual) base classes.
  13837. - Library-wide
  13838. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  13839. JSON values can be compared with `==`, see @ref
  13840. operator==(const_reference,const_reference).
  13841. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  13842. JSON values can be compared with `<`, see @ref
  13843. operator<(const_reference,const_reference).
  13844. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  13845. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  13846. other compatible types, using unqualified function call @ref swap().
  13847. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  13848. JSON values can be compared against `std::nullptr_t` objects which are used
  13849. to model the `null` value.
  13850. - Container
  13851. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  13852. JSON values can be used like STL containers and provide iterator access.
  13853. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  13854. JSON values can be used like STL containers and provide reverse iterator
  13855. access.
  13856. @invariant The member variables @a m_value and @a m_type have the following
  13857. relationship:
  13858. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  13859. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  13860. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  13861. The invariants are checked by member function assert_invariant().
  13862. @internal
  13863. @note ObjectType trick from https://stackoverflow.com/a/9860911
  13864. @endinternal
  13865. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  13866. Format](http://rfc7159.net/rfc7159)
  13867. @since version 1.0.0
  13868. @nosubgrouping
  13869. */
  13870. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  13871. class basic_json
  13872. {
  13873. private:
  13874. template<detail::value_t> friend struct detail::external_constructor;
  13875. friend ::nlohmann::json_pointer<basic_json>;
  13876. template<typename BasicJsonType, typename InputType>
  13877. friend class ::nlohmann::detail::parser;
  13878. friend ::nlohmann::detail::serializer<basic_json>;
  13879. template<typename BasicJsonType>
  13880. friend class ::nlohmann::detail::iter_impl;
  13881. template<typename BasicJsonType, typename CharType>
  13882. friend class ::nlohmann::detail::binary_writer;
  13883. template<typename BasicJsonType, typename InputType, typename SAX>
  13884. friend class ::nlohmann::detail::binary_reader;
  13885. template<typename BasicJsonType>
  13886. friend class ::nlohmann::detail::json_sax_dom_parser;
  13887. template<typename BasicJsonType>
  13888. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  13889. /// workaround type for MSVC
  13890. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  13891. // convenience aliases for types residing in namespace detail;
  13892. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  13893. template<typename InputAdapterType>
  13894. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  13895. InputAdapterType adapter,
  13896. detail::parser_callback_t<basic_json>cb = nullptr,
  13897. bool allow_exceptions = true
  13898. )
  13899. {
  13900. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter), std::move(cb), allow_exceptions);
  13901. }
  13902. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  13903. template<typename BasicJsonType>
  13904. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  13905. template<typename BasicJsonType>
  13906. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  13907. template<typename Iterator>
  13908. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  13909. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  13910. template<typename CharType>
  13911. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  13912. template<typename InputType>
  13913. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  13914. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  13915. using serializer = ::nlohmann::detail::serializer<basic_json>;
  13916. public:
  13917. using value_t = detail::value_t;
  13918. /// JSON Pointer, see @ref nlohmann::json_pointer
  13919. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  13920. template<typename T, typename SFINAE>
  13921. using json_serializer = JSONSerializer<T, SFINAE>;
  13922. /// how to treat decoding errors
  13923. using error_handler_t = detail::error_handler_t;
  13924. /// helper type for initializer lists of basic_json values
  13925. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  13926. using input_format_t = detail::input_format_t;
  13927. /// SAX interface type, see @ref nlohmann::json_sax
  13928. using json_sax_t = json_sax<basic_json>;
  13929. ////////////////
  13930. // exceptions //
  13931. ////////////////
  13932. /// @name exceptions
  13933. /// Classes to implement user-defined exceptions.
  13934. /// @{
  13935. /// @copydoc detail::exception
  13936. using exception = detail::exception;
  13937. /// @copydoc detail::parse_error
  13938. using parse_error = detail::parse_error;
  13939. /// @copydoc detail::invalid_iterator
  13940. using invalid_iterator = detail::invalid_iterator;
  13941. /// @copydoc detail::type_error
  13942. using type_error = detail::type_error;
  13943. /// @copydoc detail::out_of_range
  13944. using out_of_range = detail::out_of_range;
  13945. /// @copydoc detail::other_error
  13946. using other_error = detail::other_error;
  13947. /// @}
  13948. /////////////////////
  13949. // container types //
  13950. /////////////////////
  13951. /// @name container types
  13952. /// The canonic container types to use @ref basic_json like any other STL
  13953. /// container.
  13954. /// @{
  13955. /// the type of elements in a basic_json container
  13956. using value_type = basic_json;
  13957. /// the type of an element reference
  13958. using reference = value_type&;
  13959. /// the type of an element const reference
  13960. using const_reference = const value_type&;
  13961. /// a type to represent differences between iterators
  13962. using difference_type = std::ptrdiff_t;
  13963. /// a type to represent container sizes
  13964. using size_type = std::size_t;
  13965. /// the allocator type
  13966. using allocator_type = AllocatorType<basic_json>;
  13967. /// the type of an element pointer
  13968. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  13969. /// the type of an element const pointer
  13970. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  13971. /// an iterator for a basic_json container
  13972. using iterator = iter_impl<basic_json>;
  13973. /// a const iterator for a basic_json container
  13974. using const_iterator = iter_impl<const basic_json>;
  13975. /// a reverse iterator for a basic_json container
  13976. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  13977. /// a const reverse iterator for a basic_json container
  13978. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  13979. /// @}
  13980. /*!
  13981. @brief returns the allocator associated with the container
  13982. */
  13983. static allocator_type get_allocator()
  13984. {
  13985. return allocator_type();
  13986. }
  13987. /*!
  13988. @brief returns version information on the library
  13989. This function returns a JSON object with information about the library,
  13990. including the version number and information on the platform and compiler.
  13991. @return JSON object holding version information
  13992. key | description
  13993. ----------- | ---------------
  13994. `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).
  13995. `copyright` | The copyright line for the library as string.
  13996. `name` | The name of the library as string.
  13997. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  13998. `url` | The URL of the project as string.
  13999. `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).
  14000. @liveexample{The following code shows an example output of the `meta()`
  14001. function.,meta}
  14002. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14003. changes to any JSON value.
  14004. @complexity Constant.
  14005. @since 2.1.0
  14006. */
  14007. JSON_HEDLEY_WARN_UNUSED_RESULT
  14008. static basic_json meta()
  14009. {
  14010. basic_json result;
  14011. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  14012. result["name"] = "JSON for Modern C++";
  14013. result["url"] = "https://github.com/nlohmann/json";
  14014. result["version"]["string"] =
  14015. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  14016. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  14017. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  14018. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  14019. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  14020. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  14021. #ifdef _WIN32
  14022. result["platform"] = "win32";
  14023. #elif defined __linux__
  14024. result["platform"] = "linux";
  14025. #elif defined __APPLE__
  14026. result["platform"] = "apple";
  14027. #elif defined __unix__
  14028. result["platform"] = "unix";
  14029. #else
  14030. result["platform"] = "unknown";
  14031. #endif
  14032. #if defined(__ICC) || defined(__INTEL_COMPILER)
  14033. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  14034. #elif defined(__clang__)
  14035. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  14036. #elif defined(__GNUC__) || defined(__GNUG__)
  14037. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  14038. #elif defined(__HP_cc) || defined(__HP_aCC)
  14039. result["compiler"] = "hp"
  14040. #elif defined(__IBMCPP__)
  14041. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  14042. #elif defined(_MSC_VER)
  14043. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  14044. #elif defined(__PGI)
  14045. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  14046. #elif defined(__SUNPRO_CC)
  14047. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  14048. #else
  14049. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  14050. #endif
  14051. #ifdef __cplusplus
  14052. result["compiler"]["c++"] = std::to_string(__cplusplus);
  14053. #else
  14054. result["compiler"]["c++"] = "unknown";
  14055. #endif
  14056. return result;
  14057. }
  14058. ///////////////////////////
  14059. // JSON value data types //
  14060. ///////////////////////////
  14061. /// @name JSON value data types
  14062. /// The data types to store a JSON value. These types are derived from
  14063. /// the template arguments passed to class @ref basic_json.
  14064. /// @{
  14065. #if defined(JSON_HAS_CPP_14)
  14066. // Use transparent comparator if possible, combined with perfect forwarding
  14067. // on find() and count() calls prevents unnecessary string construction.
  14068. using object_comparator_t = std::less<>;
  14069. #else
  14070. using object_comparator_t = std::less<StringType>;
  14071. #endif
  14072. /*!
  14073. @brief a type for an object
  14074. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  14075. > An object is an unordered collection of zero or more name/value pairs,
  14076. > where a name is a string and a value is a string, number, boolean, null,
  14077. > object, or array.
  14078. To store objects in C++, a type is defined by the template parameters
  14079. described below.
  14080. @tparam ObjectType the container to store objects (e.g., `std::map` or
  14081. `std::unordered_map`)
  14082. @tparam StringType the type of the keys or names (e.g., `std::string`).
  14083. The comparison function `std::less<StringType>` is used to order elements
  14084. inside the container.
  14085. @tparam AllocatorType the allocator to use for objects (e.g.,
  14086. `std::allocator`)
  14087. #### Default type
  14088. With the default values for @a ObjectType (`std::map`), @a StringType
  14089. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  14090. value for @a object_t is:
  14091. @code {.cpp}
  14092. std::map<
  14093. std::string, // key_type
  14094. basic_json, // value_type
  14095. std::less<std::string>, // key_compare
  14096. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  14097. >
  14098. @endcode
  14099. #### Behavior
  14100. The choice of @a object_t influences the behavior of the JSON class. With
  14101. the default type, objects have the following behavior:
  14102. - When all names are unique, objects will be interoperable in the sense
  14103. that all software implementations receiving that object will agree on
  14104. the name-value mappings.
  14105. - When the names within an object are not unique, it is unspecified which
  14106. one of the values for a given key will be chosen. For instance,
  14107. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  14108. `{"key": 2}`.
  14109. - Internally, name/value pairs are stored in lexicographical order of the
  14110. names. Objects will also be serialized (see @ref dump) in this order.
  14111. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  14112. and serialized as `{"a": 2, "b": 1}`.
  14113. - When comparing objects, the order of the name/value pairs is irrelevant.
  14114. This makes objects interoperable in the sense that they will not be
  14115. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  14116. `{"a": 2, "b": 1}` will be treated as equal.
  14117. #### Limits
  14118. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14119. > An implementation may set limits on the maximum depth of nesting.
  14120. In this class, the object's limit of nesting is not explicitly constrained.
  14121. However, a maximum depth of nesting may be introduced by the compiler or
  14122. runtime environment. A theoretical limit can be queried by calling the
  14123. @ref max_size function of a JSON object.
  14124. #### Storage
  14125. Objects are stored as pointers in a @ref basic_json type. That is, for any
  14126. access to object values, a pointer of type `object_t*` must be
  14127. dereferenced.
  14128. @sa @ref array_t -- type for an array value
  14129. @since version 1.0.0
  14130. @note The order name/value pairs are added to the object is *not*
  14131. preserved by the library. Therefore, iterating an object may return
  14132. name/value pairs in a different order than they were originally stored. In
  14133. fact, keys will be traversed in alphabetical order as `std::map` with
  14134. `std::less` is used by default. Please note this behavior conforms to [RFC
  14135. 7159](http://rfc7159.net/rfc7159), because any order implements the
  14136. specified "unordered" nature of JSON objects.
  14137. */
  14138. using object_t = ObjectType<StringType,
  14139. basic_json,
  14140. object_comparator_t,
  14141. AllocatorType<std::pair<const StringType,
  14142. basic_json>>>;
  14143. /*!
  14144. @brief a type for an array
  14145. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  14146. > An array is an ordered sequence of zero or more values.
  14147. To store objects in C++, a type is defined by the template parameters
  14148. explained below.
  14149. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  14150. `std::list`)
  14151. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  14152. #### Default type
  14153. With the default values for @a ArrayType (`std::vector`) and @a
  14154. AllocatorType (`std::allocator`), the default value for @a array_t is:
  14155. @code {.cpp}
  14156. std::vector<
  14157. basic_json, // value_type
  14158. std::allocator<basic_json> // allocator_type
  14159. >
  14160. @endcode
  14161. #### Limits
  14162. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14163. > An implementation may set limits on the maximum depth of nesting.
  14164. In this class, the array's limit of nesting is not explicitly constrained.
  14165. However, a maximum depth of nesting may be introduced by the compiler or
  14166. runtime environment. A theoretical limit can be queried by calling the
  14167. @ref max_size function of a JSON array.
  14168. #### Storage
  14169. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  14170. access to array values, a pointer of type `array_t*` must be dereferenced.
  14171. @sa @ref object_t -- type for an object value
  14172. @since version 1.0.0
  14173. */
  14174. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  14175. /*!
  14176. @brief a type for a string
  14177. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  14178. > A string is a sequence of zero or more Unicode characters.
  14179. To store objects in C++, a type is defined by the template parameter
  14180. described below. Unicode values are split by the JSON class into
  14181. byte-sized characters during deserialization.
  14182. @tparam StringType the container to store strings (e.g., `std::string`).
  14183. Note this container is used for keys/names in objects, see @ref object_t.
  14184. #### Default type
  14185. With the default values for @a StringType (`std::string`), the default
  14186. value for @a string_t is:
  14187. @code {.cpp}
  14188. std::string
  14189. @endcode
  14190. #### Encoding
  14191. Strings are stored in UTF-8 encoding. Therefore, functions like
  14192. `std::string::size()` or `std::string::length()` return the number of
  14193. bytes in the string rather than the number of characters or glyphs.
  14194. #### String comparison
  14195. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14196. > Software implementations are typically required to test names of object
  14197. > members for equality. Implementations that transform the textual
  14198. > representation into sequences of Unicode code units and then perform the
  14199. > comparison numerically, code unit by code unit, are interoperable in the
  14200. > sense that implementations will agree in all cases on equality or
  14201. > inequality of two strings. For example, implementations that compare
  14202. > strings with escaped characters unconverted may incorrectly find that
  14203. > `"a\\b"` and `"a\u005Cb"` are not equal.
  14204. This implementation is interoperable as it does compare strings code unit
  14205. by code unit.
  14206. #### Storage
  14207. String values are stored as pointers in a @ref basic_json type. That is,
  14208. for any access to string values, a pointer of type `string_t*` must be
  14209. dereferenced.
  14210. @since version 1.0.0
  14211. */
  14212. using string_t = StringType;
  14213. /*!
  14214. @brief a type for a boolean
  14215. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  14216. type which differentiates the two literals `true` and `false`.
  14217. To store objects in C++, a type is defined by the template parameter @a
  14218. BooleanType which chooses the type to use.
  14219. #### Default type
  14220. With the default values for @a BooleanType (`bool`), the default value for
  14221. @a boolean_t is:
  14222. @code {.cpp}
  14223. bool
  14224. @endcode
  14225. #### Storage
  14226. Boolean values are stored directly inside a @ref basic_json type.
  14227. @since version 1.0.0
  14228. */
  14229. using boolean_t = BooleanType;
  14230. /*!
  14231. @brief a type for a number (integer)
  14232. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14233. > The representation of numbers is similar to that used in most
  14234. > programming languages. A number is represented in base 10 using decimal
  14235. > digits. It contains an integer component that may be prefixed with an
  14236. > optional minus sign, which may be followed by a fraction part and/or an
  14237. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14238. > cannot be represented in the grammar below (such as Infinity and NaN)
  14239. > are not permitted.
  14240. This description includes both integer and floating-point numbers.
  14241. However, C++ allows more precise storage if it is known whether the number
  14242. is a signed integer, an unsigned integer or a floating-point number.
  14243. Therefore, three different types, @ref number_integer_t, @ref
  14244. number_unsigned_t and @ref number_float_t are used.
  14245. To store integer numbers in C++, a type is defined by the template
  14246. parameter @a NumberIntegerType which chooses the type to use.
  14247. #### Default type
  14248. With the default values for @a NumberIntegerType (`int64_t`), the default
  14249. value for @a number_integer_t is:
  14250. @code {.cpp}
  14251. int64_t
  14252. @endcode
  14253. #### Default behavior
  14254. - The restrictions about leading zeros is not enforced in C++. Instead,
  14255. leading zeros in integer literals lead to an interpretation as octal
  14256. number. Internally, the value will be stored as decimal number. For
  14257. instance, the C++ integer literal `010` will be serialized to `8`.
  14258. During deserialization, leading zeros yield an error.
  14259. - Not-a-number (NaN) values will be serialized to `null`.
  14260. #### Limits
  14261. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14262. > An implementation may set limits on the range and precision of numbers.
  14263. When the default type is used, the maximal integer number that can be
  14264. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  14265. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  14266. that are out of range will yield over/underflow when used in a
  14267. constructor. During deserialization, too large or small integer numbers
  14268. will be automatically be stored as @ref number_unsigned_t or @ref
  14269. number_float_t.
  14270. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14271. > Note that when such software is used, numbers that are integers and are
  14272. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14273. > that implementations will agree exactly on their numeric values.
  14274. As this range is a subrange of the exactly supported range [INT64_MIN,
  14275. INT64_MAX], this class's integer type is interoperable.
  14276. #### Storage
  14277. Integer number values are stored directly inside a @ref basic_json type.
  14278. @sa @ref number_float_t -- type for number values (floating-point)
  14279. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14280. @since version 1.0.0
  14281. */
  14282. using number_integer_t = NumberIntegerType;
  14283. /*!
  14284. @brief a type for a number (unsigned)
  14285. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14286. > The representation of numbers is similar to that used in most
  14287. > programming languages. A number is represented in base 10 using decimal
  14288. > digits. It contains an integer component that may be prefixed with an
  14289. > optional minus sign, which may be followed by a fraction part and/or an
  14290. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14291. > cannot be represented in the grammar below (such as Infinity and NaN)
  14292. > are not permitted.
  14293. This description includes both integer and floating-point numbers.
  14294. However, C++ allows more precise storage if it is known whether the number
  14295. is a signed integer, an unsigned integer or a floating-point number.
  14296. Therefore, three different types, @ref number_integer_t, @ref
  14297. number_unsigned_t and @ref number_float_t are used.
  14298. To store unsigned integer numbers in C++, a type is defined by the
  14299. template parameter @a NumberUnsignedType which chooses the type to use.
  14300. #### Default type
  14301. With the default values for @a NumberUnsignedType (`uint64_t`), the
  14302. default value for @a number_unsigned_t is:
  14303. @code {.cpp}
  14304. uint64_t
  14305. @endcode
  14306. #### Default behavior
  14307. - The restrictions about leading zeros is not enforced in C++. Instead,
  14308. leading zeros in integer literals lead to an interpretation as octal
  14309. number. Internally, the value will be stored as decimal number. For
  14310. instance, the C++ integer literal `010` will be serialized to `8`.
  14311. During deserialization, leading zeros yield an error.
  14312. - Not-a-number (NaN) values will be serialized to `null`.
  14313. #### Limits
  14314. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14315. > An implementation may set limits on the range and precision of numbers.
  14316. When the default type is used, the maximal integer number that can be
  14317. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  14318. number that can be stored is `0`. Integer numbers that are out of range
  14319. will yield over/underflow when used in a constructor. During
  14320. deserialization, too large or small integer numbers will be automatically
  14321. be stored as @ref number_integer_t or @ref number_float_t.
  14322. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14323. > Note that when such software is used, numbers that are integers and are
  14324. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14325. > that implementations will agree exactly on their numeric values.
  14326. As this range is a subrange (when considered in conjunction with the
  14327. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  14328. this class's integer type is interoperable.
  14329. #### Storage
  14330. Integer number values are stored directly inside a @ref basic_json type.
  14331. @sa @ref number_float_t -- type for number values (floating-point)
  14332. @sa @ref number_integer_t -- type for number values (integer)
  14333. @since version 2.0.0
  14334. */
  14335. using number_unsigned_t = NumberUnsignedType;
  14336. /*!
  14337. @brief a type for a number (floating-point)
  14338. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14339. > The representation of numbers is similar to that used in most
  14340. > programming languages. A number is represented in base 10 using decimal
  14341. > digits. It contains an integer component that may be prefixed with an
  14342. > optional minus sign, which may be followed by a fraction part and/or an
  14343. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14344. > cannot be represented in the grammar below (such as Infinity and NaN)
  14345. > are not permitted.
  14346. This description includes both integer and floating-point numbers.
  14347. However, C++ allows more precise storage if it is known whether the number
  14348. is a signed integer, an unsigned integer or a floating-point number.
  14349. Therefore, three different types, @ref number_integer_t, @ref
  14350. number_unsigned_t and @ref number_float_t are used.
  14351. To store floating-point numbers in C++, a type is defined by the template
  14352. parameter @a NumberFloatType which chooses the type to use.
  14353. #### Default type
  14354. With the default values for @a NumberFloatType (`double`), the default
  14355. value for @a number_float_t is:
  14356. @code {.cpp}
  14357. double
  14358. @endcode
  14359. #### Default behavior
  14360. - The restrictions about leading zeros is not enforced in C++. Instead,
  14361. leading zeros in floating-point literals will be ignored. Internally,
  14362. the value will be stored as decimal number. For instance, the C++
  14363. floating-point literal `01.2` will be serialized to `1.2`. During
  14364. deserialization, leading zeros yield an error.
  14365. - Not-a-number (NaN) values will be serialized to `null`.
  14366. #### Limits
  14367. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14368. > This specification allows implementations to set limits on the range and
  14369. > precision of numbers accepted. Since software that implements IEEE
  14370. > 754-2008 binary64 (double precision) numbers is generally available and
  14371. > widely used, good interoperability can be achieved by implementations
  14372. > that expect no more precision or range than these provide, in the sense
  14373. > that implementations will approximate JSON numbers within the expected
  14374. > precision.
  14375. This implementation does exactly follow this approach, as it uses double
  14376. precision floating-point numbers. Note values smaller than
  14377. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  14378. will be stored as NaN internally and be serialized to `null`.
  14379. #### Storage
  14380. Floating-point number values are stored directly inside a @ref basic_json
  14381. type.
  14382. @sa @ref number_integer_t -- type for number values (integer)
  14383. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14384. @since version 1.0.0
  14385. */
  14386. using number_float_t = NumberFloatType;
  14387. /*!
  14388. @brief a type for a packed binary type
  14389. This type is a type designed to carry binary data that appears in various
  14390. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  14391. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  14392. exists solely for compatibility with these binary types. As such, it is
  14393. simply defined as an ordered sequence of zero or more byte values.
  14394. Additionally, as an implementation detail, the subtype of the binary data is
  14395. carried around as a `std::uint8_t`, which is compatible with both of the
  14396. binary data formats that use binary subtyping, (though the specific
  14397. numbering is incompatible with each other, and it is up to the user to
  14398. translate between them).
  14399. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  14400. as:
  14401. > Major type 2: a byte string. The string's length in bytes is represented
  14402. > following the rules for positive integers (major type 0).
  14403. [MessagePack's documentation on the bin type
  14404. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  14405. describes this type as:
  14406. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  14407. > in addition to the size of the byte array.
  14408. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  14409. binary types; however, this type is intended to represent the generic binary
  14410. type which has the description:
  14411. > Generic binary subtype - This is the most commonly used binary subtype and
  14412. > should be the 'default' for drivers and tools.
  14413. None of these impose any limitations on the internal representation other
  14414. than the basic unit of storage be some type of array whose parts are
  14415. decomposable into bytes.
  14416. The default representation of this binary format is a
  14417. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  14418. array in modern C++.
  14419. #### Default type
  14420. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  14421. #### Storage
  14422. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  14423. for any access to array values, a pointer of the type `binary_t*` must be
  14424. dereferenced.
  14425. #### Notes on subtypes
  14426. - CBOR
  14427. - Binary values are represented as byte strings. No subtypes are
  14428. supported and will be ignored when CBOR is written.
  14429. - MessagePack
  14430. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  14431. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  14432. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  14433. The subtype is then added as singed 8-bit integer.
  14434. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  14435. - BSON
  14436. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  14437. - If no subtype is given, the generic binary subtype 0x00 is used.
  14438. @sa @ref binary -- create a binary array
  14439. @since version 3.8.0
  14440. */
  14441. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  14442. /// @}
  14443. private:
  14444. /// helper for exception-safe object creation
  14445. template<typename T, typename... Args>
  14446. JSON_HEDLEY_RETURNS_NON_NULL
  14447. static T* create(Args&& ... args)
  14448. {
  14449. AllocatorType<T> alloc;
  14450. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  14451. auto deleter = [&](T * object)
  14452. {
  14453. AllocatorTraits::deallocate(alloc, object, 1);
  14454. };
  14455. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  14456. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  14457. assert(object != nullptr);
  14458. return object.release();
  14459. }
  14460. ////////////////////////
  14461. // JSON value storage //
  14462. ////////////////////////
  14463. /*!
  14464. @brief a JSON value
  14465. The actual storage for a JSON value of the @ref basic_json class. This
  14466. union combines the different storage types for the JSON value types
  14467. defined in @ref value_t.
  14468. JSON type | value_t type | used type
  14469. --------- | --------------- | ------------------------
  14470. object | object | pointer to @ref object_t
  14471. array | array | pointer to @ref array_t
  14472. string | string | pointer to @ref string_t
  14473. boolean | boolean | @ref boolean_t
  14474. number | number_integer | @ref number_integer_t
  14475. number | number_unsigned | @ref number_unsigned_t
  14476. number | number_float | @ref number_float_t
  14477. binary | binary | pointer to @ref binary_t
  14478. null | null | *no value is stored*
  14479. @note Variable-length types (objects, arrays, and strings) are stored as
  14480. pointers. The size of the union should not exceed 64 bits if the default
  14481. value types are used.
  14482. @since version 1.0.0
  14483. */
  14484. union json_value
  14485. {
  14486. /// object (stored with pointer to save storage)
  14487. object_t* object;
  14488. /// array (stored with pointer to save storage)
  14489. array_t* array;
  14490. /// string (stored with pointer to save storage)
  14491. string_t* string;
  14492. /// binary (stored with pointer to save storage)
  14493. binary_t* binary;
  14494. /// boolean
  14495. boolean_t boolean;
  14496. /// number (integer)
  14497. number_integer_t number_integer;
  14498. /// number (unsigned integer)
  14499. number_unsigned_t number_unsigned;
  14500. /// number (floating-point)
  14501. number_float_t number_float;
  14502. /// default constructor (for null values)
  14503. json_value() = default;
  14504. /// constructor for booleans
  14505. json_value(boolean_t v) noexcept : boolean(v) {}
  14506. /// constructor for numbers (integer)
  14507. json_value(number_integer_t v) noexcept : number_integer(v) {}
  14508. /// constructor for numbers (unsigned)
  14509. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  14510. /// constructor for numbers (floating-point)
  14511. json_value(number_float_t v) noexcept : number_float(v) {}
  14512. /// constructor for empty values of a given type
  14513. json_value(value_t t)
  14514. {
  14515. switch (t)
  14516. {
  14517. case value_t::object:
  14518. {
  14519. object = create<object_t>();
  14520. break;
  14521. }
  14522. case value_t::array:
  14523. {
  14524. array = create<array_t>();
  14525. break;
  14526. }
  14527. case value_t::string:
  14528. {
  14529. string = create<string_t>("");
  14530. break;
  14531. }
  14532. case value_t::binary:
  14533. {
  14534. binary = create<binary_t>();
  14535. break;
  14536. }
  14537. case value_t::boolean:
  14538. {
  14539. boolean = boolean_t(false);
  14540. break;
  14541. }
  14542. case value_t::number_integer:
  14543. {
  14544. number_integer = number_integer_t(0);
  14545. break;
  14546. }
  14547. case value_t::number_unsigned:
  14548. {
  14549. number_unsigned = number_unsigned_t(0);
  14550. break;
  14551. }
  14552. case value_t::number_float:
  14553. {
  14554. number_float = number_float_t(0.0);
  14555. break;
  14556. }
  14557. case value_t::null:
  14558. {
  14559. object = nullptr; // silence warning, see #821
  14560. break;
  14561. }
  14562. default:
  14563. {
  14564. object = nullptr; // silence warning, see #821
  14565. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  14566. {
  14567. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.3")); // LCOV_EXCL_LINE
  14568. }
  14569. break;
  14570. }
  14571. }
  14572. }
  14573. /// constructor for strings
  14574. json_value(const string_t& value)
  14575. {
  14576. string = create<string_t>(value);
  14577. }
  14578. /// constructor for rvalue strings
  14579. json_value(string_t&& value)
  14580. {
  14581. string = create<string_t>(std::move(value));
  14582. }
  14583. /// constructor for objects
  14584. json_value(const object_t& value)
  14585. {
  14586. object = create<object_t>(value);
  14587. }
  14588. /// constructor for rvalue objects
  14589. json_value(object_t&& value)
  14590. {
  14591. object = create<object_t>(std::move(value));
  14592. }
  14593. /// constructor for arrays
  14594. json_value(const array_t& value)
  14595. {
  14596. array = create<array_t>(value);
  14597. }
  14598. /// constructor for rvalue arrays
  14599. json_value(array_t&& value)
  14600. {
  14601. array = create<array_t>(std::move(value));
  14602. }
  14603. /// constructor for binary arrays
  14604. json_value(const typename binary_t::container_type& value)
  14605. {
  14606. binary = create<binary_t>(value);
  14607. }
  14608. /// constructor for rvalue binary arrays
  14609. json_value(typename binary_t::container_type&& value)
  14610. {
  14611. binary = create<binary_t>(std::move(value));
  14612. }
  14613. /// constructor for binary arrays (internal type)
  14614. json_value(const binary_t& value)
  14615. {
  14616. binary = create<binary_t>(value);
  14617. }
  14618. /// constructor for rvalue binary arrays (internal type)
  14619. json_value(binary_t&& value)
  14620. {
  14621. binary = create<binary_t>(std::move(value));
  14622. }
  14623. void destroy(value_t t) noexcept
  14624. {
  14625. // flatten the current json_value to a heap-allocated stack
  14626. std::vector<basic_json> stack;
  14627. // move the top-level items to stack
  14628. if (t == value_t::array)
  14629. {
  14630. stack.reserve(array->size());
  14631. std::move(array->begin(), array->end(), std::back_inserter(stack));
  14632. }
  14633. else if (t == value_t::object)
  14634. {
  14635. stack.reserve(object->size());
  14636. for (auto&& it : *object)
  14637. {
  14638. stack.push_back(std::move(it.second));
  14639. }
  14640. }
  14641. while (not stack.empty())
  14642. {
  14643. // move the last item to local variable to be processed
  14644. basic_json current_item(std::move(stack.back()));
  14645. stack.pop_back();
  14646. // if current_item is array/object, move
  14647. // its children to the stack to be processed later
  14648. if (current_item.is_array())
  14649. {
  14650. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
  14651. std::back_inserter(stack));
  14652. current_item.m_value.array->clear();
  14653. }
  14654. else if (current_item.is_object())
  14655. {
  14656. for (auto&& it : *current_item.m_value.object)
  14657. {
  14658. stack.push_back(std::move(it.second));
  14659. }
  14660. current_item.m_value.object->clear();
  14661. }
  14662. // it's now safe that current_item get destructed
  14663. // since it doesn't have any children
  14664. }
  14665. switch (t)
  14666. {
  14667. case value_t::object:
  14668. {
  14669. AllocatorType<object_t> alloc;
  14670. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  14671. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  14672. break;
  14673. }
  14674. case value_t::array:
  14675. {
  14676. AllocatorType<array_t> alloc;
  14677. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  14678. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  14679. break;
  14680. }
  14681. case value_t::string:
  14682. {
  14683. AllocatorType<string_t> alloc;
  14684. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  14685. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  14686. break;
  14687. }
  14688. case value_t::binary:
  14689. {
  14690. AllocatorType<binary_t> alloc;
  14691. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  14692. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  14693. break;
  14694. }
  14695. default:
  14696. {
  14697. break;
  14698. }
  14699. }
  14700. }
  14701. };
  14702. /*!
  14703. @brief checks the class invariants
  14704. This function asserts the class invariants. It needs to be called at the
  14705. end of every constructor to make sure that created objects respect the
  14706. invariant. Furthermore, it has to be called each time the type of a JSON
  14707. value is changed, because the invariant expresses a relationship between
  14708. @a m_type and @a m_value.
  14709. */
  14710. void assert_invariant() const noexcept
  14711. {
  14712. assert(m_type != value_t::object or m_value.object != nullptr);
  14713. assert(m_type != value_t::array or m_value.array != nullptr);
  14714. assert(m_type != value_t::string or m_value.string != nullptr);
  14715. assert(m_type != value_t::binary or m_value.binary != nullptr);
  14716. }
  14717. public:
  14718. //////////////////////////
  14719. // JSON parser callback //
  14720. //////////////////////////
  14721. /*!
  14722. @brief parser event types
  14723. The parser callback distinguishes the following events:
  14724. - `object_start`: the parser read `{` and started to process a JSON object
  14725. - `key`: the parser read a key of a value in an object
  14726. - `object_end`: the parser read `}` and finished processing a JSON object
  14727. - `array_start`: the parser read `[` and started to process a JSON array
  14728. - `array_end`: the parser read `]` and finished processing a JSON array
  14729. - `value`: the parser finished reading a JSON value
  14730. @image html callback_events.png "Example when certain parse events are triggered"
  14731. @sa @ref parser_callback_t for more information and examples
  14732. */
  14733. using parse_event_t = detail::parse_event_t;
  14734. /*!
  14735. @brief per-element parser callback type
  14736. With a parser callback function, the result of parsing a JSON text can be
  14737. influenced. When passed to @ref parse, it is called on certain events
  14738. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  14739. depth @a depth and context JSON value @a parsed. The return value of the
  14740. callback function is a boolean indicating whether the element that emitted
  14741. the callback shall be kept or not.
  14742. We distinguish six scenarios (determined by the event type) in which the
  14743. callback function can be called. The following table describes the values
  14744. of the parameters @a depth, @a event, and @a parsed.
  14745. parameter @a event | description | parameter @a depth | parameter @a parsed
  14746. ------------------ | ----------- | ------------------ | -------------------
  14747. 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
  14748. 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
  14749. 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
  14750. 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
  14751. 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
  14752. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  14753. @image html callback_events.png "Example when certain parse events are triggered"
  14754. Discarding a value (i.e., returning `false`) has different effects
  14755. depending on the context in which function was called:
  14756. - Discarded values in structured types are skipped. That is, the parser
  14757. will behave as if the discarded value was never read.
  14758. - In case a value outside a structured type is skipped, it is replaced
  14759. with `null`. This case happens if the top-level element is skipped.
  14760. @param[in] depth the depth of the recursion during parsing
  14761. @param[in] event an event of type parse_event_t indicating the context in
  14762. the callback function has been called
  14763. @param[in,out] parsed the current intermediate parse result; note that
  14764. writing to this value has no effect for parse_event_t::key events
  14765. @return Whether the JSON value which called the function during parsing
  14766. should be kept (`true`) or not (`false`). In the latter case, it is either
  14767. skipped completely or replaced by an empty discarded object.
  14768. @sa @ref parse for examples
  14769. @since version 1.0.0
  14770. */
  14771. using parser_callback_t = detail::parser_callback_t<basic_json>;
  14772. //////////////////
  14773. // constructors //
  14774. //////////////////
  14775. /// @name constructors and destructors
  14776. /// Constructors of class @ref basic_json, copy/move constructor, copy
  14777. /// assignment, static functions creating objects, and the destructor.
  14778. /// @{
  14779. /*!
  14780. @brief create an empty value with a given type
  14781. Create an empty JSON value with a given type. The value will be default
  14782. initialized with an empty value which depends on the type:
  14783. Value type | initial value
  14784. ----------- | -------------
  14785. null | `null`
  14786. boolean | `false`
  14787. string | `""`
  14788. number | `0`
  14789. object | `{}`
  14790. array | `[]`
  14791. binary | empty array
  14792. @param[in] v the type of the value to create
  14793. @complexity Constant.
  14794. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14795. changes to any JSON value.
  14796. @liveexample{The following code shows the constructor for different @ref
  14797. value_t values,basic_json__value_t}
  14798. @sa @ref clear() -- restores the postcondition of this constructor
  14799. @since version 1.0.0
  14800. */
  14801. basic_json(const value_t v)
  14802. : m_type(v), m_value(v)
  14803. {
  14804. assert_invariant();
  14805. }
  14806. /*!
  14807. @brief create a null object
  14808. Create a `null` JSON value. It either takes a null pointer as parameter
  14809. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  14810. The passed null pointer itself is not read -- it is only used to choose
  14811. the right constructor.
  14812. @complexity Constant.
  14813. @exceptionsafety No-throw guarantee: this constructor never throws
  14814. exceptions.
  14815. @liveexample{The following code shows the constructor with and without a
  14816. null pointer parameter.,basic_json__nullptr_t}
  14817. @since version 1.0.0
  14818. */
  14819. basic_json(std::nullptr_t = nullptr) noexcept
  14820. : basic_json(value_t::null)
  14821. {
  14822. assert_invariant();
  14823. }
  14824. /*!
  14825. @brief create a JSON value
  14826. This is a "catch all" constructor for all compatible JSON types; that is,
  14827. types for which a `to_json()` method exists. The constructor forwards the
  14828. parameter @a val to that method (to `json_serializer<U>::to_json` method
  14829. with `U = uncvref_t<CompatibleType>`, to be exact).
  14830. Template type @a CompatibleType includes, but is not limited to, the
  14831. following types:
  14832. - **arrays**: @ref array_t and all kinds of compatible containers such as
  14833. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  14834. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  14835. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  14836. which a @ref basic_json value can be constructed.
  14837. - **objects**: @ref object_t and all kinds of compatible associative
  14838. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  14839. and `std::unordered_multimap` with a `key_type` compatible to
  14840. @ref string_t and a `value_type` from which a @ref basic_json value can
  14841. be constructed.
  14842. - **strings**: @ref string_t, string literals, and all compatible string
  14843. containers can be used.
  14844. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  14845. @ref number_float_t, and all convertible number types such as `int`,
  14846. `size_t`, `int64_t`, `float` or `double` can be used.
  14847. - **boolean**: @ref boolean_t / `bool` can be used.
  14848. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used,
  14849. unfortunately because string literals cannot be distinguished from binary
  14850. character arrays by the C++ type system, all types compatible with `const
  14851. char*` will be directed to the string constructor instead. This is both
  14852. for backwards compatibility, and due to the fact that a binary type is not
  14853. a standard JSON type.
  14854. See the examples below.
  14855. @tparam CompatibleType a type such that:
  14856. - @a CompatibleType is not derived from `std::istream`,
  14857. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  14858. constructors),
  14859. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  14860. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  14861. @ref json_pointer, @ref iterator, etc ...)
  14862. - @ref @ref json_serializer<U> has a
  14863. `to_json(basic_json_t&, CompatibleType&&)` method
  14864. @tparam U = `uncvref_t<CompatibleType>`
  14865. @param[in] val the value to be forwarded to the respective constructor
  14866. @complexity Usually linear in the size of the passed @a val, also
  14867. depending on the implementation of the called `to_json()`
  14868. method.
  14869. @exceptionsafety Depends on the called constructor. For types directly
  14870. supported by the library (i.e., all types for which no `to_json()` function
  14871. was provided), strong guarantee holds: if an exception is thrown, there are
  14872. no changes to any JSON value.
  14873. @liveexample{The following code shows the constructor with several
  14874. compatible types.,basic_json__CompatibleType}
  14875. @since version 2.1.0
  14876. */
  14877. template <typename CompatibleType,
  14878. typename U = detail::uncvref_t<CompatibleType>,
  14879. detail::enable_if_t<
  14880. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  14881. basic_json(CompatibleType && val) noexcept(noexcept(
  14882. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  14883. std::forward<CompatibleType>(val))))
  14884. {
  14885. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  14886. assert_invariant();
  14887. }
  14888. /*!
  14889. @brief create a JSON value from an existing one
  14890. This is a constructor for existing @ref basic_json types.
  14891. It does not hijack copy/move constructors, since the parameter has different
  14892. template arguments than the current ones.
  14893. The constructor tries to convert the internal @ref m_value of the parameter.
  14894. @tparam BasicJsonType a type such that:
  14895. - @a BasicJsonType is a @ref basic_json type.
  14896. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  14897. @param[in] val the @ref basic_json value to be converted.
  14898. @complexity Usually linear in the size of the passed @a val, also
  14899. depending on the implementation of the called `to_json()`
  14900. method.
  14901. @exceptionsafety Depends on the called constructor. For types directly
  14902. supported by the library (i.e., all types for which no `to_json()` function
  14903. was provided), strong guarantee holds: if an exception is thrown, there are
  14904. no changes to any JSON value.
  14905. @since version 3.2.0
  14906. */
  14907. template <typename BasicJsonType,
  14908. detail::enable_if_t<
  14909. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  14910. basic_json(const BasicJsonType& val)
  14911. {
  14912. using other_boolean_t = typename BasicJsonType::boolean_t;
  14913. using other_number_float_t = typename BasicJsonType::number_float_t;
  14914. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  14915. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  14916. using other_string_t = typename BasicJsonType::string_t;
  14917. using other_object_t = typename BasicJsonType::object_t;
  14918. using other_array_t = typename BasicJsonType::array_t;
  14919. using other_binary_t = typename BasicJsonType::binary_t;
  14920. switch (val.type())
  14921. {
  14922. case value_t::boolean:
  14923. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  14924. break;
  14925. case value_t::number_float:
  14926. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  14927. break;
  14928. case value_t::number_integer:
  14929. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  14930. break;
  14931. case value_t::number_unsigned:
  14932. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  14933. break;
  14934. case value_t::string:
  14935. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  14936. break;
  14937. case value_t::object:
  14938. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  14939. break;
  14940. case value_t::array:
  14941. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  14942. break;
  14943. case value_t::binary:
  14944. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  14945. break;
  14946. case value_t::null:
  14947. *this = nullptr;
  14948. break;
  14949. case value_t::discarded:
  14950. m_type = value_t::discarded;
  14951. break;
  14952. default: // LCOV_EXCL_LINE
  14953. assert(false); // LCOV_EXCL_LINE
  14954. }
  14955. assert_invariant();
  14956. }
  14957. /*!
  14958. @brief create a container (array or object) from an initializer list
  14959. Creates a JSON value of type array or object from the passed initializer
  14960. list @a init. In case @a type_deduction is `true` (default), the type of
  14961. the JSON value to be created is deducted from the initializer list @a init
  14962. according to the following rules:
  14963. 1. If the list is empty, an empty JSON object value `{}` is created.
  14964. 2. If the list consists of pairs whose first element is a string, a JSON
  14965. object value is created where the first elements of the pairs are
  14966. treated as keys and the second elements are as values.
  14967. 3. In all other cases, an array is created.
  14968. The rules aim to create the best fit between a C++ initializer list and
  14969. JSON values. The rationale is as follows:
  14970. 1. The empty initializer list is written as `{}` which is exactly an empty
  14971. JSON object.
  14972. 2. C++ has no way of describing mapped types other than to list a list of
  14973. pairs. As JSON requires that keys must be of type string, rule 2 is the
  14974. weakest constraint one can pose on initializer lists to interpret them
  14975. as an object.
  14976. 3. In all other cases, the initializer list could not be interpreted as
  14977. JSON object type, so interpreting it as JSON array type is safe.
  14978. With the rules described above, the following JSON values cannot be
  14979. expressed by an initializer list:
  14980. - the empty array (`[]`): use @ref array(initializer_list_t)
  14981. with an empty initializer list in this case
  14982. - arrays whose elements satisfy rule 2: use @ref
  14983. array(initializer_list_t) with the same initializer list
  14984. in this case
  14985. @note When used without parentheses around an empty initializer list, @ref
  14986. basic_json() is called instead of this function, yielding the JSON null
  14987. value.
  14988. @param[in] init initializer list with JSON values
  14989. @param[in] type_deduction internal parameter; when set to `true`, the type
  14990. of the JSON value is deducted from the initializer list @a init; when set
  14991. to `false`, the type provided via @a manual_type is forced. This mode is
  14992. used by the functions @ref array(initializer_list_t) and
  14993. @ref object(initializer_list_t).
  14994. @param[in] manual_type internal parameter; when @a type_deduction is set
  14995. to `false`, the created JSON value will use the provided type (only @ref
  14996. value_t::array and @ref value_t::object are valid); when @a type_deduction
  14997. is set to `true`, this parameter has no effect
  14998. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  14999. `value_t::object`, but @a init contains an element which is not a pair
  15000. whose first element is a string. In this case, the constructor could not
  15001. create an object. If @a type_deduction would have be `true`, an array
  15002. would have been created. See @ref object(initializer_list_t)
  15003. for an example.
  15004. @complexity Linear in the size of the initializer list @a init.
  15005. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15006. changes to any JSON value.
  15007. @liveexample{The example below shows how JSON values are created from
  15008. initializer lists.,basic_json__list_init_t}
  15009. @sa @ref array(initializer_list_t) -- create a JSON array
  15010. value from an initializer list
  15011. @sa @ref object(initializer_list_t) -- create a JSON object
  15012. value from an initializer list
  15013. @since version 1.0.0
  15014. */
  15015. basic_json(initializer_list_t init,
  15016. bool type_deduction = true,
  15017. value_t manual_type = value_t::array)
  15018. {
  15019. // check if each element is an array with two elements whose first
  15020. // element is a string
  15021. bool is_an_object = std::all_of(init.begin(), init.end(),
  15022. [](const detail::json_ref<basic_json>& element_ref)
  15023. {
  15024. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  15025. });
  15026. // adjust type if type deduction is not wanted
  15027. if (not type_deduction)
  15028. {
  15029. // if array is wanted, do not create an object though possible
  15030. if (manual_type == value_t::array)
  15031. {
  15032. is_an_object = false;
  15033. }
  15034. // if object is wanted but impossible, throw an exception
  15035. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  15036. {
  15037. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  15038. }
  15039. }
  15040. if (is_an_object)
  15041. {
  15042. // the initializer list is a list of pairs -> create object
  15043. m_type = value_t::object;
  15044. m_value = value_t::object;
  15045. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  15046. {
  15047. auto element = element_ref.moved_or_copied();
  15048. m_value.object->emplace(
  15049. std::move(*((*element.m_value.array)[0].m_value.string)),
  15050. std::move((*element.m_value.array)[1]));
  15051. });
  15052. }
  15053. else
  15054. {
  15055. // the initializer list describes an array -> create array
  15056. m_type = value_t::array;
  15057. m_value.array = create<array_t>(init.begin(), init.end());
  15058. }
  15059. assert_invariant();
  15060. }
  15061. /*!
  15062. @brief explicitly create a binary array (without subtype)
  15063. Creates a JSON binary array value from a given binary container. Binary
  15064. values are part of various binary formats, such as CBOR, MessagePack, and
  15065. BSON. This constructor is used to create a value for serialization to those
  15066. formats.
  15067. @note Note, this function exists because of the difficulty in correctly
  15068. specifying the correct template overload in the standard value ctor, as both
  15069. JSON arrays and JSON binary arrays are backed with some form of a
  15070. `std::vector`. Because JSON binary arrays are a non-standard extension it
  15071. was decided that it would be best to prevent automatic initialization of a
  15072. binary array type, for backwards compatibility and so it does not happen on
  15073. accident.
  15074. @param[in] init container containing bytes to use as binary type
  15075. @return JSON binary array value
  15076. @complexity Linear in the size of @a init.
  15077. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15078. changes to any JSON value.
  15079. @since version 3.8.0
  15080. */
  15081. JSON_HEDLEY_WARN_UNUSED_RESULT
  15082. static basic_json binary(const typename binary_t::container_type& init)
  15083. {
  15084. auto res = basic_json();
  15085. res.m_type = value_t::binary;
  15086. res.m_value = init;
  15087. return res;
  15088. }
  15089. /*!
  15090. @brief explicitly create a binary array (with subtype)
  15091. Creates a JSON binary array value from a given binary container. Binary
  15092. values are part of various binary formats, such as CBOR, MessagePack, and
  15093. BSON. This constructor is used to create a value for serialization to those
  15094. formats.
  15095. @note Note, this function exists because of the difficulty in correctly
  15096. specifying the correct template overload in the standard value ctor, as both
  15097. JSON arrays and JSON binary arrays are backed with some form of a
  15098. `std::vector`. Because JSON binary arrays are a non-standard extension it
  15099. was decided that it would be best to prevent automatic initialization of a
  15100. binary array type, for backwards compatibility and so it does not happen on
  15101. accident.
  15102. @param[in] init container containing bytes to use as binary type
  15103. @param[in] subtype subtype to use in MessagePack and BSON
  15104. @return JSON binary array value
  15105. @complexity Linear in the size of @a init.
  15106. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15107. changes to any JSON value.
  15108. @since version 3.8.0
  15109. */
  15110. JSON_HEDLEY_WARN_UNUSED_RESULT
  15111. static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype)
  15112. {
  15113. auto res = basic_json();
  15114. res.m_type = value_t::binary;
  15115. res.m_value = binary_t(init, subtype);
  15116. return res;
  15117. }
  15118. /// @copydoc binary(const typename binary_t::container_type&)
  15119. JSON_HEDLEY_WARN_UNUSED_RESULT
  15120. static basic_json binary(typename binary_t::container_type&& init)
  15121. {
  15122. auto res = basic_json();
  15123. res.m_type = value_t::binary;
  15124. res.m_value = std::move(init);
  15125. return res;
  15126. }
  15127. /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t)
  15128. JSON_HEDLEY_WARN_UNUSED_RESULT
  15129. static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype)
  15130. {
  15131. auto res = basic_json();
  15132. res.m_type = value_t::binary;
  15133. res.m_value = binary_t(std::move(init), subtype);
  15134. return res;
  15135. }
  15136. /*!
  15137. @brief explicitly create an array from an initializer list
  15138. Creates a JSON array value from a given initializer list. That is, given a
  15139. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  15140. initializer list is empty, the empty array `[]` is created.
  15141. @note This function is only needed to express two edge cases that cannot
  15142. be realized with the initializer list constructor (@ref
  15143. basic_json(initializer_list_t, bool, value_t)). These cases
  15144. are:
  15145. 1. creating an array whose elements are all pairs whose first element is a
  15146. string -- in this case, the initializer list constructor would create an
  15147. object, taking the first elements as keys
  15148. 2. creating an empty array -- passing the empty initializer list to the
  15149. initializer list constructor yields an empty object
  15150. @param[in] init initializer list with JSON values to create an array from
  15151. (optional)
  15152. @return JSON array value
  15153. @complexity Linear in the size of @a init.
  15154. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15155. changes to any JSON value.
  15156. @liveexample{The following code shows an example for the `array`
  15157. function.,array}
  15158. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  15159. create a JSON value from an initializer list
  15160. @sa @ref object(initializer_list_t) -- create a JSON object
  15161. value from an initializer list
  15162. @since version 1.0.0
  15163. */
  15164. JSON_HEDLEY_WARN_UNUSED_RESULT
  15165. static basic_json array(initializer_list_t init = {})
  15166. {
  15167. return basic_json(init, false, value_t::array);
  15168. }
  15169. /*!
  15170. @brief explicitly create an object from an initializer list
  15171. Creates a JSON object value from a given initializer list. The initializer
  15172. lists elements must be pairs, and their first elements must be strings. If
  15173. the initializer list is empty, the empty object `{}` is created.
  15174. @note This function is only added for symmetry reasons. In contrast to the
  15175. related function @ref array(initializer_list_t), there are
  15176. no cases which can only be expressed by this function. That is, any
  15177. initializer list @a init can also be passed to the initializer list
  15178. constructor @ref basic_json(initializer_list_t, bool, value_t).
  15179. @param[in] init initializer list to create an object from (optional)
  15180. @return JSON object value
  15181. @throw type_error.301 if @a init is not a list of pairs whose first
  15182. elements are strings. In this case, no object can be created. When such a
  15183. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  15184. an array would have been created from the passed initializer list @a init.
  15185. See example below.
  15186. @complexity Linear in the size of @a init.
  15187. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15188. changes to any JSON value.
  15189. @liveexample{The following code shows an example for the `object`
  15190. function.,object}
  15191. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  15192. create a JSON value from an initializer list
  15193. @sa @ref array(initializer_list_t) -- create a JSON array
  15194. value from an initializer list
  15195. @since version 1.0.0
  15196. */
  15197. JSON_HEDLEY_WARN_UNUSED_RESULT
  15198. static basic_json object(initializer_list_t init = {})
  15199. {
  15200. return basic_json(init, false, value_t::object);
  15201. }
  15202. /*!
  15203. @brief construct an array with count copies of given value
  15204. Constructs a JSON array value by creating @a cnt copies of a passed value.
  15205. In case @a cnt is `0`, an empty array is created.
  15206. @param[in] cnt the number of JSON copies of @a val to create
  15207. @param[in] val the JSON value to copy
  15208. @post `std::distance(begin(),end()) == cnt` holds.
  15209. @complexity Linear in @a cnt.
  15210. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15211. changes to any JSON value.
  15212. @liveexample{The following code shows examples for the @ref
  15213. basic_json(size_type\, const basic_json&)
  15214. constructor.,basic_json__size_type_basic_json}
  15215. @since version 1.0.0
  15216. */
  15217. basic_json(size_type cnt, const basic_json& val)
  15218. : m_type(value_t::array)
  15219. {
  15220. m_value.array = create<array_t>(cnt, val);
  15221. assert_invariant();
  15222. }
  15223. /*!
  15224. @brief construct a JSON container given an iterator range
  15225. Constructs the JSON value with the contents of the range `[first, last)`.
  15226. The semantics depends on the different types a JSON value can have:
  15227. - In case of a null type, invalid_iterator.206 is thrown.
  15228. - In case of other primitive types (number, boolean, or string), @a first
  15229. must be `begin()` and @a last must be `end()`. In this case, the value is
  15230. copied. Otherwise, invalid_iterator.204 is thrown.
  15231. - In case of structured types (array, object), the constructor behaves as
  15232. similar versions for `std::vector` or `std::map`; that is, a JSON array
  15233. or object is constructed from the values in the range.
  15234. @tparam InputIT an input iterator type (@ref iterator or @ref
  15235. const_iterator)
  15236. @param[in] first begin of the range to copy from (included)
  15237. @param[in] last end of the range to copy from (excluded)
  15238. @pre Iterators @a first and @a last must be initialized. **This
  15239. precondition is enforced with an assertion (see warning).** If
  15240. assertions are switched off, a violation of this precondition yields
  15241. undefined behavior.
  15242. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  15243. checked efficiently. Only certain edge cases are detected; see the
  15244. description of the exceptions below. A violation of this precondition
  15245. yields undefined behavior.
  15246. @warning A precondition is enforced with a runtime assertion that will
  15247. result in calling `std::abort` if this precondition is not met.
  15248. Assertions can be disabled by defining `NDEBUG` at compile time.
  15249. See https://en.cppreference.com/w/cpp/error/assert for more
  15250. information.
  15251. @throw invalid_iterator.201 if iterators @a first and @a last are not
  15252. compatible (i.e., do not belong to the same JSON value). In this case,
  15253. the range `[first, last)` is undefined.
  15254. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  15255. primitive type (number, boolean, or string), but @a first does not point
  15256. to the first element any more. In this case, the range `[first, last)` is
  15257. undefined. See example code below.
  15258. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  15259. null value. In this case, the range `[first, last)` is undefined.
  15260. @complexity Linear in distance between @a first and @a last.
  15261. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15262. changes to any JSON value.
  15263. @liveexample{The example below shows several ways to create JSON values by
  15264. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  15265. @since version 1.0.0
  15266. */
  15267. template<class InputIT, typename std::enable_if<
  15268. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  15269. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  15270. basic_json(InputIT first, InputIT last)
  15271. {
  15272. assert(first.m_object != nullptr);
  15273. assert(last.m_object != nullptr);
  15274. // make sure iterator fits the current value
  15275. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  15276. {
  15277. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  15278. }
  15279. // copy type from first iterator
  15280. m_type = first.m_object->m_type;
  15281. // check if iterator range is complete for primitive values
  15282. switch (m_type)
  15283. {
  15284. case value_t::boolean:
  15285. case value_t::number_float:
  15286. case value_t::number_integer:
  15287. case value_t::number_unsigned:
  15288. case value_t::string:
  15289. {
  15290. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  15291. or not last.m_it.primitive_iterator.is_end()))
  15292. {
  15293. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15294. }
  15295. break;
  15296. }
  15297. default:
  15298. break;
  15299. }
  15300. switch (m_type)
  15301. {
  15302. case value_t::number_integer:
  15303. {
  15304. m_value.number_integer = first.m_object->m_value.number_integer;
  15305. break;
  15306. }
  15307. case value_t::number_unsigned:
  15308. {
  15309. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  15310. break;
  15311. }
  15312. case value_t::number_float:
  15313. {
  15314. m_value.number_float = first.m_object->m_value.number_float;
  15315. break;
  15316. }
  15317. case value_t::boolean:
  15318. {
  15319. m_value.boolean = first.m_object->m_value.boolean;
  15320. break;
  15321. }
  15322. case value_t::string:
  15323. {
  15324. m_value = *first.m_object->m_value.string;
  15325. break;
  15326. }
  15327. case value_t::object:
  15328. {
  15329. m_value.object = create<object_t>(first.m_it.object_iterator,
  15330. last.m_it.object_iterator);
  15331. break;
  15332. }
  15333. case value_t::array:
  15334. {
  15335. m_value.array = create<array_t>(first.m_it.array_iterator,
  15336. last.m_it.array_iterator);
  15337. break;
  15338. }
  15339. case value_t::binary:
  15340. {
  15341. m_value = *first.m_object->m_value.binary;
  15342. break;
  15343. }
  15344. default:
  15345. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  15346. std::string(first.m_object->type_name())));
  15347. }
  15348. assert_invariant();
  15349. }
  15350. ///////////////////////////////////////
  15351. // other constructors and destructor //
  15352. ///////////////////////////////////////
  15353. template <typename JsonRef,
  15354. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  15355. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  15356. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  15357. /*!
  15358. @brief copy constructor
  15359. Creates a copy of a given JSON value.
  15360. @param[in] other the JSON value to copy
  15361. @post `*this == other`
  15362. @complexity Linear in the size of @a other.
  15363. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15364. changes to any JSON value.
  15365. @requirement This function helps `basic_json` satisfying the
  15366. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15367. requirements:
  15368. - The complexity is linear.
  15369. - As postcondition, it holds: `other == basic_json(other)`.
  15370. @liveexample{The following code shows an example for the copy
  15371. constructor.,basic_json__basic_json}
  15372. @since version 1.0.0
  15373. */
  15374. basic_json(const basic_json& other)
  15375. : m_type(other.m_type)
  15376. {
  15377. // check of passed value is valid
  15378. other.assert_invariant();
  15379. switch (m_type)
  15380. {
  15381. case value_t::object:
  15382. {
  15383. m_value = *other.m_value.object;
  15384. break;
  15385. }
  15386. case value_t::array:
  15387. {
  15388. m_value = *other.m_value.array;
  15389. break;
  15390. }
  15391. case value_t::string:
  15392. {
  15393. m_value = *other.m_value.string;
  15394. break;
  15395. }
  15396. case value_t::boolean:
  15397. {
  15398. m_value = other.m_value.boolean;
  15399. break;
  15400. }
  15401. case value_t::number_integer:
  15402. {
  15403. m_value = other.m_value.number_integer;
  15404. break;
  15405. }
  15406. case value_t::number_unsigned:
  15407. {
  15408. m_value = other.m_value.number_unsigned;
  15409. break;
  15410. }
  15411. case value_t::number_float:
  15412. {
  15413. m_value = other.m_value.number_float;
  15414. break;
  15415. }
  15416. case value_t::binary:
  15417. {
  15418. m_value = *other.m_value.binary;
  15419. break;
  15420. }
  15421. default:
  15422. break;
  15423. }
  15424. assert_invariant();
  15425. }
  15426. /*!
  15427. @brief move constructor
  15428. Move constructor. Constructs a JSON value with the contents of the given
  15429. value @a other using move semantics. It "steals" the resources from @a
  15430. other and leaves it as JSON null value.
  15431. @param[in,out] other value to move to this object
  15432. @post `*this` has the same value as @a other before the call.
  15433. @post @a other is a JSON null value.
  15434. @complexity Constant.
  15435. @exceptionsafety No-throw guarantee: this constructor never throws
  15436. exceptions.
  15437. @requirement This function helps `basic_json` satisfying the
  15438. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  15439. requirements.
  15440. @liveexample{The code below shows the move constructor explicitly called
  15441. via std::move.,basic_json__moveconstructor}
  15442. @since version 1.0.0
  15443. */
  15444. basic_json(basic_json&& other) noexcept
  15445. : m_type(std::move(other.m_type)),
  15446. m_value(std::move(other.m_value))
  15447. {
  15448. // check that passed value is valid
  15449. other.assert_invariant();
  15450. // invalidate payload
  15451. other.m_type = value_t::null;
  15452. other.m_value = {};
  15453. assert_invariant();
  15454. }
  15455. /*!
  15456. @brief copy assignment
  15457. Copy assignment operator. Copies a JSON value via the "copy and swap"
  15458. strategy: It is expressed in terms of the copy constructor, destructor,
  15459. and the `swap()` member function.
  15460. @param[in] other value to copy from
  15461. @complexity Linear.
  15462. @requirement This function helps `basic_json` satisfying the
  15463. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15464. requirements:
  15465. - The complexity is linear.
  15466. @liveexample{The code below shows and example for the copy assignment. It
  15467. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  15468. copy of `a` (which is the null value after the swap) is
  15469. destroyed.,basic_json__copyassignment}
  15470. @since version 1.0.0
  15471. */
  15472. basic_json& operator=(basic_json other) noexcept (
  15473. std::is_nothrow_move_constructible<value_t>::value and
  15474. std::is_nothrow_move_assignable<value_t>::value and
  15475. std::is_nothrow_move_constructible<json_value>::value and
  15476. std::is_nothrow_move_assignable<json_value>::value
  15477. )
  15478. {
  15479. // check that passed value is valid
  15480. other.assert_invariant();
  15481. using std::swap;
  15482. swap(m_type, other.m_type);
  15483. swap(m_value, other.m_value);
  15484. assert_invariant();
  15485. return *this;
  15486. }
  15487. /*!
  15488. @brief destructor
  15489. Destroys the JSON value and frees all allocated memory.
  15490. @complexity Linear.
  15491. @requirement This function helps `basic_json` satisfying the
  15492. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15493. requirements:
  15494. - The complexity is linear.
  15495. - All stored elements are destroyed and all memory is freed.
  15496. @since version 1.0.0
  15497. */
  15498. ~basic_json() noexcept
  15499. {
  15500. assert_invariant();
  15501. m_value.destroy(m_type);
  15502. }
  15503. /// @}
  15504. public:
  15505. ///////////////////////
  15506. // object inspection //
  15507. ///////////////////////
  15508. /// @name object inspection
  15509. /// Functions to inspect the type of a JSON value.
  15510. /// @{
  15511. /*!
  15512. @brief serialization
  15513. Serialization function for JSON values. The function tries to mimic
  15514. Python's `json.dumps()` function, and currently supports its @a indent
  15515. and @a ensure_ascii parameters.
  15516. @param[in] indent If indent is nonnegative, then array elements and object
  15517. members will be pretty-printed with that indent level. An indent level of
  15518. `0` will only insert newlines. `-1` (the default) selects the most compact
  15519. representation.
  15520. @param[in] indent_char The character to use for indentation if @a indent is
  15521. greater than `0`. The default is ` ` (space).
  15522. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  15523. in the output are escaped with `\uXXXX` sequences, and the result consists
  15524. of ASCII characters only.
  15525. @param[in] error_handler how to react on decoding errors; there are three
  15526. possible values: `strict` (throws and exception in case a decoding error
  15527. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  15528. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  15529. @return string containing the serialization of the JSON value
  15530. @throw type_error.316 if a string stored inside the JSON value is not
  15531. UTF-8 encoded and @a error_handler is set to strict
  15532. @note Binary values are serialized as object containing two keys:
  15533. - "bytes": an array of bytes as integers
  15534. - "subtype": the subtype as integer or "null" if the binary has no subtype
  15535. @complexity Linear.
  15536. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15537. changes in the JSON value.
  15538. @liveexample{The following example shows the effect of different @a indent\,
  15539. @a indent_char\, and @a ensure_ascii parameters to the result of the
  15540. serialization.,dump}
  15541. @see https://docs.python.org/2/library/json.html#json.dump
  15542. @since version 1.0.0; indentation character @a indent_char, option
  15543. @a ensure_ascii and exceptions added in version 3.0.0; error
  15544. handlers added in version 3.4.0; serialization of binary values added
  15545. in version 3.8.0.
  15546. */
  15547. string_t dump(const int indent = -1,
  15548. const char indent_char = ' ',
  15549. const bool ensure_ascii = false,
  15550. const error_handler_t error_handler = error_handler_t::strict) const
  15551. {
  15552. string_t result;
  15553. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  15554. if (indent >= 0)
  15555. {
  15556. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  15557. }
  15558. else
  15559. {
  15560. s.dump(*this, false, ensure_ascii, 0);
  15561. }
  15562. return result;
  15563. }
  15564. /*!
  15565. @brief return the type of the JSON value (explicit)
  15566. Return the type of the JSON value as a value from the @ref value_t
  15567. enumeration.
  15568. @return the type of the JSON value
  15569. Value type | return value
  15570. ------------------------- | -------------------------
  15571. null | value_t::null
  15572. boolean | value_t::boolean
  15573. string | value_t::string
  15574. number (integer) | value_t::number_integer
  15575. number (unsigned integer) | value_t::number_unsigned
  15576. number (floating-point) | value_t::number_float
  15577. object | value_t::object
  15578. array | value_t::array
  15579. binary | value_t::binary
  15580. discarded | value_t::discarded
  15581. @complexity Constant.
  15582. @exceptionsafety No-throw guarantee: this member function never throws
  15583. exceptions.
  15584. @liveexample{The following code exemplifies `type()` for all JSON
  15585. types.,type}
  15586. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  15587. @sa @ref type_name() -- return the type as string
  15588. @since version 1.0.0
  15589. */
  15590. constexpr value_t type() const noexcept
  15591. {
  15592. return m_type;
  15593. }
  15594. /*!
  15595. @brief return whether type is primitive
  15596. This function returns true if and only if the JSON type is primitive
  15597. (string, number, boolean, or null).
  15598. @return `true` if type is primitive (string, number, boolean, or null),
  15599. `false` otherwise.
  15600. @complexity Constant.
  15601. @exceptionsafety No-throw guarantee: this member function never throws
  15602. exceptions.
  15603. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  15604. types.,is_primitive}
  15605. @sa @ref is_structured() -- returns whether JSON value is structured
  15606. @sa @ref is_null() -- returns whether JSON value is `null`
  15607. @sa @ref is_string() -- returns whether JSON value is a string
  15608. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  15609. @sa @ref is_number() -- returns whether JSON value is a number
  15610. @sa @ref is_binary() -- returns whether JSON value is a binary array
  15611. @since version 1.0.0
  15612. */
  15613. constexpr bool is_primitive() const noexcept
  15614. {
  15615. return is_null() or is_string() or is_boolean() or is_number() or is_binary();
  15616. }
  15617. /*!
  15618. @brief return whether type is structured
  15619. This function returns true if and only if the JSON type is structured
  15620. (array or object).
  15621. @return `true` if type is structured (array or object), `false` otherwise.
  15622. @complexity Constant.
  15623. @exceptionsafety No-throw guarantee: this member function never throws
  15624. exceptions.
  15625. @liveexample{The following code exemplifies `is_structured()` for all JSON
  15626. types.,is_structured}
  15627. @sa @ref is_primitive() -- returns whether value is primitive
  15628. @sa @ref is_array() -- returns whether value is an array
  15629. @sa @ref is_object() -- returns whether value is an object
  15630. @since version 1.0.0
  15631. */
  15632. constexpr bool is_structured() const noexcept
  15633. {
  15634. return is_array() or is_object();
  15635. }
  15636. /*!
  15637. @brief return whether value is null
  15638. This function returns true if and only if the JSON value is null.
  15639. @return `true` if type is null, `false` otherwise.
  15640. @complexity Constant.
  15641. @exceptionsafety No-throw guarantee: this member function never throws
  15642. exceptions.
  15643. @liveexample{The following code exemplifies `is_null()` for all JSON
  15644. types.,is_null}
  15645. @since version 1.0.0
  15646. */
  15647. constexpr bool is_null() const noexcept
  15648. {
  15649. return m_type == value_t::null;
  15650. }
  15651. /*!
  15652. @brief return whether value is a boolean
  15653. This function returns true if and only if the JSON value is a boolean.
  15654. @return `true` if type is boolean, `false` otherwise.
  15655. @complexity Constant.
  15656. @exceptionsafety No-throw guarantee: this member function never throws
  15657. exceptions.
  15658. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  15659. types.,is_boolean}
  15660. @since version 1.0.0
  15661. */
  15662. constexpr bool is_boolean() const noexcept
  15663. {
  15664. return m_type == value_t::boolean;
  15665. }
  15666. /*!
  15667. @brief return whether value is a number
  15668. This function returns true if and only if the JSON value is a number. This
  15669. includes both integer (signed and unsigned) and floating-point values.
  15670. @return `true` if type is number (regardless whether integer, unsigned
  15671. integer or floating-type), `false` otherwise.
  15672. @complexity Constant.
  15673. @exceptionsafety No-throw guarantee: this member function never throws
  15674. exceptions.
  15675. @liveexample{The following code exemplifies `is_number()` for all JSON
  15676. types.,is_number}
  15677. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15678. integer number
  15679. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15680. number
  15681. @sa @ref is_number_float() -- check if value is a floating-point number
  15682. @since version 1.0.0
  15683. */
  15684. constexpr bool is_number() const noexcept
  15685. {
  15686. return is_number_integer() or is_number_float();
  15687. }
  15688. /*!
  15689. @brief return whether value is an integer number
  15690. This function returns true if and only if the JSON value is a signed or
  15691. unsigned integer number. This excludes floating-point values.
  15692. @return `true` if type is an integer or unsigned integer number, `false`
  15693. otherwise.
  15694. @complexity Constant.
  15695. @exceptionsafety No-throw guarantee: this member function never throws
  15696. exceptions.
  15697. @liveexample{The following code exemplifies `is_number_integer()` for all
  15698. JSON types.,is_number_integer}
  15699. @sa @ref is_number() -- check if value is a number
  15700. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15701. number
  15702. @sa @ref is_number_float() -- check if value is a floating-point number
  15703. @since version 1.0.0
  15704. */
  15705. constexpr bool is_number_integer() const noexcept
  15706. {
  15707. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  15708. }
  15709. /*!
  15710. @brief return whether value is an unsigned integer number
  15711. This function returns true if and only if the JSON value is an unsigned
  15712. integer number. This excludes floating-point and signed integer values.
  15713. @return `true` if type is an unsigned integer number, `false` otherwise.
  15714. @complexity Constant.
  15715. @exceptionsafety No-throw guarantee: this member function never throws
  15716. exceptions.
  15717. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  15718. JSON types.,is_number_unsigned}
  15719. @sa @ref is_number() -- check if value is a number
  15720. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15721. integer number
  15722. @sa @ref is_number_float() -- check if value is a floating-point number
  15723. @since version 2.0.0
  15724. */
  15725. constexpr bool is_number_unsigned() const noexcept
  15726. {
  15727. return m_type == value_t::number_unsigned;
  15728. }
  15729. /*!
  15730. @brief return whether value is a floating-point number
  15731. This function returns true if and only if the JSON value is a
  15732. floating-point number. This excludes signed and unsigned integer values.
  15733. @return `true` if type is a floating-point number, `false` otherwise.
  15734. @complexity Constant.
  15735. @exceptionsafety No-throw guarantee: this member function never throws
  15736. exceptions.
  15737. @liveexample{The following code exemplifies `is_number_float()` for all
  15738. JSON types.,is_number_float}
  15739. @sa @ref is_number() -- check if value is number
  15740. @sa @ref is_number_integer() -- check if value is an integer number
  15741. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15742. number
  15743. @since version 1.0.0
  15744. */
  15745. constexpr bool is_number_float() const noexcept
  15746. {
  15747. return m_type == value_t::number_float;
  15748. }
  15749. /*!
  15750. @brief return whether value is an object
  15751. This function returns true if and only if the JSON value is an object.
  15752. @return `true` if type is object, `false` otherwise.
  15753. @complexity Constant.
  15754. @exceptionsafety No-throw guarantee: this member function never throws
  15755. exceptions.
  15756. @liveexample{The following code exemplifies `is_object()` for all JSON
  15757. types.,is_object}
  15758. @since version 1.0.0
  15759. */
  15760. constexpr bool is_object() const noexcept
  15761. {
  15762. return m_type == value_t::object;
  15763. }
  15764. /*!
  15765. @brief return whether value is an array
  15766. This function returns true if and only if the JSON value is an array.
  15767. @return `true` if type is array, `false` otherwise.
  15768. @complexity Constant.
  15769. @exceptionsafety No-throw guarantee: this member function never throws
  15770. exceptions.
  15771. @liveexample{The following code exemplifies `is_array()` for all JSON
  15772. types.,is_array}
  15773. @since version 1.0.0
  15774. */
  15775. constexpr bool is_array() const noexcept
  15776. {
  15777. return m_type == value_t::array;
  15778. }
  15779. /*!
  15780. @brief return whether value is a string
  15781. This function returns true if and only if the JSON value is a string.
  15782. @return `true` if type is string, `false` otherwise.
  15783. @complexity Constant.
  15784. @exceptionsafety No-throw guarantee: this member function never throws
  15785. exceptions.
  15786. @liveexample{The following code exemplifies `is_string()` for all JSON
  15787. types.,is_string}
  15788. @since version 1.0.0
  15789. */
  15790. constexpr bool is_string() const noexcept
  15791. {
  15792. return m_type == value_t::string;
  15793. }
  15794. /*!
  15795. @brief return whether value is a binary array
  15796. This function returns true if and only if the JSON value is a binary array.
  15797. @return `true` if type is binary array, `false` otherwise.
  15798. @complexity Constant.
  15799. @exceptionsafety No-throw guarantee: this member function never throws
  15800. exceptions.
  15801. @liveexample{The following code exemplifies `is_binary()` for all JSON
  15802. types.,is_binary}
  15803. @since version 3.8.0
  15804. */
  15805. constexpr bool is_binary() const noexcept
  15806. {
  15807. return m_type == value_t::binary;
  15808. }
  15809. /*!
  15810. @brief return whether value is discarded
  15811. This function returns true if and only if the JSON value was discarded
  15812. during parsing with a callback function (see @ref parser_callback_t).
  15813. @note This function will always be `false` for JSON values after parsing.
  15814. That is, discarded values can only occur during parsing, but will be
  15815. removed when inside a structured value or replaced by null in other cases.
  15816. @return `true` if type is discarded, `false` otherwise.
  15817. @complexity Constant.
  15818. @exceptionsafety No-throw guarantee: this member function never throws
  15819. exceptions.
  15820. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  15821. types.,is_discarded}
  15822. @since version 1.0.0
  15823. */
  15824. constexpr bool is_discarded() const noexcept
  15825. {
  15826. return m_type == value_t::discarded;
  15827. }
  15828. /*!
  15829. @brief return the type of the JSON value (implicit)
  15830. Implicitly return the type of the JSON value as a value from the @ref
  15831. value_t enumeration.
  15832. @return the type of the JSON value
  15833. @complexity Constant.
  15834. @exceptionsafety No-throw guarantee: this member function never throws
  15835. exceptions.
  15836. @liveexample{The following code exemplifies the @ref value_t operator for
  15837. all JSON types.,operator__value_t}
  15838. @sa @ref type() -- return the type of the JSON value (explicit)
  15839. @sa @ref type_name() -- return the type as string
  15840. @since version 1.0.0
  15841. */
  15842. constexpr operator value_t() const noexcept
  15843. {
  15844. return m_type;
  15845. }
  15846. /// @}
  15847. private:
  15848. //////////////////
  15849. // value access //
  15850. //////////////////
  15851. /// get a boolean (explicit)
  15852. boolean_t get_impl(boolean_t* /*unused*/) const
  15853. {
  15854. if (JSON_HEDLEY_LIKELY(is_boolean()))
  15855. {
  15856. return m_value.boolean;
  15857. }
  15858. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  15859. }
  15860. /// get a pointer to the value (object)
  15861. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  15862. {
  15863. return is_object() ? m_value.object : nullptr;
  15864. }
  15865. /// get a pointer to the value (object)
  15866. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  15867. {
  15868. return is_object() ? m_value.object : nullptr;
  15869. }
  15870. /// get a pointer to the value (array)
  15871. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  15872. {
  15873. return is_array() ? m_value.array : nullptr;
  15874. }
  15875. /// get a pointer to the value (array)
  15876. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  15877. {
  15878. return is_array() ? m_value.array : nullptr;
  15879. }
  15880. /// get a pointer to the value (string)
  15881. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  15882. {
  15883. return is_string() ? m_value.string : nullptr;
  15884. }
  15885. /// get a pointer to the value (string)
  15886. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  15887. {
  15888. return is_string() ? m_value.string : nullptr;
  15889. }
  15890. /// get a pointer to the value (boolean)
  15891. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  15892. {
  15893. return is_boolean() ? &m_value.boolean : nullptr;
  15894. }
  15895. /// get a pointer to the value (boolean)
  15896. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  15897. {
  15898. return is_boolean() ? &m_value.boolean : nullptr;
  15899. }
  15900. /// get a pointer to the value (integer number)
  15901. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  15902. {
  15903. return is_number_integer() ? &m_value.number_integer : nullptr;
  15904. }
  15905. /// get a pointer to the value (integer number)
  15906. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  15907. {
  15908. return is_number_integer() ? &m_value.number_integer : nullptr;
  15909. }
  15910. /// get a pointer to the value (unsigned number)
  15911. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  15912. {
  15913. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  15914. }
  15915. /// get a pointer to the value (unsigned number)
  15916. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  15917. {
  15918. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  15919. }
  15920. /// get a pointer to the value (floating-point number)
  15921. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  15922. {
  15923. return is_number_float() ? &m_value.number_float : nullptr;
  15924. }
  15925. /// get a pointer to the value (floating-point number)
  15926. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  15927. {
  15928. return is_number_float() ? &m_value.number_float : nullptr;
  15929. }
  15930. /// get a pointer to the value (binary)
  15931. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  15932. {
  15933. return is_binary() ? m_value.binary : nullptr;
  15934. }
  15935. /// get a pointer to the value (binary)
  15936. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  15937. {
  15938. return is_binary() ? m_value.binary : nullptr;
  15939. }
  15940. /*!
  15941. @brief helper function to implement get_ref()
  15942. This function helps to implement get_ref() without code duplication for
  15943. const and non-const overloads
  15944. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  15945. @throw type_error.303 if ReferenceType does not match underlying value
  15946. type of the current JSON
  15947. */
  15948. template<typename ReferenceType, typename ThisType>
  15949. static ReferenceType get_ref_impl(ThisType& obj)
  15950. {
  15951. // delegate the call to get_ptr<>()
  15952. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  15953. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  15954. {
  15955. return *ptr;
  15956. }
  15957. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  15958. }
  15959. public:
  15960. /// @name value access
  15961. /// Direct access to the stored value of a JSON value.
  15962. /// @{
  15963. /*!
  15964. @brief get special-case overload
  15965. This overloads avoids a lot of template boilerplate, it can be seen as the
  15966. identity method
  15967. @tparam BasicJsonType == @ref basic_json
  15968. @return a copy of *this
  15969. @complexity Constant.
  15970. @since version 2.1.0
  15971. */
  15972. template<typename BasicJsonType, detail::enable_if_t<
  15973. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  15974. int> = 0>
  15975. basic_json get() const
  15976. {
  15977. return *this;
  15978. }
  15979. /*!
  15980. @brief get special-case overload
  15981. This overloads converts the current @ref basic_json in a different
  15982. @ref basic_json type
  15983. @tparam BasicJsonType == @ref basic_json
  15984. @return a copy of *this, converted into @tparam BasicJsonType
  15985. @complexity Depending on the implementation of the called `from_json()`
  15986. method.
  15987. @since version 3.2.0
  15988. */
  15989. template<typename BasicJsonType, detail::enable_if_t<
  15990. not std::is_same<BasicJsonType, basic_json>::value and
  15991. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  15992. BasicJsonType get() const
  15993. {
  15994. return *this;
  15995. }
  15996. /*!
  15997. @brief get a value (explicit)
  15998. Explicit type conversion between the JSON value and a compatible value
  15999. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16000. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16001. The value is converted by calling the @ref json_serializer<ValueType>
  16002. `from_json()` method.
  16003. The function is equivalent to executing
  16004. @code {.cpp}
  16005. ValueType ret;
  16006. JSONSerializer<ValueType>::from_json(*this, ret);
  16007. return ret;
  16008. @endcode
  16009. This overloads is chosen if:
  16010. - @a ValueType is not @ref basic_json,
  16011. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16012. `void from_json(const basic_json&, ValueType&)`, and
  16013. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  16014. the form `ValueType from_json(const basic_json&)`
  16015. @tparam ValueTypeCV the provided value type
  16016. @tparam ValueType the returned value type
  16017. @return copy of the JSON value, converted to @a ValueType
  16018. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16019. @liveexample{The example below shows several conversions from JSON values
  16020. to other types. There a few things to note: (1) Floating-point numbers can
  16021. be converted to integers\, (2) A JSON array can be converted to a standard
  16022. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16023. associative containers such as `std::unordered_map<std::string\,
  16024. json>`.,get__ValueType_const}
  16025. @since version 2.1.0
  16026. */
  16027. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  16028. detail::enable_if_t <
  16029. not detail::is_basic_json<ValueType>::value and
  16030. detail::has_from_json<basic_json_t, ValueType>::value and
  16031. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16032. int> = 0>
  16033. ValueType get() const noexcept(noexcept(
  16034. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  16035. {
  16036. // we cannot static_assert on ValueTypeCV being non-const, because
  16037. // there is support for get<const basic_json_t>(), which is why we
  16038. // still need the uncvref
  16039. static_assert(not std::is_reference<ValueTypeCV>::value,
  16040. "get() cannot be used with reference types, you might want to use get_ref()");
  16041. static_assert(std::is_default_constructible<ValueType>::value,
  16042. "types must be DefaultConstructible when used with get()");
  16043. ValueType ret;
  16044. JSONSerializer<ValueType>::from_json(*this, ret);
  16045. return ret;
  16046. }
  16047. /*!
  16048. @brief get a value (explicit); special case
  16049. Explicit type conversion between the JSON value and a compatible value
  16050. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16051. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16052. The value is converted by calling the @ref json_serializer<ValueType>
  16053. `from_json()` method.
  16054. The function is equivalent to executing
  16055. @code {.cpp}
  16056. return JSONSerializer<ValueTypeCV>::from_json(*this);
  16057. @endcode
  16058. This overloads is chosen if:
  16059. - @a ValueType is not @ref basic_json and
  16060. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16061. `ValueType from_json(const basic_json&)`
  16062. @note If @ref json_serializer<ValueType> has both overloads of
  16063. `from_json()`, this one is chosen.
  16064. @tparam ValueTypeCV the provided value type
  16065. @tparam ValueType the returned value type
  16066. @return copy of the JSON value, converted to @a ValueType
  16067. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16068. @since version 2.1.0
  16069. */
  16070. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  16071. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  16072. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16073. int> = 0>
  16074. ValueType get() const noexcept(noexcept(
  16075. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  16076. {
  16077. static_assert(not std::is_reference<ValueTypeCV>::value,
  16078. "get() cannot be used with reference types, you might want to use get_ref()");
  16079. return JSONSerializer<ValueType>::from_json(*this);
  16080. }
  16081. /*!
  16082. @brief get a value (explicit)
  16083. Explicit type conversion between the JSON value and a compatible value.
  16084. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  16085. `from_json()` method.
  16086. The function is equivalent to executing
  16087. @code {.cpp}
  16088. ValueType v;
  16089. JSONSerializer<ValueType>::from_json(*this, v);
  16090. @endcode
  16091. This overloads is chosen if:
  16092. - @a ValueType is not @ref basic_json,
  16093. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16094. `void from_json(const basic_json&, ValueType&)`, and
  16095. @tparam ValueType the input parameter type.
  16096. @return the input parameter, allowing chaining calls.
  16097. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16098. @liveexample{The example below shows several conversions from JSON values
  16099. to other types. There a few things to note: (1) Floating-point numbers can
  16100. be converted to integers\, (2) A JSON array can be converted to a standard
  16101. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16102. associative containers such as `std::unordered_map<std::string\,
  16103. json>`.,get_to}
  16104. @since version 3.3.0
  16105. */
  16106. template<typename ValueType,
  16107. detail::enable_if_t <
  16108. not detail::is_basic_json<ValueType>::value and
  16109. detail::has_from_json<basic_json_t, ValueType>::value,
  16110. int> = 0>
  16111. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  16112. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  16113. {
  16114. JSONSerializer<ValueType>::from_json(*this, v);
  16115. return v;
  16116. }
  16117. template <
  16118. typename T, std::size_t N,
  16119. typename Array = T (&)[N],
  16120. detail::enable_if_t <
  16121. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  16122. Array get_to(T (&v)[N]) const
  16123. noexcept(noexcept(JSONSerializer<Array>::from_json(
  16124. std::declval<const basic_json_t&>(), v)))
  16125. {
  16126. JSONSerializer<Array>::from_json(*this, v);
  16127. return v;
  16128. }
  16129. /*!
  16130. @brief get a pointer value (implicit)
  16131. Implicit pointer access to the internally stored JSON value. No copies are
  16132. made.
  16133. @warning Writing data to the pointee of the result yields an undefined
  16134. state.
  16135. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16136. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16137. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  16138. assertion.
  16139. @return pointer to the internally stored JSON value if the requested
  16140. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16141. @complexity Constant.
  16142. @liveexample{The example below shows how pointers to internal values of a
  16143. JSON value can be requested. Note that no type conversions are made and a
  16144. `nullptr` is returned if the value and the requested pointer type does not
  16145. match.,get_ptr}
  16146. @since version 1.0.0
  16147. */
  16148. template<typename PointerType, typename std::enable_if<
  16149. std::is_pointer<PointerType>::value, int>::type = 0>
  16150. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16151. {
  16152. // delegate the call to get_impl_ptr<>()
  16153. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16154. }
  16155. /*!
  16156. @brief get a pointer value (implicit)
  16157. @copydoc get_ptr()
  16158. */
  16159. template<typename PointerType, typename std::enable_if<
  16160. std::is_pointer<PointerType>::value and
  16161. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  16162. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16163. {
  16164. // delegate the call to get_impl_ptr<>() const
  16165. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16166. }
  16167. /*!
  16168. @brief get a pointer value (explicit)
  16169. Explicit pointer access to the internally stored JSON value. No copies are
  16170. made.
  16171. @warning The pointer becomes invalid if the underlying JSON object
  16172. changes.
  16173. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16174. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16175. @ref number_unsigned_t, or @ref number_float_t.
  16176. @return pointer to the internally stored JSON value if the requested
  16177. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16178. @complexity Constant.
  16179. @liveexample{The example below shows how pointers to internal values of a
  16180. JSON value can be requested. Note that no type conversions are made and a
  16181. `nullptr` is returned if the value and the requested pointer type does not
  16182. match.,get__PointerType}
  16183. @sa @ref get_ptr() for explicit pointer-member access
  16184. @since version 1.0.0
  16185. */
  16186. template<typename PointerType, typename std::enable_if<
  16187. std::is_pointer<PointerType>::value, int>::type = 0>
  16188. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  16189. {
  16190. // delegate the call to get_ptr
  16191. return get_ptr<PointerType>();
  16192. }
  16193. /*!
  16194. @brief get a pointer value (explicit)
  16195. @copydoc get()
  16196. */
  16197. template<typename PointerType, typename std::enable_if<
  16198. std::is_pointer<PointerType>::value, int>::type = 0>
  16199. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  16200. {
  16201. // delegate the call to get_ptr
  16202. return get_ptr<PointerType>();
  16203. }
  16204. /*!
  16205. @brief get a reference value (implicit)
  16206. Implicit reference access to the internally stored JSON value. No copies
  16207. are made.
  16208. @warning Writing data to the referee of the result yields an undefined
  16209. state.
  16210. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  16211. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  16212. @ref number_float_t. Enforced by static assertion.
  16213. @return reference to the internally stored JSON value if the requested
  16214. reference type @a ReferenceType fits to the JSON value; throws
  16215. type_error.303 otherwise
  16216. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  16217. with the stored JSON value; see example below
  16218. @complexity Constant.
  16219. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  16220. @since version 1.1.0
  16221. */
  16222. template<typename ReferenceType, typename std::enable_if<
  16223. std::is_reference<ReferenceType>::value, int>::type = 0>
  16224. ReferenceType get_ref()
  16225. {
  16226. // delegate call to get_ref_impl
  16227. return get_ref_impl<ReferenceType>(*this);
  16228. }
  16229. /*!
  16230. @brief get a reference value (implicit)
  16231. @copydoc get_ref()
  16232. */
  16233. template<typename ReferenceType, typename std::enable_if<
  16234. std::is_reference<ReferenceType>::value and
  16235. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  16236. ReferenceType get_ref() const
  16237. {
  16238. // delegate call to get_ref_impl
  16239. return get_ref_impl<ReferenceType>(*this);
  16240. }
  16241. /*!
  16242. @brief get a value (implicit)
  16243. Implicit type conversion between the JSON value and a compatible value.
  16244. The call is realized by calling @ref get() const.
  16245. @tparam ValueType non-pointer type compatible to the JSON value, for
  16246. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  16247. `std::vector` types for JSON arrays. The character type of @ref string_t
  16248. as well as an initializer list of this type is excluded to avoid
  16249. ambiguities as these types implicitly convert to `std::string`.
  16250. @return copy of the JSON value, converted to type @a ValueType
  16251. @throw type_error.302 in case passed type @a ValueType is incompatible
  16252. to the JSON value type (e.g., the JSON value is of type boolean, but a
  16253. string is requested); see example below
  16254. @complexity Linear in the size of the JSON value.
  16255. @liveexample{The example below shows several conversions from JSON values
  16256. to other types. There a few things to note: (1) Floating-point numbers can
  16257. be converted to integers\, (2) A JSON array can be converted to a standard
  16258. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16259. associative containers such as `std::unordered_map<std::string\,
  16260. json>`.,operator__ValueType}
  16261. @since version 1.0.0
  16262. */
  16263. template < typename ValueType, typename std::enable_if <
  16264. not std::is_pointer<ValueType>::value and
  16265. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  16266. not std::is_same<ValueType, typename string_t::value_type>::value and
  16267. not detail::is_basic_json<ValueType>::value
  16268. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  16269. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER >= 1910 and _MSC_VER <= 1914))
  16270. and not std::is_same<ValueType, typename std::string_view>::value
  16271. #endif
  16272. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  16273. , int >::type = 0 >
  16274. operator ValueType() const
  16275. {
  16276. // delegate the call to get<>() const
  16277. return get<ValueType>();
  16278. }
  16279. /*!
  16280. @return reference to the binary value
  16281. @throw type_error.302 if the value is not binary
  16282. @sa @ref is_binary() to check if the value is binary
  16283. @since version 3.8.0
  16284. */
  16285. binary_t& get_binary()
  16286. {
  16287. if (not is_binary())
  16288. {
  16289. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  16290. }
  16291. return *get_ptr<binary_t*>();
  16292. }
  16293. /// @copydoc get_binary()
  16294. const binary_t& get_binary() const
  16295. {
  16296. if (not is_binary())
  16297. {
  16298. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  16299. }
  16300. return *get_ptr<const binary_t*>();
  16301. }
  16302. /// @}
  16303. ////////////////////
  16304. // element access //
  16305. ////////////////////
  16306. /// @name element access
  16307. /// Access to the JSON value.
  16308. /// @{
  16309. /*!
  16310. @brief access specified array element with bounds checking
  16311. Returns a reference to the element at specified location @a idx, with
  16312. bounds checking.
  16313. @param[in] idx index of the element to access
  16314. @return reference to the element at index @a idx
  16315. @throw type_error.304 if the JSON value is not an array; in this case,
  16316. calling `at` with an index makes no sense. See example below.
  16317. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16318. that is, `idx >= size()`. See example below.
  16319. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16320. changes in the JSON value.
  16321. @complexity Constant.
  16322. @since version 1.0.0
  16323. @liveexample{The example below shows how array elements can be read and
  16324. written using `at()`. It also demonstrates the different exceptions that
  16325. can be thrown.,at__size_type}
  16326. */
  16327. reference at(size_type idx)
  16328. {
  16329. // at only works for arrays
  16330. if (JSON_HEDLEY_LIKELY(is_array()))
  16331. {
  16332. JSON_TRY
  16333. {
  16334. return m_value.array->at(idx);
  16335. }
  16336. JSON_CATCH (std::out_of_range&)
  16337. {
  16338. // create better exception explanation
  16339. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16340. }
  16341. }
  16342. else
  16343. {
  16344. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16345. }
  16346. }
  16347. /*!
  16348. @brief access specified array element with bounds checking
  16349. Returns a const reference to the element at specified location @a idx,
  16350. with bounds checking.
  16351. @param[in] idx index of the element to access
  16352. @return const reference to the element at index @a idx
  16353. @throw type_error.304 if the JSON value is not an array; in this case,
  16354. calling `at` with an index makes no sense. See example below.
  16355. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16356. that is, `idx >= size()`. See example below.
  16357. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16358. changes in the JSON value.
  16359. @complexity Constant.
  16360. @since version 1.0.0
  16361. @liveexample{The example below shows how array elements can be read using
  16362. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16363. at__size_type_const}
  16364. */
  16365. const_reference at(size_type idx) const
  16366. {
  16367. // at only works for arrays
  16368. if (JSON_HEDLEY_LIKELY(is_array()))
  16369. {
  16370. JSON_TRY
  16371. {
  16372. return m_value.array->at(idx);
  16373. }
  16374. JSON_CATCH (std::out_of_range&)
  16375. {
  16376. // create better exception explanation
  16377. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16378. }
  16379. }
  16380. else
  16381. {
  16382. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16383. }
  16384. }
  16385. /*!
  16386. @brief access specified object element with bounds checking
  16387. Returns a reference to the element at with specified key @a key, with
  16388. bounds checking.
  16389. @param[in] key key of the element to access
  16390. @return reference to the element at key @a key
  16391. @throw type_error.304 if the JSON value is not an object; in this case,
  16392. calling `at` with a key makes no sense. See example below.
  16393. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16394. that is, `find(key) == end()`. See example below.
  16395. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16396. changes in the JSON value.
  16397. @complexity Logarithmic in the size of the container.
  16398. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16399. access by reference
  16400. @sa @ref value() for access by value with a default value
  16401. @since version 1.0.0
  16402. @liveexample{The example below shows how object elements can be read and
  16403. written using `at()`. It also demonstrates the different exceptions that
  16404. can be thrown.,at__object_t_key_type}
  16405. */
  16406. reference at(const typename object_t::key_type& key)
  16407. {
  16408. // at only works for objects
  16409. if (JSON_HEDLEY_LIKELY(is_object()))
  16410. {
  16411. JSON_TRY
  16412. {
  16413. return m_value.object->at(key);
  16414. }
  16415. JSON_CATCH (std::out_of_range&)
  16416. {
  16417. // create better exception explanation
  16418. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16419. }
  16420. }
  16421. else
  16422. {
  16423. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16424. }
  16425. }
  16426. /*!
  16427. @brief access specified object element with bounds checking
  16428. Returns a const reference to the element at with specified key @a key,
  16429. with bounds checking.
  16430. @param[in] key key of the element to access
  16431. @return const reference to the element at key @a key
  16432. @throw type_error.304 if the JSON value is not an object; in this case,
  16433. calling `at` with a key makes no sense. See example below.
  16434. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16435. that is, `find(key) == end()`. See example below.
  16436. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16437. changes in the JSON value.
  16438. @complexity Logarithmic in the size of the container.
  16439. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16440. access by reference
  16441. @sa @ref value() for access by value with a default value
  16442. @since version 1.0.0
  16443. @liveexample{The example below shows how object elements can be read using
  16444. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16445. at__object_t_key_type_const}
  16446. */
  16447. const_reference at(const typename object_t::key_type& key) const
  16448. {
  16449. // at only works for objects
  16450. if (JSON_HEDLEY_LIKELY(is_object()))
  16451. {
  16452. JSON_TRY
  16453. {
  16454. return m_value.object->at(key);
  16455. }
  16456. JSON_CATCH (std::out_of_range&)
  16457. {
  16458. // create better exception explanation
  16459. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16460. }
  16461. }
  16462. else
  16463. {
  16464. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16465. }
  16466. }
  16467. /*!
  16468. @brief access specified array element
  16469. Returns a reference to the element at specified location @a idx.
  16470. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  16471. then the array is silently filled up with `null` values to make `idx` a
  16472. valid reference to the last stored element.
  16473. @param[in] idx index of the element to access
  16474. @return reference to the element at index @a idx
  16475. @throw type_error.305 if the JSON value is not an array or null; in that
  16476. cases, using the [] operator with an index makes no sense.
  16477. @complexity Constant if @a idx is in the range of the array. Otherwise
  16478. linear in `idx - size()`.
  16479. @liveexample{The example below shows how array elements can be read and
  16480. written using `[]` operator. Note the addition of `null`
  16481. values.,operatorarray__size_type}
  16482. @since version 1.0.0
  16483. */
  16484. reference operator[](size_type idx)
  16485. {
  16486. // implicitly convert null value to an empty array
  16487. if (is_null())
  16488. {
  16489. m_type = value_t::array;
  16490. m_value.array = create<array_t>();
  16491. assert_invariant();
  16492. }
  16493. // operator[] only works for arrays
  16494. if (JSON_HEDLEY_LIKELY(is_array()))
  16495. {
  16496. // fill up array with null values if given idx is outside range
  16497. if (idx >= m_value.array->size())
  16498. {
  16499. m_value.array->insert(m_value.array->end(),
  16500. idx - m_value.array->size() + 1,
  16501. basic_json());
  16502. }
  16503. return m_value.array->operator[](idx);
  16504. }
  16505. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16506. }
  16507. /*!
  16508. @brief access specified array element
  16509. Returns a const reference to the element at specified location @a idx.
  16510. @param[in] idx index of the element to access
  16511. @return const reference to the element at index @a idx
  16512. @throw type_error.305 if the JSON value is not an array; in that case,
  16513. using the [] operator with an index makes no sense.
  16514. @complexity Constant.
  16515. @liveexample{The example below shows how array elements can be read using
  16516. the `[]` operator.,operatorarray__size_type_const}
  16517. @since version 1.0.0
  16518. */
  16519. const_reference operator[](size_type idx) const
  16520. {
  16521. // const operator[] only works for arrays
  16522. if (JSON_HEDLEY_LIKELY(is_array()))
  16523. {
  16524. return m_value.array->operator[](idx);
  16525. }
  16526. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16527. }
  16528. /*!
  16529. @brief access specified object element
  16530. Returns a reference to the element at with specified key @a key.
  16531. @note If @a key is not found in the object, then it is silently added to
  16532. the object and filled with a `null` value to make `key` a valid reference.
  16533. In case the value was `null` before, it is converted to an object.
  16534. @param[in] key key of the element to access
  16535. @return reference to the element at key @a key
  16536. @throw type_error.305 if the JSON value is not an object or null; in that
  16537. cases, using the [] operator with a key makes no sense.
  16538. @complexity Logarithmic in the size of the container.
  16539. @liveexample{The example below shows how object elements can be read and
  16540. written using the `[]` operator.,operatorarray__key_type}
  16541. @sa @ref at(const typename object_t::key_type&) for access by reference
  16542. with range checking
  16543. @sa @ref value() for access by value with a default value
  16544. @since version 1.0.0
  16545. */
  16546. reference operator[](const typename object_t::key_type& key)
  16547. {
  16548. // implicitly convert null value to an empty object
  16549. if (is_null())
  16550. {
  16551. m_type = value_t::object;
  16552. m_value.object = create<object_t>();
  16553. assert_invariant();
  16554. }
  16555. // operator[] only works for objects
  16556. if (JSON_HEDLEY_LIKELY(is_object()))
  16557. {
  16558. return m_value.object->operator[](key);
  16559. }
  16560. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16561. }
  16562. /*!
  16563. @brief read-only access specified object element
  16564. Returns a const reference to the element at with specified key @a key. No
  16565. bounds checking is performed.
  16566. @warning If the element with key @a key does not exist, the behavior is
  16567. undefined.
  16568. @param[in] key key of the element to access
  16569. @return const reference to the element at key @a key
  16570. @pre The element with key @a key must exist. **This precondition is
  16571. enforced with an assertion.**
  16572. @throw type_error.305 if the JSON value is not an object; in that case,
  16573. using the [] operator with a key makes no sense.
  16574. @complexity Logarithmic in the size of the container.
  16575. @liveexample{The example below shows how object elements can be read using
  16576. the `[]` operator.,operatorarray__key_type_const}
  16577. @sa @ref at(const typename object_t::key_type&) for access by reference
  16578. with range checking
  16579. @sa @ref value() for access by value with a default value
  16580. @since version 1.0.0
  16581. */
  16582. const_reference operator[](const typename object_t::key_type& key) const
  16583. {
  16584. // const operator[] only works for objects
  16585. if (JSON_HEDLEY_LIKELY(is_object()))
  16586. {
  16587. assert(m_value.object->find(key) != m_value.object->end());
  16588. return m_value.object->find(key)->second;
  16589. }
  16590. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16591. }
  16592. /*!
  16593. @brief access specified object element
  16594. Returns a reference to the element at with specified key @a key.
  16595. @note If @a key is not found in the object, then it is silently added to
  16596. the object and filled with a `null` value to make `key` a valid reference.
  16597. In case the value was `null` before, it is converted to an object.
  16598. @param[in] key key of the element to access
  16599. @return reference to the element at key @a key
  16600. @throw type_error.305 if the JSON value is not an object or null; in that
  16601. cases, using the [] operator with a key makes no sense.
  16602. @complexity Logarithmic in the size of the container.
  16603. @liveexample{The example below shows how object elements can be read and
  16604. written using the `[]` operator.,operatorarray__key_type}
  16605. @sa @ref at(const typename object_t::key_type&) for access by reference
  16606. with range checking
  16607. @sa @ref value() for access by value with a default value
  16608. @since version 1.1.0
  16609. */
  16610. template<typename T>
  16611. JSON_HEDLEY_NON_NULL(2)
  16612. reference operator[](T* key)
  16613. {
  16614. // implicitly convert null to object
  16615. if (is_null())
  16616. {
  16617. m_type = value_t::object;
  16618. m_value = value_t::object;
  16619. assert_invariant();
  16620. }
  16621. // at only works for objects
  16622. if (JSON_HEDLEY_LIKELY(is_object()))
  16623. {
  16624. return m_value.object->operator[](key);
  16625. }
  16626. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16627. }
  16628. /*!
  16629. @brief read-only access specified object element
  16630. Returns a const reference to the element at with specified key @a key. No
  16631. bounds checking is performed.
  16632. @warning If the element with key @a key does not exist, the behavior is
  16633. undefined.
  16634. @param[in] key key of the element to access
  16635. @return const reference to the element at key @a key
  16636. @pre The element with key @a key must exist. **This precondition is
  16637. enforced with an assertion.**
  16638. @throw type_error.305 if the JSON value is not an object; in that case,
  16639. using the [] operator with a key makes no sense.
  16640. @complexity Logarithmic in the size of the container.
  16641. @liveexample{The example below shows how object elements can be read using
  16642. the `[]` operator.,operatorarray__key_type_const}
  16643. @sa @ref at(const typename object_t::key_type&) for access by reference
  16644. with range checking
  16645. @sa @ref value() for access by value with a default value
  16646. @since version 1.1.0
  16647. */
  16648. template<typename T>
  16649. JSON_HEDLEY_NON_NULL(2)
  16650. const_reference operator[](T* key) const
  16651. {
  16652. // at only works for objects
  16653. if (JSON_HEDLEY_LIKELY(is_object()))
  16654. {
  16655. assert(m_value.object->find(key) != m_value.object->end());
  16656. return m_value.object->find(key)->second;
  16657. }
  16658. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16659. }
  16660. /*!
  16661. @brief access specified object element with default value
  16662. Returns either a copy of an object's element at the specified key @a key
  16663. or a given default value if no element with key @a key exists.
  16664. The function is basically equivalent to executing
  16665. @code {.cpp}
  16666. try {
  16667. return at(key);
  16668. } catch(out_of_range) {
  16669. return default_value;
  16670. }
  16671. @endcode
  16672. @note Unlike @ref at(const typename object_t::key_type&), this function
  16673. does not throw if the given key @a key was not found.
  16674. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  16675. function does not implicitly add an element to the position defined by @a
  16676. key. This function is furthermore also applicable to const objects.
  16677. @param[in] key key of the element to access
  16678. @param[in] default_value the value to return if @a key is not found
  16679. @tparam ValueType type compatible to JSON values, for instance `int` for
  16680. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16681. JSON arrays. Note the type of the expected value at @a key and the default
  16682. value @a default_value must be compatible.
  16683. @return copy of the element at key @a key or @a default_value if @a key
  16684. is not found
  16685. @throw type_error.302 if @a default_value does not match the type of the
  16686. value at @a key
  16687. @throw type_error.306 if the JSON value is not an object; in that case,
  16688. using `value()` with a key makes no sense.
  16689. @complexity Logarithmic in the size of the container.
  16690. @liveexample{The example below shows how object elements can be queried
  16691. with a default value.,basic_json__value}
  16692. @sa @ref at(const typename object_t::key_type&) for access by reference
  16693. with range checking
  16694. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16695. access by reference
  16696. @since version 1.0.0
  16697. */
  16698. template<class ValueType, typename std::enable_if<
  16699. std::is_convertible<basic_json_t, ValueType>::value
  16700. and not std::is_same<value_t, ValueType>::value, int>::type = 0>
  16701. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  16702. {
  16703. // at only works for objects
  16704. if (JSON_HEDLEY_LIKELY(is_object()))
  16705. {
  16706. // if key is found, return value and given default value otherwise
  16707. const auto it = find(key);
  16708. if (it != end())
  16709. {
  16710. return *it;
  16711. }
  16712. return default_value;
  16713. }
  16714. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16715. }
  16716. /*!
  16717. @brief overload for a default value of type const char*
  16718. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  16719. */
  16720. string_t value(const typename object_t::key_type& key, const char* default_value) const
  16721. {
  16722. return value(key, string_t(default_value));
  16723. }
  16724. /*!
  16725. @brief access specified object element via JSON Pointer with default value
  16726. Returns either a copy of an object's element at the specified key @a key
  16727. or a given default value if no element with key @a key exists.
  16728. The function is basically equivalent to executing
  16729. @code {.cpp}
  16730. try {
  16731. return at(ptr);
  16732. } catch(out_of_range) {
  16733. return default_value;
  16734. }
  16735. @endcode
  16736. @note Unlike @ref at(const json_pointer&), this function does not throw
  16737. if the given key @a key was not found.
  16738. @param[in] ptr a JSON pointer to the element to access
  16739. @param[in] default_value the value to return if @a ptr found no value
  16740. @tparam ValueType type compatible to JSON values, for instance `int` for
  16741. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16742. JSON arrays. Note the type of the expected value at @a key and the default
  16743. value @a default_value must be compatible.
  16744. @return copy of the element at key @a key or @a default_value if @a key
  16745. is not found
  16746. @throw type_error.302 if @a default_value does not match the type of the
  16747. value at @a ptr
  16748. @throw type_error.306 if the JSON value is not an object; in that case,
  16749. using `value()` with a key makes no sense.
  16750. @complexity Logarithmic in the size of the container.
  16751. @liveexample{The example below shows how object elements can be queried
  16752. with a default value.,basic_json__value_ptr}
  16753. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  16754. @since version 2.0.2
  16755. */
  16756. template<class ValueType, typename std::enable_if<
  16757. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  16758. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  16759. {
  16760. // at only works for objects
  16761. if (JSON_HEDLEY_LIKELY(is_object()))
  16762. {
  16763. // if pointer resolves a value, return it or use default value
  16764. JSON_TRY
  16765. {
  16766. return ptr.get_checked(this);
  16767. }
  16768. JSON_INTERNAL_CATCH (out_of_range&)
  16769. {
  16770. return default_value;
  16771. }
  16772. }
  16773. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16774. }
  16775. /*!
  16776. @brief overload for a default value of type const char*
  16777. @copydoc basic_json::value(const json_pointer&, ValueType) const
  16778. */
  16779. JSON_HEDLEY_NON_NULL(3)
  16780. string_t value(const json_pointer& ptr, const char* default_value) const
  16781. {
  16782. return value(ptr, string_t(default_value));
  16783. }
  16784. /*!
  16785. @brief access the first element
  16786. Returns a reference to the first element in the container. For a JSON
  16787. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  16788. @return In case of a structured type (array or object), a reference to the
  16789. first element is returned. In case of number, string, boolean, or binary
  16790. values, a reference to the value is returned.
  16791. @complexity Constant.
  16792. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16793. or an empty array or object (undefined behavior, **guarded by
  16794. assertions**).
  16795. @post The JSON value remains unchanged.
  16796. @throw invalid_iterator.214 when called on `null` value
  16797. @liveexample{The following code shows an example for `front()`.,front}
  16798. @sa @ref back() -- access the last element
  16799. @since version 1.0.0
  16800. */
  16801. reference front()
  16802. {
  16803. return *begin();
  16804. }
  16805. /*!
  16806. @copydoc basic_json::front()
  16807. */
  16808. const_reference front() const
  16809. {
  16810. return *cbegin();
  16811. }
  16812. /*!
  16813. @brief access the last element
  16814. Returns a reference to the last element in the container. For a JSON
  16815. container `c`, the expression `c.back()` is equivalent to
  16816. @code {.cpp}
  16817. auto tmp = c.end();
  16818. --tmp;
  16819. return *tmp;
  16820. @endcode
  16821. @return In case of a structured type (array or object), a reference to the
  16822. last element is returned. In case of number, string, boolean, or binary
  16823. values, a reference to the value is returned.
  16824. @complexity Constant.
  16825. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16826. or an empty array or object (undefined behavior, **guarded by
  16827. assertions**).
  16828. @post The JSON value remains unchanged.
  16829. @throw invalid_iterator.214 when called on a `null` value. See example
  16830. below.
  16831. @liveexample{The following code shows an example for `back()`.,back}
  16832. @sa @ref front() -- access the first element
  16833. @since version 1.0.0
  16834. */
  16835. reference back()
  16836. {
  16837. auto tmp = end();
  16838. --tmp;
  16839. return *tmp;
  16840. }
  16841. /*!
  16842. @copydoc basic_json::back()
  16843. */
  16844. const_reference back() const
  16845. {
  16846. auto tmp = cend();
  16847. --tmp;
  16848. return *tmp;
  16849. }
  16850. /*!
  16851. @brief remove element given an iterator
  16852. Removes the element specified by iterator @a pos. The iterator @a pos must
  16853. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  16854. but is not dereferenceable) cannot be used as a value for @a pos.
  16855. If called on a primitive type other than `null`, the resulting JSON value
  16856. will be `null`.
  16857. @param[in] pos iterator to the element to remove
  16858. @return Iterator following the last removed element. If the iterator @a
  16859. pos refers to the last element, the `end()` iterator is returned.
  16860. @tparam IteratorType an @ref iterator or @ref const_iterator
  16861. @post Invalidates iterators and references at or after the point of the
  16862. erase, including the `end()` iterator.
  16863. @throw type_error.307 if called on a `null` value; example: `"cannot use
  16864. erase() with null"`
  16865. @throw invalid_iterator.202 if called on an iterator which does not belong
  16866. to the current JSON value; example: `"iterator does not fit current
  16867. value"`
  16868. @throw invalid_iterator.205 if called on a primitive type with invalid
  16869. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  16870. out of range"`
  16871. @complexity The complexity depends on the type:
  16872. - objects: amortized constant
  16873. - arrays: linear in distance between @a pos and the end of the container
  16874. - strings and binary: linear in the length of the member
  16875. - other types: constant
  16876. @liveexample{The example shows the result of `erase()` for different JSON
  16877. types.,erase__IteratorType}
  16878. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  16879. the given range
  16880. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16881. from an object at the given key
  16882. @sa @ref erase(const size_type) -- removes the element from an array at
  16883. the given index
  16884. @since version 1.0.0
  16885. */
  16886. template<class IteratorType, typename std::enable_if<
  16887. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  16888. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  16889. = 0>
  16890. IteratorType erase(IteratorType pos)
  16891. {
  16892. // make sure iterator fits the current value
  16893. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  16894. {
  16895. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16896. }
  16897. IteratorType result = end();
  16898. switch (m_type)
  16899. {
  16900. case value_t::boolean:
  16901. case value_t::number_float:
  16902. case value_t::number_integer:
  16903. case value_t::number_unsigned:
  16904. case value_t::string:
  16905. case value_t::binary:
  16906. {
  16907. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  16908. {
  16909. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  16910. }
  16911. if (is_string())
  16912. {
  16913. AllocatorType<string_t> alloc;
  16914. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  16915. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  16916. m_value.string = nullptr;
  16917. }
  16918. else if (is_binary())
  16919. {
  16920. AllocatorType<binary_t> alloc;
  16921. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  16922. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  16923. m_value.binary = nullptr;
  16924. }
  16925. m_type = value_t::null;
  16926. assert_invariant();
  16927. break;
  16928. }
  16929. case value_t::object:
  16930. {
  16931. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  16932. break;
  16933. }
  16934. case value_t::array:
  16935. {
  16936. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  16937. break;
  16938. }
  16939. default:
  16940. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  16941. }
  16942. return result;
  16943. }
  16944. /*!
  16945. @brief remove elements given an iterator range
  16946. Removes the element specified by the range `[first; last)`. The iterator
  16947. @a first does not need to be dereferenceable if `first == last`: erasing
  16948. an empty range is a no-op.
  16949. If called on a primitive type other than `null`, the resulting JSON value
  16950. will be `null`.
  16951. @param[in] first iterator to the beginning of the range to remove
  16952. @param[in] last iterator past the end of the range to remove
  16953. @return Iterator following the last removed element. If the iterator @a
  16954. second refers to the last element, the `end()` iterator is returned.
  16955. @tparam IteratorType an @ref iterator or @ref const_iterator
  16956. @post Invalidates iterators and references at or after the point of the
  16957. erase, including the `end()` iterator.
  16958. @throw type_error.307 if called on a `null` value; example: `"cannot use
  16959. erase() with null"`
  16960. @throw invalid_iterator.203 if called on iterators which does not belong
  16961. to the current JSON value; example: `"iterators do not fit current value"`
  16962. @throw invalid_iterator.204 if called on a primitive type with invalid
  16963. iterators (i.e., if `first != begin()` and `last != end()`); example:
  16964. `"iterators out of range"`
  16965. @complexity The complexity depends on the type:
  16966. - objects: `log(size()) + std::distance(first, last)`
  16967. - arrays: linear in the distance between @a first and @a last, plus linear
  16968. in the distance between @a last and end of the container
  16969. - strings and binary: linear in the length of the member
  16970. - other types: constant
  16971. @liveexample{The example shows the result of `erase()` for different JSON
  16972. types.,erase__IteratorType_IteratorType}
  16973. @sa @ref erase(IteratorType) -- removes the element at a given position
  16974. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  16975. from an object at the given key
  16976. @sa @ref erase(const size_type) -- removes the element from an array at
  16977. the given index
  16978. @since version 1.0.0
  16979. */
  16980. template<class IteratorType, typename std::enable_if<
  16981. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  16982. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  16983. = 0>
  16984. IteratorType erase(IteratorType first, IteratorType last)
  16985. {
  16986. // make sure iterator fits the current value
  16987. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  16988. {
  16989. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  16990. }
  16991. IteratorType result = end();
  16992. switch (m_type)
  16993. {
  16994. case value_t::boolean:
  16995. case value_t::number_float:
  16996. case value_t::number_integer:
  16997. case value_t::number_unsigned:
  16998. case value_t::string:
  16999. case value_t::binary:
  17000. {
  17001. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  17002. or not last.m_it.primitive_iterator.is_end()))
  17003. {
  17004. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  17005. }
  17006. if (is_string())
  17007. {
  17008. AllocatorType<string_t> alloc;
  17009. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  17010. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  17011. m_value.string = nullptr;
  17012. }
  17013. else if (is_binary())
  17014. {
  17015. AllocatorType<binary_t> alloc;
  17016. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  17017. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  17018. m_value.binary = nullptr;
  17019. }
  17020. m_type = value_t::null;
  17021. assert_invariant();
  17022. break;
  17023. }
  17024. case value_t::object:
  17025. {
  17026. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  17027. last.m_it.object_iterator);
  17028. break;
  17029. }
  17030. case value_t::array:
  17031. {
  17032. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  17033. last.m_it.array_iterator);
  17034. break;
  17035. }
  17036. default:
  17037. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17038. }
  17039. return result;
  17040. }
  17041. /*!
  17042. @brief remove element from a JSON object given a key
  17043. Removes elements from a JSON object with the key value @a key.
  17044. @param[in] key value of the elements to remove
  17045. @return Number of elements removed. If @a ObjectType is the default
  17046. `std::map` type, the return value will always be `0` (@a key was not
  17047. found) or `1` (@a key was found).
  17048. @post References and iterators to the erased elements are invalidated.
  17049. Other references and iterators are not affected.
  17050. @throw type_error.307 when called on a type other than JSON object;
  17051. example: `"cannot use erase() with null"`
  17052. @complexity `log(size()) + count(key)`
  17053. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  17054. @sa @ref erase(IteratorType) -- removes the element at a given position
  17055. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17056. the given range
  17057. @sa @ref erase(const size_type) -- removes the element from an array at
  17058. the given index
  17059. @since version 1.0.0
  17060. */
  17061. size_type erase(const typename object_t::key_type& key)
  17062. {
  17063. // this erase only works for objects
  17064. if (JSON_HEDLEY_LIKELY(is_object()))
  17065. {
  17066. return m_value.object->erase(key);
  17067. }
  17068. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17069. }
  17070. /*!
  17071. @brief remove element from a JSON array given an index
  17072. Removes element from a JSON array at the index @a idx.
  17073. @param[in] idx index of the element to remove
  17074. @throw type_error.307 when called on a type other than JSON object;
  17075. example: `"cannot use erase() with null"`
  17076. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  17077. is out of range"`
  17078. @complexity Linear in distance between @a idx and the end of the container.
  17079. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  17080. @sa @ref erase(IteratorType) -- removes the element at a given position
  17081. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17082. the given range
  17083. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17084. from an object at the given key
  17085. @since version 1.0.0
  17086. */
  17087. void erase(const size_type idx)
  17088. {
  17089. // this erase only works for arrays
  17090. if (JSON_HEDLEY_LIKELY(is_array()))
  17091. {
  17092. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  17093. {
  17094. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  17095. }
  17096. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  17097. }
  17098. else
  17099. {
  17100. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17101. }
  17102. }
  17103. /// @}
  17104. ////////////
  17105. // lookup //
  17106. ////////////
  17107. /// @name lookup
  17108. /// @{
  17109. /*!
  17110. @brief find an element in a JSON object
  17111. Finds an element in a JSON object with key equivalent to @a key. If the
  17112. element is not found or the JSON value is not an object, end() is
  17113. returned.
  17114. @note This method always returns @ref end() when executed on a JSON type
  17115. that is not an object.
  17116. @param[in] key key value of the element to search for.
  17117. @return Iterator to an element with key equivalent to @a key. If no such
  17118. element is found or the JSON value is not an object, past-the-end (see
  17119. @ref end()) iterator is returned.
  17120. @complexity Logarithmic in the size of the JSON object.
  17121. @liveexample{The example shows how `find()` is used.,find__key_type}
  17122. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  17123. @since version 1.0.0
  17124. */
  17125. template<typename KeyT>
  17126. iterator find(KeyT&& key)
  17127. {
  17128. auto result = end();
  17129. if (is_object())
  17130. {
  17131. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17132. }
  17133. return result;
  17134. }
  17135. /*!
  17136. @brief find an element in a JSON object
  17137. @copydoc find(KeyT&&)
  17138. */
  17139. template<typename KeyT>
  17140. const_iterator find(KeyT&& key) const
  17141. {
  17142. auto result = cend();
  17143. if (is_object())
  17144. {
  17145. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17146. }
  17147. return result;
  17148. }
  17149. /*!
  17150. @brief returns the number of occurrences of a key in a JSON object
  17151. Returns the number of elements with key @a key. If ObjectType is the
  17152. default `std::map` type, the return value will always be `0` (@a key was
  17153. not found) or `1` (@a key was found).
  17154. @note This method always returns `0` when executed on a JSON type that is
  17155. not an object.
  17156. @param[in] key key value of the element to count
  17157. @return Number of elements with key @a key. If the JSON value is not an
  17158. object, the return value will be `0`.
  17159. @complexity Logarithmic in the size of the JSON object.
  17160. @liveexample{The example shows how `count()` is used.,count}
  17161. @since version 1.0.0
  17162. */
  17163. template<typename KeyT>
  17164. size_type count(KeyT&& key) const
  17165. {
  17166. // return 0 for all nonobject types
  17167. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  17168. }
  17169. /*!
  17170. @brief check the existence of an element in a JSON object
  17171. Check whether an element exists in a JSON object with key equivalent to
  17172. @a key. If the element is not found or the JSON value is not an object,
  17173. false is returned.
  17174. @note This method always returns false when executed on a JSON type
  17175. that is not an object.
  17176. @param[in] key key value to check its existence.
  17177. @return true if an element with specified @a key exists. If no such
  17178. element with such key is found or the JSON value is not an object,
  17179. false is returned.
  17180. @complexity Logarithmic in the size of the JSON object.
  17181. @liveexample{The following code shows an example for `contains()`.,contains}
  17182. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  17183. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  17184. @since version 3.6.0
  17185. */
  17186. template<typename KeyT, typename std::enable_if<
  17187. not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
  17188. bool contains(KeyT && key) const
  17189. {
  17190. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  17191. }
  17192. /*!
  17193. @brief check the existence of an element in a JSON object given a JSON pointer
  17194. Check whether the given JSON pointer @a ptr can be resolved in the current
  17195. JSON value.
  17196. @note This method can be executed on any JSON value type.
  17197. @param[in] ptr JSON pointer to check its existence.
  17198. @return true if the JSON pointer can be resolved to a stored value, false
  17199. otherwise.
  17200. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  17201. @throw parse_error.106 if an array index begins with '0'
  17202. @throw parse_error.109 if an array index was not a number
  17203. @complexity Logarithmic in the size of the JSON object.
  17204. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  17205. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  17206. @since version 3.7.0
  17207. */
  17208. bool contains(const json_pointer& ptr) const
  17209. {
  17210. return ptr.contains(this);
  17211. }
  17212. /// @}
  17213. ///////////////
  17214. // iterators //
  17215. ///////////////
  17216. /// @name iterators
  17217. /// @{
  17218. /*!
  17219. @brief returns an iterator to the first element
  17220. Returns an iterator to the first element.
  17221. @image html range-begin-end.svg "Illustration from cppreference.com"
  17222. @return iterator to the first element
  17223. @complexity Constant.
  17224. @requirement This function helps `basic_json` satisfying the
  17225. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17226. requirements:
  17227. - The complexity is constant.
  17228. @liveexample{The following code shows an example for `begin()`.,begin}
  17229. @sa @ref cbegin() -- returns a const iterator to the beginning
  17230. @sa @ref end() -- returns an iterator to the end
  17231. @sa @ref cend() -- returns a const iterator to the end
  17232. @since version 1.0.0
  17233. */
  17234. iterator begin() noexcept
  17235. {
  17236. iterator result(this);
  17237. result.set_begin();
  17238. return result;
  17239. }
  17240. /*!
  17241. @copydoc basic_json::cbegin()
  17242. */
  17243. const_iterator begin() const noexcept
  17244. {
  17245. return cbegin();
  17246. }
  17247. /*!
  17248. @brief returns a const iterator to the first element
  17249. Returns a const iterator to the first element.
  17250. @image html range-begin-end.svg "Illustration from cppreference.com"
  17251. @return const iterator to the first element
  17252. @complexity Constant.
  17253. @requirement This function helps `basic_json` satisfying the
  17254. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17255. requirements:
  17256. - The complexity is constant.
  17257. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  17258. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  17259. @sa @ref begin() -- returns an iterator to the beginning
  17260. @sa @ref end() -- returns an iterator to the end
  17261. @sa @ref cend() -- returns a const iterator to the end
  17262. @since version 1.0.0
  17263. */
  17264. const_iterator cbegin() const noexcept
  17265. {
  17266. const_iterator result(this);
  17267. result.set_begin();
  17268. return result;
  17269. }
  17270. /*!
  17271. @brief returns an iterator to one past the last element
  17272. Returns an iterator to one past the last element.
  17273. @image html range-begin-end.svg "Illustration from cppreference.com"
  17274. @return iterator one past the last element
  17275. @complexity Constant.
  17276. @requirement This function helps `basic_json` satisfying the
  17277. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17278. requirements:
  17279. - The complexity is constant.
  17280. @liveexample{The following code shows an example for `end()`.,end}
  17281. @sa @ref cend() -- returns a const iterator to the end
  17282. @sa @ref begin() -- returns an iterator to the beginning
  17283. @sa @ref cbegin() -- returns a const iterator to the beginning
  17284. @since version 1.0.0
  17285. */
  17286. iterator end() noexcept
  17287. {
  17288. iterator result(this);
  17289. result.set_end();
  17290. return result;
  17291. }
  17292. /*!
  17293. @copydoc basic_json::cend()
  17294. */
  17295. const_iterator end() const noexcept
  17296. {
  17297. return cend();
  17298. }
  17299. /*!
  17300. @brief returns a const iterator to one past the last element
  17301. Returns a const iterator to one past the last element.
  17302. @image html range-begin-end.svg "Illustration from cppreference.com"
  17303. @return const iterator one past the last element
  17304. @complexity Constant.
  17305. @requirement This function helps `basic_json` satisfying the
  17306. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17307. requirements:
  17308. - The complexity is constant.
  17309. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  17310. @liveexample{The following code shows an example for `cend()`.,cend}
  17311. @sa @ref end() -- returns an iterator to the end
  17312. @sa @ref begin() -- returns an iterator to the beginning
  17313. @sa @ref cbegin() -- returns a const iterator to the beginning
  17314. @since version 1.0.0
  17315. */
  17316. const_iterator cend() const noexcept
  17317. {
  17318. const_iterator result(this);
  17319. result.set_end();
  17320. return result;
  17321. }
  17322. /*!
  17323. @brief returns an iterator to the reverse-beginning
  17324. Returns an iterator to the reverse-beginning; that is, the last element.
  17325. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17326. @complexity Constant.
  17327. @requirement This function helps `basic_json` satisfying the
  17328. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17329. requirements:
  17330. - The complexity is constant.
  17331. - Has the semantics of `reverse_iterator(end())`.
  17332. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  17333. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17334. @sa @ref rend() -- returns a reverse iterator to the end
  17335. @sa @ref crend() -- returns a const reverse iterator to the end
  17336. @since version 1.0.0
  17337. */
  17338. reverse_iterator rbegin() noexcept
  17339. {
  17340. return reverse_iterator(end());
  17341. }
  17342. /*!
  17343. @copydoc basic_json::crbegin()
  17344. */
  17345. const_reverse_iterator rbegin() const noexcept
  17346. {
  17347. return crbegin();
  17348. }
  17349. /*!
  17350. @brief returns an iterator to the reverse-end
  17351. Returns an iterator to the reverse-end; that is, one before the first
  17352. element.
  17353. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17354. @complexity Constant.
  17355. @requirement This function helps `basic_json` satisfying the
  17356. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17357. requirements:
  17358. - The complexity is constant.
  17359. - Has the semantics of `reverse_iterator(begin())`.
  17360. @liveexample{The following code shows an example for `rend()`.,rend}
  17361. @sa @ref crend() -- returns a const reverse iterator to the end
  17362. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17363. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17364. @since version 1.0.0
  17365. */
  17366. reverse_iterator rend() noexcept
  17367. {
  17368. return reverse_iterator(begin());
  17369. }
  17370. /*!
  17371. @copydoc basic_json::crend()
  17372. */
  17373. const_reverse_iterator rend() const noexcept
  17374. {
  17375. return crend();
  17376. }
  17377. /*!
  17378. @brief returns a const reverse iterator to the last element
  17379. Returns a const iterator to the reverse-beginning; that is, the last
  17380. element.
  17381. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17382. @complexity Constant.
  17383. @requirement This function helps `basic_json` satisfying the
  17384. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17385. requirements:
  17386. - The complexity is constant.
  17387. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  17388. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  17389. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17390. @sa @ref rend() -- returns a reverse iterator to the end
  17391. @sa @ref crend() -- returns a const reverse iterator to the end
  17392. @since version 1.0.0
  17393. */
  17394. const_reverse_iterator crbegin() const noexcept
  17395. {
  17396. return const_reverse_iterator(cend());
  17397. }
  17398. /*!
  17399. @brief returns a const reverse iterator to one before the first
  17400. Returns a const reverse iterator to the reverse-end; that is, one before
  17401. the first element.
  17402. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17403. @complexity Constant.
  17404. @requirement This function helps `basic_json` satisfying the
  17405. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17406. requirements:
  17407. - The complexity is constant.
  17408. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  17409. @liveexample{The following code shows an example for `crend()`.,crend}
  17410. @sa @ref rend() -- returns a reverse iterator to the end
  17411. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17412. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17413. @since version 1.0.0
  17414. */
  17415. const_reverse_iterator crend() const noexcept
  17416. {
  17417. return const_reverse_iterator(cbegin());
  17418. }
  17419. public:
  17420. /*!
  17421. @brief wrapper to access iterator member functions in range-based for
  17422. This function allows to access @ref iterator::key() and @ref
  17423. iterator::value() during range-based for loops. In these loops, a
  17424. reference to the JSON values is returned, so there is no access to the
  17425. underlying iterator.
  17426. For loop without iterator_wrapper:
  17427. @code{cpp}
  17428. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17429. {
  17430. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17431. }
  17432. @endcode
  17433. Range-based for loop without iterator proxy:
  17434. @code{cpp}
  17435. for (auto it : j_object)
  17436. {
  17437. // "it" is of type json::reference and has no key() member
  17438. std::cout << "value: " << it << '\n';
  17439. }
  17440. @endcode
  17441. Range-based for loop with iterator proxy:
  17442. @code{cpp}
  17443. for (auto it : json::iterator_wrapper(j_object))
  17444. {
  17445. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17446. }
  17447. @endcode
  17448. @note When iterating over an array, `key()` will return the index of the
  17449. element as string (see example).
  17450. @param[in] ref reference to a JSON value
  17451. @return iteration proxy object wrapping @a ref with an interface to use in
  17452. range-based for loops
  17453. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  17454. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17455. changes in the JSON value.
  17456. @complexity Constant.
  17457. @note The name of this function is not yet final and may change in the
  17458. future.
  17459. @deprecated This stream operator is deprecated and will be removed in
  17460. future 4.0.0 of the library. Please use @ref items() instead;
  17461. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  17462. */
  17463. JSON_HEDLEY_DEPRECATED(3.1.0)
  17464. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  17465. {
  17466. return ref.items();
  17467. }
  17468. /*!
  17469. @copydoc iterator_wrapper(reference)
  17470. */
  17471. JSON_HEDLEY_DEPRECATED(3.1.0)
  17472. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  17473. {
  17474. return ref.items();
  17475. }
  17476. /*!
  17477. @brief helper to access iterator member functions in range-based for
  17478. This function allows to access @ref iterator::key() and @ref
  17479. iterator::value() during range-based for loops. In these loops, a
  17480. reference to the JSON values is returned, so there is no access to the
  17481. underlying iterator.
  17482. For loop without `items()` function:
  17483. @code{cpp}
  17484. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17485. {
  17486. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17487. }
  17488. @endcode
  17489. Range-based for loop without `items()` function:
  17490. @code{cpp}
  17491. for (auto it : j_object)
  17492. {
  17493. // "it" is of type json::reference and has no key() member
  17494. std::cout << "value: " << it << '\n';
  17495. }
  17496. @endcode
  17497. Range-based for loop with `items()` function:
  17498. @code{cpp}
  17499. for (auto& el : j_object.items())
  17500. {
  17501. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  17502. }
  17503. @endcode
  17504. The `items()` function also allows to use
  17505. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  17506. (C++17):
  17507. @code{cpp}
  17508. for (auto& [key, val] : j_object.items())
  17509. {
  17510. std::cout << "key: " << key << ", value:" << val << '\n';
  17511. }
  17512. @endcode
  17513. @note When iterating over an array, `key()` will return the index of the
  17514. element as string (see example). For primitive types (e.g., numbers),
  17515. `key()` returns an empty string.
  17516. @warning Using `items()` on temporary objects is dangerous. Make sure the
  17517. object's lifetime exeeds the iteration. See
  17518. <https://github.com/nlohmann/json/issues/2040> for more
  17519. information.
  17520. @return iteration proxy object wrapping @a ref with an interface to use in
  17521. range-based for loops
  17522. @liveexample{The following code shows how the function is used.,items}
  17523. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17524. changes in the JSON value.
  17525. @complexity Constant.
  17526. @since version 3.1.0, structured bindings support since 3.5.0.
  17527. */
  17528. iteration_proxy<iterator> items() noexcept
  17529. {
  17530. return iteration_proxy<iterator>(*this);
  17531. }
  17532. /*!
  17533. @copydoc items()
  17534. */
  17535. iteration_proxy<const_iterator> items() const noexcept
  17536. {
  17537. return iteration_proxy<const_iterator>(*this);
  17538. }
  17539. /// @}
  17540. //////////////
  17541. // capacity //
  17542. //////////////
  17543. /// @name capacity
  17544. /// @{
  17545. /*!
  17546. @brief checks whether the container is empty.
  17547. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  17548. @return The return value depends on the different types and is
  17549. defined as follows:
  17550. Value type | return value
  17551. ----------- | -------------
  17552. null | `true`
  17553. boolean | `false`
  17554. string | `false`
  17555. number | `false`
  17556. binary | `false`
  17557. object | result of function `object_t::empty()`
  17558. array | result of function `array_t::empty()`
  17559. @liveexample{The following code uses `empty()` to check if a JSON
  17560. object contains any elements.,empty}
  17561. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17562. the Container concept; that is, their `empty()` functions have constant
  17563. complexity.
  17564. @iterators No changes.
  17565. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17566. @note This function does not return whether a string stored as JSON value
  17567. is empty - it returns whether the JSON container itself is empty which is
  17568. false in the case of a string.
  17569. @requirement This function helps `basic_json` satisfying the
  17570. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17571. requirements:
  17572. - The complexity is constant.
  17573. - Has the semantics of `begin() == end()`.
  17574. @sa @ref size() -- returns the number of elements
  17575. @since version 1.0.0
  17576. */
  17577. bool empty() const noexcept
  17578. {
  17579. switch (m_type)
  17580. {
  17581. case value_t::null:
  17582. {
  17583. // null values are empty
  17584. return true;
  17585. }
  17586. case value_t::array:
  17587. {
  17588. // delegate call to array_t::empty()
  17589. return m_value.array->empty();
  17590. }
  17591. case value_t::object:
  17592. {
  17593. // delegate call to object_t::empty()
  17594. return m_value.object->empty();
  17595. }
  17596. default:
  17597. {
  17598. // all other types are nonempty
  17599. return false;
  17600. }
  17601. }
  17602. }
  17603. /*!
  17604. @brief returns the number of elements
  17605. Returns the number of elements in a JSON value.
  17606. @return The return value depends on the different types and is
  17607. defined as follows:
  17608. Value type | return value
  17609. ----------- | -------------
  17610. null | `0`
  17611. boolean | `1`
  17612. string | `1`
  17613. number | `1`
  17614. binary | `1`
  17615. object | result of function object_t::size()
  17616. array | result of function array_t::size()
  17617. @liveexample{The following code calls `size()` on the different value
  17618. types.,size}
  17619. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17620. the Container concept; that is, their size() functions have constant
  17621. complexity.
  17622. @iterators No changes.
  17623. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17624. @note This function does not return the length of a string stored as JSON
  17625. value - it returns the number of elements in the JSON value which is 1 in
  17626. the case of a string.
  17627. @requirement This function helps `basic_json` satisfying the
  17628. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17629. requirements:
  17630. - The complexity is constant.
  17631. - Has the semantics of `std::distance(begin(), end())`.
  17632. @sa @ref empty() -- checks whether the container is empty
  17633. @sa @ref max_size() -- returns the maximal number of elements
  17634. @since version 1.0.0
  17635. */
  17636. size_type size() const noexcept
  17637. {
  17638. switch (m_type)
  17639. {
  17640. case value_t::null:
  17641. {
  17642. // null values are empty
  17643. return 0;
  17644. }
  17645. case value_t::array:
  17646. {
  17647. // delegate call to array_t::size()
  17648. return m_value.array->size();
  17649. }
  17650. case value_t::object:
  17651. {
  17652. // delegate call to object_t::size()
  17653. return m_value.object->size();
  17654. }
  17655. default:
  17656. {
  17657. // all other types have size 1
  17658. return 1;
  17659. }
  17660. }
  17661. }
  17662. /*!
  17663. @brief returns the maximum possible number of elements
  17664. Returns the maximum number of elements a JSON value is able to hold due to
  17665. system or library implementation limitations, i.e. `std::distance(begin(),
  17666. end())` for the JSON value.
  17667. @return The return value depends on the different types and is
  17668. defined as follows:
  17669. Value type | return value
  17670. ----------- | -------------
  17671. null | `0` (same as `size()`)
  17672. boolean | `1` (same as `size()`)
  17673. string | `1` (same as `size()`)
  17674. number | `1` (same as `size()`)
  17675. binary | `1` (same as `size()`)
  17676. object | result of function `object_t::max_size()`
  17677. array | result of function `array_t::max_size()`
  17678. @liveexample{The following code calls `max_size()` on the different value
  17679. types. Note the output is implementation specific.,max_size}
  17680. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17681. the Container concept; that is, their `max_size()` functions have constant
  17682. complexity.
  17683. @iterators No changes.
  17684. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17685. @requirement This function helps `basic_json` satisfying the
  17686. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17687. requirements:
  17688. - The complexity is constant.
  17689. - Has the semantics of returning `b.size()` where `b` is the largest
  17690. possible JSON value.
  17691. @sa @ref size() -- returns the number of elements
  17692. @since version 1.0.0
  17693. */
  17694. size_type max_size() const noexcept
  17695. {
  17696. switch (m_type)
  17697. {
  17698. case value_t::array:
  17699. {
  17700. // delegate call to array_t::max_size()
  17701. return m_value.array->max_size();
  17702. }
  17703. case value_t::object:
  17704. {
  17705. // delegate call to object_t::max_size()
  17706. return m_value.object->max_size();
  17707. }
  17708. default:
  17709. {
  17710. // all other types have max_size() == size()
  17711. return size();
  17712. }
  17713. }
  17714. }
  17715. /// @}
  17716. ///////////////
  17717. // modifiers //
  17718. ///////////////
  17719. /// @name modifiers
  17720. /// @{
  17721. /*!
  17722. @brief clears the contents
  17723. Clears the content of a JSON value and resets it to the default value as
  17724. if @ref basic_json(value_t) would have been called with the current value
  17725. type from @ref type():
  17726. Value type | initial value
  17727. ----------- | -------------
  17728. null | `null`
  17729. boolean | `false`
  17730. string | `""`
  17731. number | `0`
  17732. binary | An empty byte vector
  17733. object | `{}`
  17734. array | `[]`
  17735. @post Has the same effect as calling
  17736. @code {.cpp}
  17737. *this = basic_json(type());
  17738. @endcode
  17739. @liveexample{The example below shows the effect of `clear()` to different
  17740. JSON types.,clear}
  17741. @complexity Linear in the size of the JSON value.
  17742. @iterators All iterators, pointers and references related to this container
  17743. are invalidated.
  17744. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17745. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  17746. same value than calling `clear()`
  17747. @since version 1.0.0
  17748. */
  17749. void clear() noexcept
  17750. {
  17751. switch (m_type)
  17752. {
  17753. case value_t::number_integer:
  17754. {
  17755. m_value.number_integer = 0;
  17756. break;
  17757. }
  17758. case value_t::number_unsigned:
  17759. {
  17760. m_value.number_unsigned = 0;
  17761. break;
  17762. }
  17763. case value_t::number_float:
  17764. {
  17765. m_value.number_float = 0.0;
  17766. break;
  17767. }
  17768. case value_t::boolean:
  17769. {
  17770. m_value.boolean = false;
  17771. break;
  17772. }
  17773. case value_t::string:
  17774. {
  17775. m_value.string->clear();
  17776. break;
  17777. }
  17778. case value_t::binary:
  17779. {
  17780. m_value.binary->clear();
  17781. break;
  17782. }
  17783. case value_t::array:
  17784. {
  17785. m_value.array->clear();
  17786. break;
  17787. }
  17788. case value_t::object:
  17789. {
  17790. m_value.object->clear();
  17791. break;
  17792. }
  17793. default:
  17794. break;
  17795. }
  17796. }
  17797. /*!
  17798. @brief add an object to an array
  17799. Appends the given element @a val to the end of the JSON value. If the
  17800. function is called on a JSON null value, an empty array is created before
  17801. appending @a val.
  17802. @param[in] val the value to add to the JSON array
  17803. @throw type_error.308 when called on a type other than JSON array or
  17804. null; example: `"cannot use push_back() with number"`
  17805. @complexity Amortized constant.
  17806. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17807. add elements to a JSON array. Note how the `null` value was silently
  17808. converted to a JSON array.,push_back}
  17809. @since version 1.0.0
  17810. */
  17811. void push_back(basic_json&& val)
  17812. {
  17813. // push_back only works for null objects or arrays
  17814. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17815. {
  17816. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17817. }
  17818. // transform null object into an array
  17819. if (is_null())
  17820. {
  17821. m_type = value_t::array;
  17822. m_value = value_t::array;
  17823. assert_invariant();
  17824. }
  17825. // add element to array (move semantics)
  17826. m_value.array->push_back(std::move(val));
  17827. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  17828. }
  17829. /*!
  17830. @brief add an object to an array
  17831. @copydoc push_back(basic_json&&)
  17832. */
  17833. reference operator+=(basic_json&& val)
  17834. {
  17835. push_back(std::move(val));
  17836. return *this;
  17837. }
  17838. /*!
  17839. @brief add an object to an array
  17840. @copydoc push_back(basic_json&&)
  17841. */
  17842. void push_back(const basic_json& val)
  17843. {
  17844. // push_back only works for null objects or arrays
  17845. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17846. {
  17847. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17848. }
  17849. // transform null object into an array
  17850. if (is_null())
  17851. {
  17852. m_type = value_t::array;
  17853. m_value = value_t::array;
  17854. assert_invariant();
  17855. }
  17856. // add element to array
  17857. m_value.array->push_back(val);
  17858. }
  17859. /*!
  17860. @brief add an object to an array
  17861. @copydoc push_back(basic_json&&)
  17862. */
  17863. reference operator+=(const basic_json& val)
  17864. {
  17865. push_back(val);
  17866. return *this;
  17867. }
  17868. /*!
  17869. @brief add an object to an object
  17870. Inserts the given element @a val to the JSON object. If the function is
  17871. called on a JSON null value, an empty object is created before inserting
  17872. @a val.
  17873. @param[in] val the value to add to the JSON object
  17874. @throw type_error.308 when called on a type other than JSON object or
  17875. null; example: `"cannot use push_back() with number"`
  17876. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  17877. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17878. add elements to a JSON object. Note how the `null` value was silently
  17879. converted to a JSON object.,push_back__object_t__value}
  17880. @since version 1.0.0
  17881. */
  17882. void push_back(const typename object_t::value_type& val)
  17883. {
  17884. // push_back only works for null objects or objects
  17885. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  17886. {
  17887. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  17888. }
  17889. // transform null object into an object
  17890. if (is_null())
  17891. {
  17892. m_type = value_t::object;
  17893. m_value = value_t::object;
  17894. assert_invariant();
  17895. }
  17896. // add element to array
  17897. m_value.object->insert(val);
  17898. }
  17899. /*!
  17900. @brief add an object to an object
  17901. @copydoc push_back(const typename object_t::value_type&)
  17902. */
  17903. reference operator+=(const typename object_t::value_type& val)
  17904. {
  17905. push_back(val);
  17906. return *this;
  17907. }
  17908. /*!
  17909. @brief add an object to an object
  17910. This function allows to use `push_back` with an initializer list. In case
  17911. 1. the current value is an object,
  17912. 2. the initializer list @a init contains only two elements, and
  17913. 3. the first element of @a init is a string,
  17914. @a init is converted into an object element and added using
  17915. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  17916. is converted to a JSON value and added using @ref push_back(basic_json&&).
  17917. @param[in] init an initializer list
  17918. @complexity Linear in the size of the initializer list @a init.
  17919. @note This function is required to resolve an ambiguous overload error,
  17920. because pairs like `{"key", "value"}` can be both interpreted as
  17921. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  17922. https://github.com/nlohmann/json/issues/235 for more information.
  17923. @liveexample{The example shows how initializer lists are treated as
  17924. objects when possible.,push_back__initializer_list}
  17925. */
  17926. void push_back(initializer_list_t init)
  17927. {
  17928. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  17929. {
  17930. basic_json&& key = init.begin()->moved_or_copied();
  17931. push_back(typename object_t::value_type(
  17932. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  17933. }
  17934. else
  17935. {
  17936. push_back(basic_json(init));
  17937. }
  17938. }
  17939. /*!
  17940. @brief add an object to an object
  17941. @copydoc push_back(initializer_list_t)
  17942. */
  17943. reference operator+=(initializer_list_t init)
  17944. {
  17945. push_back(init);
  17946. return *this;
  17947. }
  17948. /*!
  17949. @brief add an object to an array
  17950. Creates a JSON value from the passed parameters @a args to the end of the
  17951. JSON value. If the function is called on a JSON null value, an empty array
  17952. is created before appending the value created from @a args.
  17953. @param[in] args arguments to forward to a constructor of @ref basic_json
  17954. @tparam Args compatible types to create a @ref basic_json object
  17955. @return reference to the inserted element
  17956. @throw type_error.311 when called on a type other than JSON array or
  17957. null; example: `"cannot use emplace_back() with number"`
  17958. @complexity Amortized constant.
  17959. @liveexample{The example shows how `push_back()` can be used to add
  17960. elements to a JSON array. Note how the `null` value was silently converted
  17961. to a JSON array.,emplace_back}
  17962. @since version 2.0.8, returns reference since 3.7.0
  17963. */
  17964. template<class... Args>
  17965. reference emplace_back(Args&& ... args)
  17966. {
  17967. // emplace_back only works for null objects or arrays
  17968. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  17969. {
  17970. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  17971. }
  17972. // transform null object into an array
  17973. if (is_null())
  17974. {
  17975. m_type = value_t::array;
  17976. m_value = value_t::array;
  17977. assert_invariant();
  17978. }
  17979. // add element to array (perfect forwarding)
  17980. #ifdef JSON_HAS_CPP_17
  17981. return m_value.array->emplace_back(std::forward<Args>(args)...);
  17982. #else
  17983. m_value.array->emplace_back(std::forward<Args>(args)...);
  17984. return m_value.array->back();
  17985. #endif
  17986. }
  17987. /*!
  17988. @brief add an object to an object if key does not exist
  17989. Inserts a new element into a JSON object constructed in-place with the
  17990. given @a args if there is no element with the key in the container. If the
  17991. function is called on a JSON null value, an empty object is created before
  17992. appending the value created from @a args.
  17993. @param[in] args arguments to forward to a constructor of @ref basic_json
  17994. @tparam Args compatible types to create a @ref basic_json object
  17995. @return a pair consisting of an iterator to the inserted element, or the
  17996. already-existing element if no insertion happened, and a bool
  17997. denoting whether the insertion took place.
  17998. @throw type_error.311 when called on a type other than JSON object or
  17999. null; example: `"cannot use emplace() with number"`
  18000. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  18001. @liveexample{The example shows how `emplace()` can be used to add elements
  18002. to a JSON object. Note how the `null` value was silently converted to a
  18003. JSON object. Further note how no value is added if there was already one
  18004. value stored with the same key.,emplace}
  18005. @since version 2.0.8
  18006. */
  18007. template<class... Args>
  18008. std::pair<iterator, bool> emplace(Args&& ... args)
  18009. {
  18010. // emplace only works for null objects or arrays
  18011. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  18012. {
  18013. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  18014. }
  18015. // transform null object into an object
  18016. if (is_null())
  18017. {
  18018. m_type = value_t::object;
  18019. m_value = value_t::object;
  18020. assert_invariant();
  18021. }
  18022. // add element to array (perfect forwarding)
  18023. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  18024. // create result iterator and set iterator to the result of emplace
  18025. auto it = begin();
  18026. it.m_it.object_iterator = res.first;
  18027. // return pair of iterator and boolean
  18028. return {it, res.second};
  18029. }
  18030. /// Helper for insertion of an iterator
  18031. /// @note: This uses std::distance to support GCC 4.8,
  18032. /// see https://github.com/nlohmann/json/pull/1257
  18033. template<typename... Args>
  18034. iterator insert_iterator(const_iterator pos, Args&& ... args)
  18035. {
  18036. iterator result(this);
  18037. assert(m_value.array != nullptr);
  18038. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  18039. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  18040. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  18041. // This could have been written as:
  18042. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  18043. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  18044. return result;
  18045. }
  18046. /*!
  18047. @brief inserts element
  18048. Inserts element @a val before iterator @a pos.
  18049. @param[in] pos iterator before which the content will be inserted; may be
  18050. the end() iterator
  18051. @param[in] val element to insert
  18052. @return iterator pointing to the inserted @a val.
  18053. @throw type_error.309 if called on JSON values other than arrays;
  18054. example: `"cannot use insert() with string"`
  18055. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18056. example: `"iterator does not fit current value"`
  18057. @complexity Constant plus linear in the distance between @a pos and end of
  18058. the container.
  18059. @liveexample{The example shows how `insert()` is used.,insert}
  18060. @since version 1.0.0
  18061. */
  18062. iterator insert(const_iterator pos, const basic_json& val)
  18063. {
  18064. // insert only works for arrays
  18065. if (JSON_HEDLEY_LIKELY(is_array()))
  18066. {
  18067. // check if iterator pos fits to this JSON value
  18068. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18069. {
  18070. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18071. }
  18072. // insert to array and return iterator
  18073. return insert_iterator(pos, val);
  18074. }
  18075. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18076. }
  18077. /*!
  18078. @brief inserts element
  18079. @copydoc insert(const_iterator, const basic_json&)
  18080. */
  18081. iterator insert(const_iterator pos, basic_json&& val)
  18082. {
  18083. return insert(pos, val);
  18084. }
  18085. /*!
  18086. @brief inserts elements
  18087. Inserts @a cnt copies of @a val before iterator @a pos.
  18088. @param[in] pos iterator before which the content will be inserted; may be
  18089. the end() iterator
  18090. @param[in] cnt number of copies of @a val to insert
  18091. @param[in] val element to insert
  18092. @return iterator pointing to the first element inserted, or @a pos if
  18093. `cnt==0`
  18094. @throw type_error.309 if called on JSON values other than arrays; example:
  18095. `"cannot use insert() with string"`
  18096. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18097. example: `"iterator does not fit current value"`
  18098. @complexity Linear in @a cnt plus linear in the distance between @a pos
  18099. and end of the container.
  18100. @liveexample{The example shows how `insert()` is used.,insert__count}
  18101. @since version 1.0.0
  18102. */
  18103. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  18104. {
  18105. // insert only works for arrays
  18106. if (JSON_HEDLEY_LIKELY(is_array()))
  18107. {
  18108. // check if iterator pos fits to this JSON value
  18109. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18110. {
  18111. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18112. }
  18113. // insert to array and return iterator
  18114. return insert_iterator(pos, cnt, val);
  18115. }
  18116. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18117. }
  18118. /*!
  18119. @brief inserts elements
  18120. Inserts elements from range `[first, last)` before iterator @a pos.
  18121. @param[in] pos iterator before which the content will be inserted; may be
  18122. the end() iterator
  18123. @param[in] first begin of the range of elements to insert
  18124. @param[in] last end of the range of elements to insert
  18125. @throw type_error.309 if called on JSON values other than arrays; example:
  18126. `"cannot use insert() with string"`
  18127. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18128. example: `"iterator does not fit current value"`
  18129. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18130. same JSON value; example: `"iterators do not fit"`
  18131. @throw invalid_iterator.211 if @a first or @a last are iterators into
  18132. container for which insert is called; example: `"passed iterators may not
  18133. belong to container"`
  18134. @return iterator pointing to the first element inserted, or @a pos if
  18135. `first==last`
  18136. @complexity Linear in `std::distance(first, last)` plus linear in the
  18137. distance between @a pos and end of the container.
  18138. @liveexample{The example shows how `insert()` is used.,insert__range}
  18139. @since version 1.0.0
  18140. */
  18141. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  18142. {
  18143. // insert only works for arrays
  18144. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  18145. {
  18146. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18147. }
  18148. // check if iterator pos fits to this JSON value
  18149. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18150. {
  18151. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18152. }
  18153. // check if range iterators belong to the same JSON object
  18154. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18155. {
  18156. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18157. }
  18158. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  18159. {
  18160. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  18161. }
  18162. // insert to array and return iterator
  18163. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  18164. }
  18165. /*!
  18166. @brief inserts elements
  18167. Inserts elements from initializer list @a ilist before iterator @a pos.
  18168. @param[in] pos iterator before which the content will be inserted; may be
  18169. the end() iterator
  18170. @param[in] ilist initializer list to insert the values from
  18171. @throw type_error.309 if called on JSON values other than arrays; example:
  18172. `"cannot use insert() with string"`
  18173. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18174. example: `"iterator does not fit current value"`
  18175. @return iterator pointing to the first element inserted, or @a pos if
  18176. `ilist` is empty
  18177. @complexity Linear in `ilist.size()` plus linear in the distance between
  18178. @a pos and end of the container.
  18179. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  18180. @since version 1.0.0
  18181. */
  18182. iterator insert(const_iterator pos, initializer_list_t ilist)
  18183. {
  18184. // insert only works for arrays
  18185. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  18186. {
  18187. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18188. }
  18189. // check if iterator pos fits to this JSON value
  18190. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18191. {
  18192. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18193. }
  18194. // insert to array and return iterator
  18195. return insert_iterator(pos, ilist.begin(), ilist.end());
  18196. }
  18197. /*!
  18198. @brief inserts elements
  18199. Inserts elements from range `[first, last)`.
  18200. @param[in] first begin of the range of elements to insert
  18201. @param[in] last end of the range of elements to insert
  18202. @throw type_error.309 if called on JSON values other than objects; example:
  18203. `"cannot use insert() with string"`
  18204. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18205. point to an object; example: `"iterators first and last must point to
  18206. objects"`
  18207. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18208. same JSON value; example: `"iterators do not fit"`
  18209. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  18210. of elements to insert.
  18211. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  18212. @since version 3.0.0
  18213. */
  18214. void insert(const_iterator first, const_iterator last)
  18215. {
  18216. // insert only works for objects
  18217. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18218. {
  18219. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18220. }
  18221. // check if range iterators belong to the same JSON object
  18222. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18223. {
  18224. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18225. }
  18226. // passed iterators must belong to objects
  18227. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  18228. {
  18229. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18230. }
  18231. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  18232. }
  18233. /*!
  18234. @brief updates a JSON object from another object, overwriting existing keys
  18235. Inserts all values from JSON object @a j and overwrites existing keys.
  18236. @param[in] j JSON object to read values from
  18237. @throw type_error.312 if called on JSON values other than objects; example:
  18238. `"cannot use update() with string"`
  18239. @complexity O(N*log(size() + N)), where N is the number of elements to
  18240. insert.
  18241. @liveexample{The example shows how `update()` is used.,update}
  18242. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18243. @since version 3.0.0
  18244. */
  18245. void update(const_reference j)
  18246. {
  18247. // implicitly convert null value to an empty object
  18248. if (is_null())
  18249. {
  18250. m_type = value_t::object;
  18251. m_value.object = create<object_t>();
  18252. assert_invariant();
  18253. }
  18254. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18255. {
  18256. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18257. }
  18258. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  18259. {
  18260. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  18261. }
  18262. for (auto it = j.cbegin(); it != j.cend(); ++it)
  18263. {
  18264. m_value.object->operator[](it.key()) = it.value();
  18265. }
  18266. }
  18267. /*!
  18268. @brief updates a JSON object from another object, overwriting existing keys
  18269. Inserts all values from from range `[first, last)` and overwrites existing
  18270. keys.
  18271. @param[in] first begin of the range of elements to insert
  18272. @param[in] last end of the range of elements to insert
  18273. @throw type_error.312 if called on JSON values other than objects; example:
  18274. `"cannot use update() with string"`
  18275. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18276. point to an object; example: `"iterators first and last must point to
  18277. objects"`
  18278. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18279. same JSON value; example: `"iterators do not fit"`
  18280. @complexity O(N*log(size() + N)), where N is the number of elements to
  18281. insert.
  18282. @liveexample{The example shows how `update()` is used__range.,update}
  18283. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18284. @since version 3.0.0
  18285. */
  18286. void update(const_iterator first, const_iterator last)
  18287. {
  18288. // implicitly convert null value to an empty object
  18289. if (is_null())
  18290. {
  18291. m_type = value_t::object;
  18292. m_value.object = create<object_t>();
  18293. assert_invariant();
  18294. }
  18295. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  18296. {
  18297. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18298. }
  18299. // check if range iterators belong to the same JSON object
  18300. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18301. {
  18302. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18303. }
  18304. // passed iterators must belong to objects
  18305. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  18306. or not last.m_object->is_object()))
  18307. {
  18308. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18309. }
  18310. for (auto it = first; it != last; ++it)
  18311. {
  18312. m_value.object->operator[](it.key()) = it.value();
  18313. }
  18314. }
  18315. /*!
  18316. @brief exchanges the values
  18317. Exchanges the contents of the JSON value with those of @a other. Does not
  18318. invoke any move, copy, or swap operations on individual elements. All
  18319. iterators and references remain valid. The past-the-end iterator is
  18320. invalidated.
  18321. @param[in,out] other JSON value to exchange the contents with
  18322. @complexity Constant.
  18323. @liveexample{The example below shows how JSON values can be swapped with
  18324. `swap()`.,swap__reference}
  18325. @since version 1.0.0
  18326. */
  18327. void swap(reference other) noexcept (
  18328. std::is_nothrow_move_constructible<value_t>::value and
  18329. std::is_nothrow_move_assignable<value_t>::value and
  18330. std::is_nothrow_move_constructible<json_value>::value and
  18331. std::is_nothrow_move_assignable<json_value>::value
  18332. )
  18333. {
  18334. std::swap(m_type, other.m_type);
  18335. std::swap(m_value, other.m_value);
  18336. assert_invariant();
  18337. }
  18338. /*!
  18339. @brief exchanges the values
  18340. Exchanges the contents of a JSON array with those of @a other. Does not
  18341. invoke any move, copy, or swap operations on individual elements. All
  18342. iterators and references remain valid. The past-the-end iterator is
  18343. invalidated.
  18344. @param[in,out] other array to exchange the contents with
  18345. @throw type_error.310 when JSON value is not an array; example: `"cannot
  18346. use swap() with string"`
  18347. @complexity Constant.
  18348. @liveexample{The example below shows how arrays can be swapped with
  18349. `swap()`.,swap__array_t}
  18350. @since version 1.0.0
  18351. */
  18352. void swap(array_t& other)
  18353. {
  18354. // swap only works for arrays
  18355. if (JSON_HEDLEY_LIKELY(is_array()))
  18356. {
  18357. std::swap(*(m_value.array), other);
  18358. }
  18359. else
  18360. {
  18361. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18362. }
  18363. }
  18364. /*!
  18365. @brief exchanges the values
  18366. Exchanges the contents of a JSON object with those of @a other. Does not
  18367. invoke any move, copy, or swap operations on individual elements. All
  18368. iterators and references remain valid. The past-the-end iterator is
  18369. invalidated.
  18370. @param[in,out] other object to exchange the contents with
  18371. @throw type_error.310 when JSON value is not an object; example:
  18372. `"cannot use swap() with string"`
  18373. @complexity Constant.
  18374. @liveexample{The example below shows how objects can be swapped with
  18375. `swap()`.,swap__object_t}
  18376. @since version 1.0.0
  18377. */
  18378. void swap(object_t& other)
  18379. {
  18380. // swap only works for objects
  18381. if (JSON_HEDLEY_LIKELY(is_object()))
  18382. {
  18383. std::swap(*(m_value.object), other);
  18384. }
  18385. else
  18386. {
  18387. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18388. }
  18389. }
  18390. /*!
  18391. @brief exchanges the values
  18392. Exchanges the contents of a JSON string with those of @a other. Does not
  18393. invoke any move, copy, or swap operations on individual elements. All
  18394. iterators and references remain valid. The past-the-end iterator is
  18395. invalidated.
  18396. @param[in,out] other string to exchange the contents with
  18397. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18398. use swap() with boolean"`
  18399. @complexity Constant.
  18400. @liveexample{The example below shows how strings can be swapped with
  18401. `swap()`.,swap__string_t}
  18402. @since version 1.0.0
  18403. */
  18404. void swap(string_t& other)
  18405. {
  18406. // swap only works for strings
  18407. if (JSON_HEDLEY_LIKELY(is_string()))
  18408. {
  18409. std::swap(*(m_value.string), other);
  18410. }
  18411. else
  18412. {
  18413. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18414. }
  18415. }
  18416. /*!
  18417. @brief exchanges the values
  18418. Exchanges the contents of a JSON string with those of @a other. Does not
  18419. invoke any move, copy, or swap operations on individual elements. All
  18420. iterators and references remain valid. The past-the-end iterator is
  18421. invalidated.
  18422. @param[in,out] other binary to exchange the contents with
  18423. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18424. use swap() with boolean"`
  18425. @complexity Constant.
  18426. @liveexample{The example below shows how strings can be swapped with
  18427. `swap()`.,swap__binary_t}
  18428. @since version 3.8.0
  18429. */
  18430. void swap(binary_t& other)
  18431. {
  18432. // swap only works for strings
  18433. if (JSON_HEDLEY_LIKELY(is_binary()))
  18434. {
  18435. std::swap(*(m_value.binary), other);
  18436. }
  18437. else
  18438. {
  18439. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18440. }
  18441. }
  18442. /// @copydoc swap(binary_t)
  18443. void swap(typename binary_t::container_type& other)
  18444. {
  18445. // swap only works for strings
  18446. if (JSON_HEDLEY_LIKELY(is_binary()))
  18447. {
  18448. std::swap(*(m_value.binary), other);
  18449. }
  18450. else
  18451. {
  18452. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18453. }
  18454. }
  18455. /// @}
  18456. public:
  18457. //////////////////////////////////////////
  18458. // lexicographical comparison operators //
  18459. //////////////////////////////////////////
  18460. /// @name lexicographical comparison operators
  18461. /// @{
  18462. /*!
  18463. @brief comparison: equal
  18464. Compares two JSON values for equality according to the following rules:
  18465. - Two JSON values are equal if (1) they are from the same type and (2)
  18466. their stored values are the same according to their respective
  18467. `operator==`.
  18468. - Integer and floating-point numbers are automatically converted before
  18469. comparison. Note that two NaN values are always treated as unequal.
  18470. - Two JSON null values are equal.
  18471. @note Floating-point inside JSON values numbers are compared with
  18472. `json::number_float_t::operator==` which is `double::operator==` by
  18473. default. To compare floating-point while respecting an epsilon, an alternative
  18474. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  18475. could be used, for instance
  18476. @code {.cpp}
  18477. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  18478. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  18479. {
  18480. return std::abs(a - b) <= epsilon;
  18481. }
  18482. @endcode
  18483. Or you can self-defined operator equal function like this:
  18484. @code {.cpp}
  18485. bool my_equal(const_reference lhs, const_reference rhs) {
  18486. const auto lhs_type lhs.type();
  18487. const auto rhs_type rhs.type();
  18488. if (lhs_type == rhs_type) {
  18489. switch(lhs_type)
  18490. // self_defined case
  18491. case value_t::number_float:
  18492. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  18493. // other cases remain the same with the original
  18494. ...
  18495. }
  18496. ...
  18497. }
  18498. @endcode
  18499. @note NaN values never compare equal to themselves or to other NaN values.
  18500. @param[in] lhs first JSON value to consider
  18501. @param[in] rhs second JSON value to consider
  18502. @return whether the values @a lhs and @a rhs are equal
  18503. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18504. @complexity Linear.
  18505. @liveexample{The example demonstrates comparing several JSON
  18506. types.,operator__equal}
  18507. @since version 1.0.0
  18508. */
  18509. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  18510. {
  18511. const auto lhs_type = lhs.type();
  18512. const auto rhs_type = rhs.type();
  18513. if (lhs_type == rhs_type)
  18514. {
  18515. switch (lhs_type)
  18516. {
  18517. case value_t::array:
  18518. return *lhs.m_value.array == *rhs.m_value.array;
  18519. case value_t::object:
  18520. return *lhs.m_value.object == *rhs.m_value.object;
  18521. case value_t::null:
  18522. return true;
  18523. case value_t::string:
  18524. return *lhs.m_value.string == *rhs.m_value.string;
  18525. case value_t::boolean:
  18526. return lhs.m_value.boolean == rhs.m_value.boolean;
  18527. case value_t::number_integer:
  18528. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  18529. case value_t::number_unsigned:
  18530. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  18531. case value_t::number_float:
  18532. return lhs.m_value.number_float == rhs.m_value.number_float;
  18533. case value_t::binary:
  18534. return *lhs.m_value.binary == *rhs.m_value.binary;
  18535. default:
  18536. return false;
  18537. }
  18538. }
  18539. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  18540. {
  18541. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  18542. }
  18543. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  18544. {
  18545. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  18546. }
  18547. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  18548. {
  18549. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  18550. }
  18551. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  18552. {
  18553. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18554. }
  18555. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  18556. {
  18557. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  18558. }
  18559. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  18560. {
  18561. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18562. }
  18563. return false;
  18564. }
  18565. /*!
  18566. @brief comparison: equal
  18567. @copydoc operator==(const_reference, const_reference)
  18568. */
  18569. template<typename ScalarType, typename std::enable_if<
  18570. std::is_scalar<ScalarType>::value, int>::type = 0>
  18571. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  18572. {
  18573. return lhs == basic_json(rhs);
  18574. }
  18575. /*!
  18576. @brief comparison: equal
  18577. @copydoc operator==(const_reference, const_reference)
  18578. */
  18579. template<typename ScalarType, typename std::enable_if<
  18580. std::is_scalar<ScalarType>::value, int>::type = 0>
  18581. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  18582. {
  18583. return basic_json(lhs) == rhs;
  18584. }
  18585. /*!
  18586. @brief comparison: not equal
  18587. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  18588. @param[in] lhs first JSON value to consider
  18589. @param[in] rhs second JSON value to consider
  18590. @return whether the values @a lhs and @a rhs are not equal
  18591. @complexity Linear.
  18592. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18593. @liveexample{The example demonstrates comparing several JSON
  18594. types.,operator__notequal}
  18595. @since version 1.0.0
  18596. */
  18597. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  18598. {
  18599. return not (lhs == rhs);
  18600. }
  18601. /*!
  18602. @brief comparison: not 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_reference lhs, const ScalarType rhs) noexcept
  18608. {
  18609. return lhs != basic_json(rhs);
  18610. }
  18611. /*!
  18612. @brief comparison: not equal
  18613. @copydoc operator!=(const_reference, const_reference)
  18614. */
  18615. template<typename ScalarType, typename std::enable_if<
  18616. std::is_scalar<ScalarType>::value, int>::type = 0>
  18617. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  18618. {
  18619. return basic_json(lhs) != rhs;
  18620. }
  18621. /*!
  18622. @brief comparison: less than
  18623. Compares whether one JSON value @a lhs is less than another JSON value @a
  18624. rhs according to the following rules:
  18625. - If @a lhs and @a rhs have the same type, the values are compared using
  18626. the default `<` operator.
  18627. - Integer and floating-point numbers are automatically converted before
  18628. comparison
  18629. - In case @a lhs and @a rhs have different types, the values are ignored
  18630. and the order of the types is considered, see
  18631. @ref operator<(const value_t, const value_t).
  18632. @param[in] lhs first JSON value to consider
  18633. @param[in] rhs second JSON value to consider
  18634. @return whether @a lhs is less than @a rhs
  18635. @complexity Linear.
  18636. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18637. @liveexample{The example demonstrates comparing several JSON
  18638. types.,operator__less}
  18639. @since version 1.0.0
  18640. */
  18641. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  18642. {
  18643. const auto lhs_type = lhs.type();
  18644. const auto rhs_type = rhs.type();
  18645. if (lhs_type == rhs_type)
  18646. {
  18647. switch (lhs_type)
  18648. {
  18649. case value_t::array:
  18650. // note parentheses are necessary, see
  18651. // https://github.com/nlohmann/json/issues/1530
  18652. return (*lhs.m_value.array) < (*rhs.m_value.array);
  18653. case value_t::object:
  18654. return (*lhs.m_value.object) < (*rhs.m_value.object);
  18655. case value_t::null:
  18656. return false;
  18657. case value_t::string:
  18658. return (*lhs.m_value.string) < (*rhs.m_value.string);
  18659. case value_t::boolean:
  18660. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  18661. case value_t::number_integer:
  18662. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  18663. case value_t::number_unsigned:
  18664. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  18665. case value_t::number_float:
  18666. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  18667. case value_t::binary:
  18668. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  18669. default:
  18670. return false;
  18671. }
  18672. }
  18673. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  18674. {
  18675. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  18676. }
  18677. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  18678. {
  18679. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  18680. }
  18681. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  18682. {
  18683. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  18684. }
  18685. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  18686. {
  18687. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18688. }
  18689. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  18690. {
  18691. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18692. }
  18693. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  18694. {
  18695. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  18696. }
  18697. // We only reach this line if we cannot compare values. In that case,
  18698. // we compare types. Note we have to call the operator explicitly,
  18699. // because MSVC has problems otherwise.
  18700. return operator<(lhs_type, rhs_type);
  18701. }
  18702. /*!
  18703. @brief comparison: less than
  18704. @copydoc operator<(const_reference, const_reference)
  18705. */
  18706. template<typename ScalarType, typename std::enable_if<
  18707. std::is_scalar<ScalarType>::value, int>::type = 0>
  18708. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  18709. {
  18710. return lhs < basic_json(rhs);
  18711. }
  18712. /*!
  18713. @brief comparison: less than
  18714. @copydoc operator<(const_reference, const_reference)
  18715. */
  18716. template<typename ScalarType, typename std::enable_if<
  18717. std::is_scalar<ScalarType>::value, int>::type = 0>
  18718. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  18719. {
  18720. return basic_json(lhs) < rhs;
  18721. }
  18722. /*!
  18723. @brief comparison: less than or equal
  18724. Compares whether one JSON value @a lhs is less than or equal to another
  18725. JSON value by calculating `not (rhs < lhs)`.
  18726. @param[in] lhs first JSON value to consider
  18727. @param[in] rhs second JSON value to consider
  18728. @return whether @a lhs is less than or equal to @a rhs
  18729. @complexity Linear.
  18730. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18731. @liveexample{The example demonstrates comparing several JSON
  18732. types.,operator__greater}
  18733. @since version 1.0.0
  18734. */
  18735. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  18736. {
  18737. return not (rhs < lhs);
  18738. }
  18739. /*!
  18740. @brief comparison: less than or equal
  18741. @copydoc operator<=(const_reference, const_reference)
  18742. */
  18743. template<typename ScalarType, typename std::enable_if<
  18744. std::is_scalar<ScalarType>::value, int>::type = 0>
  18745. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  18746. {
  18747. return lhs <= basic_json(rhs);
  18748. }
  18749. /*!
  18750. @brief comparison: less than or equal
  18751. @copydoc operator<=(const_reference, const_reference)
  18752. */
  18753. template<typename ScalarType, typename std::enable_if<
  18754. std::is_scalar<ScalarType>::value, int>::type = 0>
  18755. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  18756. {
  18757. return basic_json(lhs) <= rhs;
  18758. }
  18759. /*!
  18760. @brief comparison: greater than
  18761. Compares whether one JSON value @a lhs is greater than another
  18762. JSON value by calculating `not (lhs <= rhs)`.
  18763. @param[in] lhs first JSON value to consider
  18764. @param[in] rhs second JSON value to consider
  18765. @return whether @a lhs is greater than to @a rhs
  18766. @complexity Linear.
  18767. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18768. @liveexample{The example demonstrates comparing several JSON
  18769. types.,operator__lessequal}
  18770. @since version 1.0.0
  18771. */
  18772. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  18773. {
  18774. return not (lhs <= rhs);
  18775. }
  18776. /*!
  18777. @brief comparison: greater than
  18778. @copydoc operator>(const_reference, const_reference)
  18779. */
  18780. template<typename ScalarType, typename std::enable_if<
  18781. std::is_scalar<ScalarType>::value, int>::type = 0>
  18782. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  18783. {
  18784. return lhs > basic_json(rhs);
  18785. }
  18786. /*!
  18787. @brief comparison: greater than
  18788. @copydoc operator>(const_reference, const_reference)
  18789. */
  18790. template<typename ScalarType, typename std::enable_if<
  18791. std::is_scalar<ScalarType>::value, int>::type = 0>
  18792. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  18793. {
  18794. return basic_json(lhs) > rhs;
  18795. }
  18796. /*!
  18797. @brief comparison: greater than or equal
  18798. Compares whether one JSON value @a lhs is greater than or equal to another
  18799. JSON value by calculating `not (lhs < rhs)`.
  18800. @param[in] lhs first JSON value to consider
  18801. @param[in] rhs second JSON value to consider
  18802. @return whether @a lhs is greater than or equal to @a rhs
  18803. @complexity Linear.
  18804. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18805. @liveexample{The example demonstrates comparing several JSON
  18806. types.,operator__greaterequal}
  18807. @since version 1.0.0
  18808. */
  18809. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  18810. {
  18811. return not (lhs < rhs);
  18812. }
  18813. /*!
  18814. @brief comparison: greater than or equal
  18815. @copydoc operator>=(const_reference, const_reference)
  18816. */
  18817. template<typename ScalarType, typename std::enable_if<
  18818. std::is_scalar<ScalarType>::value, int>::type = 0>
  18819. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  18820. {
  18821. return lhs >= basic_json(rhs);
  18822. }
  18823. /*!
  18824. @brief comparison: greater than or equal
  18825. @copydoc operator>=(const_reference, const_reference)
  18826. */
  18827. template<typename ScalarType, typename std::enable_if<
  18828. std::is_scalar<ScalarType>::value, int>::type = 0>
  18829. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  18830. {
  18831. return basic_json(lhs) >= rhs;
  18832. }
  18833. /// @}
  18834. ///////////////////
  18835. // serialization //
  18836. ///////////////////
  18837. /// @name serialization
  18838. /// @{
  18839. /*!
  18840. @brief serialize to stream
  18841. Serialize the given JSON value @a j to the output stream @a o. The JSON
  18842. value will be serialized using the @ref dump member function.
  18843. - The indentation of the output can be controlled with the member variable
  18844. `width` of the output stream @a o. For instance, using the manipulator
  18845. `std::setw(4)` on @a o sets the indentation level to `4` and the
  18846. serialization result is the same as calling `dump(4)`.
  18847. - The indentation character can be controlled with the member variable
  18848. `fill` of the output stream @a o. For instance, the manipulator
  18849. `std::setfill('\\t')` sets indentation to use a tab character rather than
  18850. the default space character.
  18851. @param[in,out] o stream to serialize to
  18852. @param[in] j JSON value to serialize
  18853. @return the stream @a o
  18854. @throw type_error.316 if a string stored inside the JSON value is not
  18855. UTF-8 encoded
  18856. @complexity Linear.
  18857. @liveexample{The example below shows the serialization with different
  18858. parameters to `width` to adjust the indentation level.,operator_serialize}
  18859. @since version 1.0.0; indentation character added in version 3.0.0
  18860. */
  18861. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  18862. {
  18863. // read width member and use it as indentation parameter if nonzero
  18864. const bool pretty_print = o.width() > 0;
  18865. const auto indentation = pretty_print ? o.width() : 0;
  18866. // reset width to 0 for subsequent calls to this stream
  18867. o.width(0);
  18868. // do the actual serialization
  18869. serializer s(detail::output_adapter<char>(o), o.fill());
  18870. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  18871. return o;
  18872. }
  18873. /*!
  18874. @brief serialize to stream
  18875. @deprecated This stream operator is deprecated and will be removed in
  18876. future 4.0.0 of the library. Please use
  18877. @ref operator<<(std::ostream&, const basic_json&)
  18878. instead; that is, replace calls like `j >> o;` with `o << j;`.
  18879. @since version 1.0.0; deprecated since version 3.0.0
  18880. */
  18881. JSON_HEDLEY_DEPRECATED(3.0.0)
  18882. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  18883. {
  18884. return o << j;
  18885. }
  18886. /// @}
  18887. /////////////////////
  18888. // deserialization //
  18889. /////////////////////
  18890. /// @name deserialization
  18891. /// @{
  18892. /*!
  18893. @brief deserialize from a compatible input
  18894. This function reads from a compatible input. Examples are:
  18895. - an array of 1-byte values
  18896. - strings with character/literal type with size of 1 byte
  18897. - input streams
  18898. - container with contiguous storage of 1-byte values. Compatible container
  18899. types include `std::vector`, `std::string`, `std::array`,
  18900. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  18901. arrays can be used with `std::begin()`/`std::end()`. User-defined
  18902. containers can be used as long as they implement random-access iterators
  18903. and a contiguous storage.
  18904. @pre Each element of the container has a size of 1 byte. Violating this
  18905. precondition yields undefined behavior. **This precondition is enforced
  18906. with a static assertion.**
  18907. @pre The container storage is contiguous. Violating this precondition
  18908. yields undefined behavior. **This precondition is enforced with an
  18909. assertion.**
  18910. @warning There is no way to enforce all preconditions at compile-time. If
  18911. the function is called with a noncompliant container and with
  18912. assertions switched off, the behavior is undefined and will most
  18913. likely yield segmentation violation.
  18914. @param[in] i input to read from
  18915. @param[in] cb a parser callback function of type @ref parser_callback_t
  18916. which is used to control the deserialization by filtering unwanted values
  18917. (optional)
  18918. @param[in] allow_exceptions whether to throw exceptions in case of a
  18919. parse error (optional, true by default)
  18920. @return deserialized JSON value; in case of a parse error and
  18921. @a allow_exceptions set to `false`, the return value will be
  18922. value_t::discarded.
  18923. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  18924. of input; expected string literal""`
  18925. @throw parse_error.102 if to_unicode fails or surrogate error
  18926. @throw parse_error.103 if to_unicode fails
  18927. @complexity Linear in the length of the input. The parser is a predictive
  18928. LL(1) parser. The complexity can be higher if the parser callback function
  18929. @a cb has a super-linear complexity.
  18930. @note A UTF-8 byte order mark is silently ignored.
  18931. @liveexample{The example below demonstrates the `parse()` function reading
  18932. from an array.,parse__array__parser_callback_t}
  18933. @liveexample{The example below demonstrates the `parse()` function with
  18934. and without callback function.,parse__string__parser_callback_t}
  18935. @liveexample{The example below demonstrates the `parse()` function with
  18936. and without callback function.,parse__istream__parser_callback_t}
  18937. @liveexample{The example below demonstrates the `parse()` function reading
  18938. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  18939. @since version 2.0.3 (contiguous containers)
  18940. */
  18941. template<typename InputType>
  18942. JSON_HEDLEY_WARN_UNUSED_RESULT
  18943. static basic_json parse(InputType&& i,
  18944. const parser_callback_t cb = nullptr,
  18945. const bool allow_exceptions = true)
  18946. {
  18947. basic_json result;
  18948. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions).parse(true, result);
  18949. return result;
  18950. }
  18951. JSON_HEDLEY_WARN_UNUSED_RESULT
  18952. static basic_json parse(detail::span_input_adapter&& i,
  18953. const parser_callback_t cb = nullptr,
  18954. const bool allow_exceptions = true)
  18955. {
  18956. basic_json result;
  18957. parser(i.get(), cb, allow_exceptions).parse(true, result);
  18958. return result;
  18959. }
  18960. template<typename InputType>
  18961. static bool accept(InputType&& i)
  18962. {
  18963. return parser(detail::input_adapter(std::forward<InputType>(i))).accept(true);
  18964. }
  18965. static bool accept(detail::span_input_adapter&& i)
  18966. {
  18967. return parser(i.get()).accept(true);
  18968. }
  18969. /*!
  18970. @brief generate SAX events
  18971. The SAX event lister must follow the interface of @ref json_sax.
  18972. This function reads from a compatible input. Examples are:
  18973. - an array of 1-byte values
  18974. - strings with character/literal type with size of 1 byte
  18975. - input streams
  18976. - container with contiguous storage of 1-byte values. Compatible container
  18977. types include `std::vector`, `std::string`, `std::array`,
  18978. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  18979. arrays can be used with `std::begin()`/`std::end()`. User-defined
  18980. containers can be used as long as they implement random-access iterators
  18981. and a contiguous storage.
  18982. @pre Each element of the container has a size of 1 byte. Violating this
  18983. precondition yields undefined behavior. **This precondition is enforced
  18984. with a static assertion.**
  18985. @pre The container storage is contiguous. Violating this precondition
  18986. yields undefined behavior. **This precondition is enforced with an
  18987. assertion.**
  18988. @warning There is no way to enforce all preconditions at compile-time. If
  18989. the function is called with a noncompliant container and with
  18990. assertions switched off, the behavior is undefined and will most
  18991. likely yield segmentation violation.
  18992. @param[in] i input to read from
  18993. @param[in,out] sax SAX event listener
  18994. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  18995. @param[in] strict whether the input has to be consumed completely
  18996. @return return value of the last processed SAX event
  18997. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  18998. of input; expected string literal""`
  18999. @throw parse_error.102 if to_unicode fails or surrogate error
  19000. @throw parse_error.103 if to_unicode fails
  19001. @complexity Linear in the length of the input. The parser is a predictive
  19002. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  19003. a super-linear complexity.
  19004. @note A UTF-8 byte order mark is silently ignored.
  19005. @liveexample{The example below demonstrates the `sax_parse()` function
  19006. reading from string and processing the events with a user-defined SAX
  19007. event consumer.,sax_parse}
  19008. @since version 3.2.0
  19009. */
  19010. template <typename SAX, typename InputType>
  19011. JSON_HEDLEY_NON_NULL(2)
  19012. static bool sax_parse(InputType&& i, SAX* sax,
  19013. input_format_t format = input_format_t::json,
  19014. const bool strict = true)
  19015. {
  19016. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19017. return format == input_format_t::json
  19018. ? parser(std::move(ia)).sax_parse(sax, strict)
  19019. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19020. }
  19021. template <typename SAX>
  19022. JSON_HEDLEY_NON_NULL(2)
  19023. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  19024. input_format_t format = input_format_t::json,
  19025. const bool strict = true)
  19026. {
  19027. auto ia = i.get();
  19028. return format == input_format_t::json
  19029. ? parser(std::move(ia)).sax_parse(sax, strict)
  19030. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19031. }
  19032. /*!
  19033. @brief deserialize from an iterator range with contiguous storage
  19034. This function reads from an iterator range of a container with contiguous
  19035. storage of 1-byte values. Compatible container types include
  19036. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  19037. `std::initializer_list`. Furthermore, C-style arrays can be used with
  19038. `std::begin()`/`std::end()`. User-defined containers can be used as long
  19039. as they implement random-access iterators and a contiguous storage.
  19040. @pre The iterator range is contiguous. Violating this precondition yields
  19041. undefined behavior. **This precondition is enforced with an assertion.**
  19042. @pre Each element in the range has a size of 1 byte. Violating this
  19043. precondition yields undefined behavior. **This precondition is enforced
  19044. with a static assertion.**
  19045. @warning There is no way to enforce all preconditions at compile-time. If
  19046. the function is called with noncompliant iterators and with
  19047. assertions switched off, the behavior is undefined and will most
  19048. likely yield segmentation violation.
  19049. @tparam IteratorType iterator of container with contiguous storage
  19050. @param[in] first begin of the range to parse (included)
  19051. @param[in] last end of the range to parse (excluded)
  19052. @param[in] cb a parser callback function of type @ref parser_callback_t
  19053. which is used to control the deserialization by filtering unwanted values
  19054. (optional)
  19055. @param[in] allow_exceptions whether to throw exceptions in case of a
  19056. parse error (optional, true by default)
  19057. @return deserialized JSON value; in case of a parse error and
  19058. @a allow_exceptions set to `false`, the return value will be
  19059. value_t::discarded.
  19060. @throw parse_error.101 in case of an unexpected token
  19061. @throw parse_error.102 if to_unicode fails or surrogate error
  19062. @throw parse_error.103 if to_unicode fails
  19063. @complexity Linear in the length of the input. The parser is a predictive
  19064. LL(1) parser. The complexity can be higher if the parser callback function
  19065. @a cb has a super-linear complexity.
  19066. @note A UTF-8 byte order mark is silently ignored.
  19067. @liveexample{The example below demonstrates the `parse()` function reading
  19068. from an iterator range.,parse__iteratortype__parser_callback_t}
  19069. @since version 2.0.3
  19070. */
  19071. template<class IteratorType, typename std::enable_if<
  19072. std::is_base_of<
  19073. std::random_access_iterator_tag,
  19074. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  19075. static basic_json parse(IteratorType first, IteratorType last,
  19076. const parser_callback_t cb = nullptr,
  19077. const bool allow_exceptions = true)
  19078. {
  19079. basic_json result;
  19080. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  19081. return result;
  19082. }
  19083. template<class IteratorType, typename std::enable_if<
  19084. std::is_base_of<
  19085. std::random_access_iterator_tag,
  19086. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  19087. static bool accept(IteratorType first, IteratorType last)
  19088. {
  19089. return parser(detail::input_adapter(first, last)).accept(true);
  19090. }
  19091. template<class IteratorType, class SAX, typename std::enable_if<
  19092. std::is_base_of<
  19093. std::random_access_iterator_tag,
  19094. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  19095. JSON_HEDLEY_NON_NULL(3)
  19096. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  19097. {
  19098. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  19099. }
  19100. /*!
  19101. @brief deserialize from stream
  19102. @deprecated This stream operator is deprecated and will be removed in
  19103. version 4.0.0 of the library. Please use
  19104. @ref operator>>(std::istream&, basic_json&)
  19105. instead; that is, replace calls like `j << i;` with `i >> j;`.
  19106. @since version 1.0.0; deprecated since version 3.0.0
  19107. */
  19108. JSON_HEDLEY_DEPRECATED(3.0.0)
  19109. friend std::istream& operator<<(basic_json& j, std::istream& i)
  19110. {
  19111. return operator>>(i, j);
  19112. }
  19113. /*!
  19114. @brief deserialize from stream
  19115. Deserializes an input stream to a JSON value.
  19116. @param[in,out] i input stream to read a serialized JSON value from
  19117. @param[in,out] j JSON value to write the deserialized input to
  19118. @throw parse_error.101 in case of an unexpected token
  19119. @throw parse_error.102 if to_unicode fails or surrogate error
  19120. @throw parse_error.103 if to_unicode fails
  19121. @complexity Linear in the length of the input. The parser is a predictive
  19122. LL(1) parser.
  19123. @note A UTF-8 byte order mark is silently ignored.
  19124. @liveexample{The example below shows how a JSON value is constructed by
  19125. reading a serialization from a stream.,operator_deserialize}
  19126. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  19127. parser callback function to filter values while parsing
  19128. @since version 1.0.0
  19129. */
  19130. friend std::istream& operator>>(std::istream& i, basic_json& j)
  19131. {
  19132. parser(detail::input_adapter(i)).parse(false, j);
  19133. return i;
  19134. }
  19135. /// @}
  19136. ///////////////////////////
  19137. // convenience functions //
  19138. ///////////////////////////
  19139. /*!
  19140. @brief return the type as string
  19141. Returns the type name as string to be used in error messages - usually to
  19142. indicate that a function was called on a wrong JSON type.
  19143. @return a string representation of a the @a m_type member:
  19144. Value type | return value
  19145. ----------- | -------------
  19146. null | `"null"`
  19147. boolean | `"boolean"`
  19148. string | `"string"`
  19149. number | `"number"` (for all number types)
  19150. object | `"object"`
  19151. array | `"array"`
  19152. binary | `"binary"`
  19153. discarded | `"discarded"`
  19154. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19155. @complexity Constant.
  19156. @liveexample{The following code exemplifies `type_name()` for all JSON
  19157. types.,type_name}
  19158. @sa @ref type() -- return the type of the JSON value
  19159. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  19160. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  19161. since 3.0.0
  19162. */
  19163. JSON_HEDLEY_RETURNS_NON_NULL
  19164. const char* type_name() const noexcept
  19165. {
  19166. {
  19167. switch (m_type)
  19168. {
  19169. case value_t::null:
  19170. return "null";
  19171. case value_t::object:
  19172. return "object";
  19173. case value_t::array:
  19174. return "array";
  19175. case value_t::string:
  19176. return "string";
  19177. case value_t::boolean:
  19178. return "boolean";
  19179. case value_t::binary:
  19180. return "binary";
  19181. case value_t::discarded:
  19182. return "discarded";
  19183. default:
  19184. return "number";
  19185. }
  19186. }
  19187. }
  19188. private:
  19189. //////////////////////
  19190. // member variables //
  19191. //////////////////////
  19192. /// the type of the current element
  19193. value_t m_type = value_t::null;
  19194. /// the value of the current element
  19195. json_value m_value = {};
  19196. //////////////////////////////////////////
  19197. // binary serialization/deserialization //
  19198. //////////////////////////////////////////
  19199. /// @name binary serialization/deserialization support
  19200. /// @{
  19201. public:
  19202. /*!
  19203. @brief create a CBOR serialization of a given JSON value
  19204. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  19205. Binary Object Representation) serialization format. CBOR is a binary
  19206. serialization format which aims to be more compact than JSON itself, yet
  19207. more efficient to parse.
  19208. The library uses the following mapping from JSON values types to
  19209. CBOR types according to the CBOR specification (RFC 7049):
  19210. JSON value type | value/range | CBOR type | first byte
  19211. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  19212. null | `null` | Null | 0xF6
  19213. boolean | `true` | True | 0xF5
  19214. boolean | `false` | False | 0xF4
  19215. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  19216. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  19217. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  19218. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  19219. number_integer | -24..-1 | Negative integer | 0x20..0x37
  19220. number_integer | 0..23 | Integer | 0x00..0x17
  19221. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19222. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19223. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19224. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19225. number_unsigned | 0..23 | Integer | 0x00..0x17
  19226. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19227. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19228. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19229. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19230. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  19231. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  19232. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  19233. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  19234. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  19235. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  19236. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  19237. array | *size*: 0..23 | array | 0x80..0x97
  19238. array | *size*: 23..255 | array (1 byte follow) | 0x98
  19239. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  19240. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  19241. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  19242. object | *size*: 0..23 | map | 0xA0..0xB7
  19243. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  19244. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  19245. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  19246. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  19247. binary | *size*: 0..23 | byte string | 0x40..0x57
  19248. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  19249. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  19250. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  19251. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  19252. @note The mapping is **complete** in the sense that any JSON value type
  19253. can be converted to a CBOR value.
  19254. @note If NaN or Infinity are stored inside a JSON number, they are
  19255. serialized properly. This behavior differs from the @ref dump()
  19256. function which serializes NaN or Infinity to `null`.
  19257. @note The following CBOR types are not used in the conversion:
  19258. - UTF-8 strings terminated by "break" (0x7F)
  19259. - arrays terminated by "break" (0x9F)
  19260. - maps terminated by "break" (0xBF)
  19261. - byte strings terminated by "break" (0x5F)
  19262. - date/time (0xC0..0xC1)
  19263. - bignum (0xC2..0xC3)
  19264. - decimal fraction (0xC4)
  19265. - bigfloat (0xC5)
  19266. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19267. - expected conversions (0xD5..0xD7)
  19268. - simple values (0xE0..0xF3, 0xF8)
  19269. - undefined (0xF7)
  19270. - half-precision floats (0xF9)
  19271. - break (0xFF)
  19272. @param[in] j JSON value to serialize
  19273. @return CBOR serialization as byte vector
  19274. @complexity Linear in the size of the JSON value @a j.
  19275. @liveexample{The example shows the serialization of a JSON value to a byte
  19276. vector in CBOR format.,to_cbor}
  19277. @sa http://cbor.io
  19278. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19279. analogous deserialization
  19280. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19281. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19282. related UBJSON format
  19283. @since version 2.0.9; compact representation of floating-point numbers
  19284. since version 3.8.0
  19285. */
  19286. static std::vector<uint8_t> to_cbor(const basic_json& j)
  19287. {
  19288. std::vector<uint8_t> result;
  19289. to_cbor(j, result);
  19290. return result;
  19291. }
  19292. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  19293. {
  19294. binary_writer<uint8_t>(o).write_cbor(j);
  19295. }
  19296. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  19297. {
  19298. binary_writer<char>(o).write_cbor(j);
  19299. }
  19300. /*!
  19301. @brief create a MessagePack serialization of a given JSON value
  19302. Serializes a given JSON value @a j to a byte vector using the MessagePack
  19303. serialization format. MessagePack is a binary serialization format which
  19304. aims to be more compact than JSON itself, yet more efficient to parse.
  19305. The library uses the following mapping from JSON values types to
  19306. MessagePack types according to the MessagePack specification:
  19307. JSON value type | value/range | MessagePack type | first byte
  19308. --------------- | --------------------------------- | ---------------- | ----------
  19309. null | `null` | nil | 0xC0
  19310. boolean | `true` | true | 0xC3
  19311. boolean | `false` | false | 0xC2
  19312. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  19313. number_integer | -2147483648..-32769 | int32 | 0xD2
  19314. number_integer | -32768..-129 | int16 | 0xD1
  19315. number_integer | -128..-33 | int8 | 0xD0
  19316. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  19317. number_integer | 0..127 | positive fixint | 0x00..0x7F
  19318. number_integer | 128..255 | uint 8 | 0xCC
  19319. number_integer | 256..65535 | uint 16 | 0xCD
  19320. number_integer | 65536..4294967295 | uint 32 | 0xCE
  19321. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19322. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  19323. number_unsigned | 128..255 | uint 8 | 0xCC
  19324. number_unsigned | 256..65535 | uint 16 | 0xCD
  19325. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  19326. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19327. number_float | *any value* | float 64 | 0xCB
  19328. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  19329. string | *length*: 32..255 | str 8 | 0xD9
  19330. string | *length*: 256..65535 | str 16 | 0xDA
  19331. string | *length*: 65536..4294967295 | str 32 | 0xDB
  19332. array | *size*: 0..15 | fixarray | 0x90..0x9F
  19333. array | *size*: 16..65535 | array 16 | 0xDC
  19334. array | *size*: 65536..4294967295 | array 32 | 0xDD
  19335. object | *size*: 0..15 | fix map | 0x80..0x8F
  19336. object | *size*: 16..65535 | map 16 | 0xDE
  19337. object | *size*: 65536..4294967295 | map 32 | 0xDF
  19338. binary | *size*: 0..255 | bin 8 | 0xC4
  19339. binary | *size*: 256..65535 | bin 16 | 0xC5
  19340. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  19341. @note The mapping is **complete** in the sense that any JSON value type
  19342. can be converted to a MessagePack value.
  19343. @note The following values can **not** be converted to a MessagePack value:
  19344. - strings with more than 4294967295 bytes
  19345. - byte strings with more than 4294967295 bytes
  19346. - arrays with more than 4294967295 elements
  19347. - objects with more than 4294967295 elements
  19348. @note The following MessagePack types are not used in the conversion:
  19349. - float 32 (0xCA)
  19350. @note Any MessagePack output created @ref to_msgpack can be successfully
  19351. parsed by @ref from_msgpack.
  19352. @note If NaN or Infinity are stored inside a JSON number, they are
  19353. serialized properly. This behavior differs from the @ref dump()
  19354. function which serializes NaN or Infinity to `null`.
  19355. @param[in] j JSON value to serialize
  19356. @return MessagePack serialization as byte vector
  19357. @complexity Linear in the size of the JSON value @a j.
  19358. @liveexample{The example shows the serialization of a JSON value to a byte
  19359. vector in MessagePack format.,to_msgpack}
  19360. @sa http://msgpack.org
  19361. @sa @ref from_msgpack for the analogous deserialization
  19362. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19363. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19364. related UBJSON format
  19365. @since version 2.0.9
  19366. */
  19367. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  19368. {
  19369. std::vector<uint8_t> result;
  19370. to_msgpack(j, result);
  19371. return result;
  19372. }
  19373. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  19374. {
  19375. binary_writer<uint8_t>(o).write_msgpack(j);
  19376. }
  19377. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  19378. {
  19379. binary_writer<char>(o).write_msgpack(j);
  19380. }
  19381. /*!
  19382. @brief create a UBJSON serialization of a given JSON value
  19383. Serializes a given JSON value @a j to a byte vector using the UBJSON
  19384. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  19385. than JSON itself, yet more efficient to parse.
  19386. The library uses the following mapping from JSON values types to
  19387. UBJSON types according to the UBJSON specification:
  19388. JSON value type | value/range | UBJSON type | marker
  19389. --------------- | --------------------------------- | ----------- | ------
  19390. null | `null` | null | `Z`
  19391. boolean | `true` | true | `T`
  19392. boolean | `false` | false | `F`
  19393. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  19394. number_integer | -2147483648..-32769 | int32 | `l`
  19395. number_integer | -32768..-129 | int16 | `I`
  19396. number_integer | -128..127 | int8 | `i`
  19397. number_integer | 128..255 | uint8 | `U`
  19398. number_integer | 256..32767 | int16 | `I`
  19399. number_integer | 32768..2147483647 | int32 | `l`
  19400. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  19401. number_unsigned | 0..127 | int8 | `i`
  19402. number_unsigned | 128..255 | uint8 | `U`
  19403. number_unsigned | 256..32767 | int16 | `I`
  19404. number_unsigned | 32768..2147483647 | int32 | `l`
  19405. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  19406. number_float | *any value* | float64 | `D`
  19407. string | *with shortest length indicator* | string | `S`
  19408. array | *see notes on optimized format* | array | `[`
  19409. object | *see notes on optimized format* | map | `{`
  19410. @note The mapping is **complete** in the sense that any JSON value type
  19411. can be converted to a UBJSON value.
  19412. @note The following values can **not** be converted to a UBJSON value:
  19413. - strings with more than 9223372036854775807 bytes (theoretical)
  19414. - unsigned integer numbers above 9223372036854775807
  19415. @note The following markers are not used in the conversion:
  19416. - `Z`: no-op values are not created.
  19417. - `C`: single-byte strings are serialized with `S` markers.
  19418. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  19419. by @ref from_ubjson.
  19420. @note If NaN or Infinity are stored inside a JSON number, they are
  19421. serialized properly. This behavior differs from the @ref dump()
  19422. function which serializes NaN or Infinity to `null`.
  19423. @note The optimized formats for containers are supported: Parameter
  19424. @a use_size adds size information to the beginning of a container and
  19425. removes the closing marker. Parameter @a use_type further checks
  19426. whether all elements of a container have the same type and adds the
  19427. type marker to the beginning of the container. The @a use_type
  19428. parameter must only be used together with @a use_size = true. Note
  19429. that @a use_size = true alone may result in larger representations -
  19430. the benefit of this parameter is that the receiving side is
  19431. immediately informed on the number of elements of the container.
  19432. @note If the JSON data contains the binary type, the value stored is a list
  19433. of integers, as suggested by the UBJSON documentation. In particular,
  19434. this means that serialization and the deserialization of a JSON
  19435. containing binary values into UBJSON and back will result in a
  19436. different JSON object.
  19437. @param[in] j JSON value to serialize
  19438. @param[in] use_size whether to add size annotations to container types
  19439. @param[in] use_type whether to add type annotations to container types
  19440. (must be combined with @a use_size = true)
  19441. @return UBJSON serialization as byte vector
  19442. @complexity Linear in the size of the JSON value @a j.
  19443. @liveexample{The example shows the serialization of a JSON value to a byte
  19444. vector in UBJSON format.,to_ubjson}
  19445. @sa http://ubjson.org
  19446. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19447. analogous deserialization
  19448. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19449. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19450. @since version 3.1.0
  19451. */
  19452. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  19453. const bool use_size = false,
  19454. const bool use_type = false)
  19455. {
  19456. std::vector<uint8_t> result;
  19457. to_ubjson(j, result, use_size, use_type);
  19458. return result;
  19459. }
  19460. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  19461. const bool use_size = false, const bool use_type = false)
  19462. {
  19463. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  19464. }
  19465. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  19466. const bool use_size = false, const bool use_type = false)
  19467. {
  19468. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  19469. }
  19470. /*!
  19471. @brief Serializes the given JSON object `j` to BSON and returns a vector
  19472. containing the corresponding BSON-representation.
  19473. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  19474. stored as a single entity (a so-called document).
  19475. The library uses the following mapping from JSON values types to BSON types:
  19476. JSON value type | value/range | BSON type | marker
  19477. --------------- | --------------------------------- | ----------- | ------
  19478. null | `null` | null | 0x0A
  19479. boolean | `true`, `false` | boolean | 0x08
  19480. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  19481. number_integer | -2147483648..2147483647 | int32 | 0x10
  19482. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  19483. number_unsigned | 0..2147483647 | int32 | 0x10
  19484. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  19485. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  19486. number_float | *any value* | double | 0x01
  19487. string | *any value* | string | 0x02
  19488. array | *any value* | document | 0x04
  19489. object | *any value* | document | 0x03
  19490. binary | *any value* | binary | 0x05
  19491. @warning The mapping is **incomplete**, since only JSON-objects (and things
  19492. contained therein) can be serialized to BSON.
  19493. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  19494. and the keys may not contain U+0000, since they are serialized a
  19495. zero-terminated c-strings.
  19496. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  19497. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  19498. @throw type_error.317 if `!j.is_object()`
  19499. @pre The input `j` is required to be an object: `j.is_object() == true`.
  19500. @note Any BSON output created via @ref to_bson can be successfully parsed
  19501. by @ref from_bson.
  19502. @param[in] j JSON value to serialize
  19503. @return BSON serialization as byte vector
  19504. @complexity Linear in the size of the JSON value @a j.
  19505. @liveexample{The example shows the serialization of a JSON value to a byte
  19506. vector in BSON format.,to_bson}
  19507. @sa http://bsonspec.org/spec.html
  19508. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  19509. analogous deserialization
  19510. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19511. related UBJSON format
  19512. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  19513. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19514. */
  19515. static std::vector<uint8_t> to_bson(const basic_json& j)
  19516. {
  19517. std::vector<uint8_t> result;
  19518. to_bson(j, result);
  19519. return result;
  19520. }
  19521. /*!
  19522. @brief Serializes the given JSON object `j` to BSON and forwards the
  19523. corresponding BSON-representation to the given output_adapter `o`.
  19524. @param j The JSON object to convert to BSON.
  19525. @param o The output adapter that receives the binary BSON representation.
  19526. @pre The input `j` shall be an object: `j.is_object() == true`
  19527. @sa @ref to_bson(const basic_json&)
  19528. */
  19529. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  19530. {
  19531. binary_writer<uint8_t>(o).write_bson(j);
  19532. }
  19533. /*!
  19534. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  19535. */
  19536. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  19537. {
  19538. binary_writer<char>(o).write_bson(j);
  19539. }
  19540. /*!
  19541. @brief create a JSON value from an input in CBOR format
  19542. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  19543. Binary Object Representation) serialization format.
  19544. The library maps CBOR types to JSON value types as follows:
  19545. CBOR type | JSON value type | first byte
  19546. ---------------------- | --------------- | ----------
  19547. Integer | number_unsigned | 0x00..0x17
  19548. Unsigned integer | number_unsigned | 0x18
  19549. Unsigned integer | number_unsigned | 0x19
  19550. Unsigned integer | number_unsigned | 0x1A
  19551. Unsigned integer | number_unsigned | 0x1B
  19552. Negative integer | number_integer | 0x20..0x37
  19553. Negative integer | number_integer | 0x38
  19554. Negative integer | number_integer | 0x39
  19555. Negative integer | number_integer | 0x3A
  19556. Negative integer | number_integer | 0x3B
  19557. Byte string | binary | 0x40..0x57
  19558. Byte string | binary | 0x58
  19559. Byte string | binary | 0x59
  19560. Byte string | binary | 0x5A
  19561. Byte string | binary | 0x5B
  19562. UTF-8 string | string | 0x60..0x77
  19563. UTF-8 string | string | 0x78
  19564. UTF-8 string | string | 0x79
  19565. UTF-8 string | string | 0x7A
  19566. UTF-8 string | string | 0x7B
  19567. UTF-8 string | string | 0x7F
  19568. array | array | 0x80..0x97
  19569. array | array | 0x98
  19570. array | array | 0x99
  19571. array | array | 0x9A
  19572. array | array | 0x9B
  19573. array | array | 0x9F
  19574. map | object | 0xA0..0xB7
  19575. map | object | 0xB8
  19576. map | object | 0xB9
  19577. map | object | 0xBA
  19578. map | object | 0xBB
  19579. map | object | 0xBF
  19580. False | `false` | 0xF4
  19581. True | `true` | 0xF5
  19582. Null | `null` | 0xF6
  19583. Half-Precision Float | number_float | 0xF9
  19584. Single-Precision Float | number_float | 0xFA
  19585. Double-Precision Float | number_float | 0xFB
  19586. @warning The mapping is **incomplete** in the sense that not all CBOR
  19587. types can be converted to a JSON value. The following CBOR types
  19588. are not supported and will yield parse errors (parse_error.112):
  19589. - date/time (0xC0..0xC1)
  19590. - bignum (0xC2..0xC3)
  19591. - decimal fraction (0xC4)
  19592. - bigfloat (0xC5)
  19593. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19594. - expected conversions (0xD5..0xD7)
  19595. - simple values (0xE0..0xF3, 0xF8)
  19596. - undefined (0xF7)
  19597. @warning CBOR allows map keys of any type, whereas JSON only allows
  19598. strings as keys in object values. Therefore, CBOR maps with keys
  19599. other than UTF-8 strings are rejected (parse_error.113).
  19600. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  19601. @ref from_cbor.
  19602. @param[in] i an input in CBOR format convertible to an input adapter
  19603. @param[in] strict whether to expect the input to be consumed until EOF
  19604. (true by default)
  19605. @param[in] allow_exceptions whether to throw exceptions in case of a
  19606. parse error (optional, true by default)
  19607. @return deserialized JSON value; in case of a parse error and
  19608. @a allow_exceptions set to `false`, the return value will be
  19609. value_t::discarded.
  19610. @throw parse_error.110 if the given input ends prematurely or the end of
  19611. file was not reached when @a strict was set to true
  19612. @throw parse_error.112 if unsupported features from CBOR were
  19613. used in the given input @a v or if the input is not valid CBOR
  19614. @throw parse_error.113 if a string was expected as map key, but not found
  19615. @complexity Linear in the size of the input @a i.
  19616. @liveexample{The example shows the deserialization of a byte vector in CBOR
  19617. format to a JSON value.,from_cbor}
  19618. @sa http://cbor.io
  19619. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  19620. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  19621. related MessagePack format
  19622. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19623. related UBJSON format
  19624. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19625. consume input adapters, removed start_index parameter, and added
  19626. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19627. since 3.2.0
  19628. */
  19629. template<typename InputType>
  19630. JSON_HEDLEY_WARN_UNUSED_RESULT
  19631. static basic_json from_cbor(InputType&& i,
  19632. const bool strict = true,
  19633. const bool allow_exceptions = true)
  19634. {
  19635. basic_json result;
  19636. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19637. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19638. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict);
  19639. return res ? result : basic_json(value_t::discarded);
  19640. }
  19641. /*!
  19642. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  19643. */
  19644. template<typename A1, typename A2,
  19645. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19646. JSON_HEDLEY_WARN_UNUSED_RESULT
  19647. static basic_json from_cbor(A1 && a1, A2 && a2,
  19648. const bool strict = true,
  19649. const bool allow_exceptions = true)
  19650. {
  19651. basic_json result;
  19652. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19653. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::cbor, &sdp, strict);
  19654. return res ? result : basic_json(value_t::discarded);
  19655. }
  19656. JSON_HEDLEY_WARN_UNUSED_RESULT
  19657. static basic_json from_cbor(detail::span_input_adapter&& i,
  19658. const bool strict = true,
  19659. const bool allow_exceptions = true)
  19660. {
  19661. basic_json result;
  19662. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19663. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::cbor, &sdp, strict);
  19664. return res ? result : basic_json(value_t::discarded);
  19665. }
  19666. /*!
  19667. @brief create a JSON value from an input in MessagePack format
  19668. Deserializes a given input @a i to a JSON value using the MessagePack
  19669. serialization format.
  19670. The library maps MessagePack types to JSON value types as follows:
  19671. MessagePack type | JSON value type | first byte
  19672. ---------------- | --------------- | ----------
  19673. positive fixint | number_unsigned | 0x00..0x7F
  19674. fixmap | object | 0x80..0x8F
  19675. fixarray | array | 0x90..0x9F
  19676. fixstr | string | 0xA0..0xBF
  19677. nil | `null` | 0xC0
  19678. false | `false` | 0xC2
  19679. true | `true` | 0xC3
  19680. float 32 | number_float | 0xCA
  19681. float 64 | number_float | 0xCB
  19682. uint 8 | number_unsigned | 0xCC
  19683. uint 16 | number_unsigned | 0xCD
  19684. uint 32 | number_unsigned | 0xCE
  19685. uint 64 | number_unsigned | 0xCF
  19686. int 8 | number_integer | 0xD0
  19687. int 16 | number_integer | 0xD1
  19688. int 32 | number_integer | 0xD2
  19689. int 64 | number_integer | 0xD3
  19690. str 8 | string | 0xD9
  19691. str 16 | string | 0xDA
  19692. str 32 | string | 0xDB
  19693. array 16 | array | 0xDC
  19694. array 32 | array | 0xDD
  19695. map 16 | object | 0xDE
  19696. map 32 | object | 0xDF
  19697. bin 8 | binary | 0xC4
  19698. bin 16 | binary | 0xC5
  19699. bin 32 | binary | 0xC6
  19700. ext 8 | binary | 0xC7
  19701. ext 16 | binary | 0xC8
  19702. ext 32 | binary | 0xC9
  19703. fixext 1 | binary | 0xD4
  19704. fixext 2 | binary | 0xD5
  19705. fixext 4 | binary | 0xD6
  19706. fixext 8 | binary | 0xD7
  19707. fixext 16 | binary | 0xD8
  19708. negative fixint | number_integer | 0xE0-0xFF
  19709. @note Any MessagePack output created @ref to_msgpack can be successfully
  19710. parsed by @ref from_msgpack.
  19711. @param[in] i an input in MessagePack format convertible to an input
  19712. adapter
  19713. @param[in] strict whether to expect the input to be consumed until EOF
  19714. (true by default)
  19715. @param[in] allow_exceptions whether to throw exceptions in case of a
  19716. parse error (optional, true by default)
  19717. @return deserialized JSON value; in case of a parse error and
  19718. @a allow_exceptions set to `false`, the return value will be
  19719. value_t::discarded.
  19720. @throw parse_error.110 if the given input ends prematurely or the end of
  19721. file was not reached when @a strict was set to true
  19722. @throw parse_error.112 if unsupported features from MessagePack were
  19723. used in the given input @a i or if the input is not valid MessagePack
  19724. @throw parse_error.113 if a string was expected as map key, but not found
  19725. @complexity Linear in the size of the input @a i.
  19726. @liveexample{The example shows the deserialization of a byte vector in
  19727. MessagePack format to a JSON value.,from_msgpack}
  19728. @sa http://msgpack.org
  19729. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  19730. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19731. related CBOR format
  19732. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  19733. the related UBJSON format
  19734. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19735. the related BSON format
  19736. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19737. consume input adapters, removed start_index parameter, and added
  19738. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19739. since 3.2.0
  19740. */
  19741. template<typename InputType>
  19742. JSON_HEDLEY_WARN_UNUSED_RESULT
  19743. static basic_json from_msgpack(InputType&& i,
  19744. const bool strict = true,
  19745. const bool allow_exceptions = true)
  19746. {
  19747. basic_json result;
  19748. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19749. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19750. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  19751. return res ? result : basic_json(value_t::discarded);
  19752. }
  19753. /*!
  19754. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  19755. */
  19756. template<typename A1, typename A2,
  19757. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19758. JSON_HEDLEY_WARN_UNUSED_RESULT
  19759. static basic_json from_msgpack(A1 && a1, A2 && a2,
  19760. const bool strict = true,
  19761. const bool allow_exceptions = true)
  19762. {
  19763. basic_json result;
  19764. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19765. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::msgpack, &sdp, strict);
  19766. return res ? result : basic_json(value_t::discarded);
  19767. }
  19768. JSON_HEDLEY_WARN_UNUSED_RESULT
  19769. static basic_json from_msgpack(detail::span_input_adapter&& i,
  19770. const bool strict = true,
  19771. const bool allow_exceptions = true)
  19772. {
  19773. basic_json result;
  19774. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19775. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::msgpack, &sdp, strict);
  19776. return res ? result : basic_json(value_t::discarded);
  19777. }
  19778. /*!
  19779. @brief create a JSON value from an input in UBJSON format
  19780. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  19781. Binary JSON) serialization format.
  19782. The library maps UBJSON types to JSON value types as follows:
  19783. UBJSON type | JSON value type | marker
  19784. ----------- | --------------------------------------- | ------
  19785. no-op | *no value, next value is read* | `N`
  19786. null | `null` | `Z`
  19787. false | `false` | `F`
  19788. true | `true` | `T`
  19789. float32 | number_float | `d`
  19790. float64 | number_float | `D`
  19791. uint8 | number_unsigned | `U`
  19792. int8 | number_integer | `i`
  19793. int16 | number_integer | `I`
  19794. int32 | number_integer | `l`
  19795. int64 | number_integer | `L`
  19796. string | string | `S`
  19797. char | string | `C`
  19798. array | array (optimized values are supported) | `[`
  19799. object | object (optimized values are supported) | `{`
  19800. @note The mapping is **complete** in the sense that any UBJSON value can
  19801. be converted to a JSON value.
  19802. @param[in] i an input in UBJSON format convertible to an input adapter
  19803. @param[in] strict whether to expect the input to be consumed until EOF
  19804. (true by default)
  19805. @param[in] allow_exceptions whether to throw exceptions in case of a
  19806. parse error (optional, true by default)
  19807. @return deserialized JSON value; in case of a parse error and
  19808. @a allow_exceptions set to `false`, the return value will be
  19809. value_t::discarded.
  19810. @throw parse_error.110 if the given input ends prematurely or the end of
  19811. file was not reached when @a strict was set to true
  19812. @throw parse_error.112 if a parse error occurs
  19813. @throw parse_error.113 if a string could not be parsed successfully
  19814. @complexity Linear in the size of the input @a i.
  19815. @liveexample{The example shows the deserialization of a byte vector in
  19816. UBJSON format to a JSON value.,from_ubjson}
  19817. @sa http://ubjson.org
  19818. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19819. analogous serialization
  19820. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19821. related CBOR format
  19822. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  19823. the related MessagePack format
  19824. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19825. the related BSON format
  19826. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  19827. */
  19828. template<typename InputType>
  19829. JSON_HEDLEY_WARN_UNUSED_RESULT
  19830. static basic_json from_ubjson(InputType&& i,
  19831. const bool strict = true,
  19832. const bool allow_exceptions = true)
  19833. {
  19834. basic_json result;
  19835. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19836. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19837. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  19838. return res ? result : basic_json(value_t::discarded);
  19839. }
  19840. /*!
  19841. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  19842. */
  19843. template<typename A1, typename A2,
  19844. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19845. JSON_HEDLEY_WARN_UNUSED_RESULT
  19846. static basic_json from_ubjson(A1 && a1, A2 && a2,
  19847. const bool strict = true,
  19848. const bool allow_exceptions = true)
  19849. {
  19850. basic_json result;
  19851. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19852. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::ubjson, &sdp, strict);
  19853. return res ? result : basic_json(value_t::discarded);
  19854. }
  19855. static basic_json from_ubjson(detail::span_input_adapter&& i,
  19856. const bool strict = true,
  19857. const bool allow_exceptions = true)
  19858. {
  19859. basic_json result;
  19860. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19861. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::ubjson, &sdp, strict);
  19862. return res ? result : basic_json(value_t::discarded);
  19863. }
  19864. /*!
  19865. @brief Create a JSON value from an input in BSON format
  19866. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  19867. serialization format.
  19868. The library maps BSON record types to JSON value types as follows:
  19869. BSON type | BSON marker byte | JSON value type
  19870. --------------- | ---------------- | ---------------------------
  19871. double | 0x01 | number_float
  19872. string | 0x02 | string
  19873. document | 0x03 | object
  19874. array | 0x04 | array
  19875. binary | 0x05 | still unsupported
  19876. undefined | 0x06 | still unsupported
  19877. ObjectId | 0x07 | still unsupported
  19878. boolean | 0x08 | boolean
  19879. UTC Date-Time | 0x09 | still unsupported
  19880. null | 0x0A | null
  19881. Regular Expr. | 0x0B | still unsupported
  19882. DB Pointer | 0x0C | still unsupported
  19883. JavaScript Code | 0x0D | still unsupported
  19884. Symbol | 0x0E | still unsupported
  19885. JavaScript Code | 0x0F | still unsupported
  19886. int32 | 0x10 | number_integer
  19887. Timestamp | 0x11 | still unsupported
  19888. 128-bit decimal float | 0x13 | still unsupported
  19889. Max Key | 0x7F | still unsupported
  19890. Min Key | 0xFF | still unsupported
  19891. @warning The mapping is **incomplete**. The unsupported mappings
  19892. are indicated in the table above.
  19893. @param[in] i an input in BSON format convertible to an input adapter
  19894. @param[in] strict whether to expect the input to be consumed until EOF
  19895. (true by default)
  19896. @param[in] allow_exceptions whether to throw exceptions in case of a
  19897. parse error (optional, true by default)
  19898. @return deserialized JSON value; in case of a parse error and
  19899. @a allow_exceptions set to `false`, the return value will be
  19900. value_t::discarded.
  19901. @throw parse_error.114 if an unsupported BSON record type is encountered
  19902. @complexity Linear in the size of the input @a i.
  19903. @liveexample{The example shows the deserialization of a byte vector in
  19904. BSON format to a JSON value.,from_bson}
  19905. @sa http://bsonspec.org/spec.html
  19906. @sa @ref to_bson(const basic_json&) for the analogous serialization
  19907. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19908. related CBOR format
  19909. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  19910. the related MessagePack format
  19911. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19912. related UBJSON format
  19913. */
  19914. template<typename InputType>
  19915. JSON_HEDLEY_WARN_UNUSED_RESULT
  19916. static basic_json from_bson(InputType&& i,
  19917. const bool strict = true,
  19918. const bool allow_exceptions = true)
  19919. {
  19920. basic_json result;
  19921. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19922. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19923. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  19924. return res ? result : basic_json(value_t::discarded);
  19925. }
  19926. /*!
  19927. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  19928. */
  19929. template<typename A1, typename A2,
  19930. detail::enable_if_t<std::is_constructible<detail::span_input_adapter, A1, A2>::value, int> = 0>
  19931. JSON_HEDLEY_WARN_UNUSED_RESULT
  19932. static basic_json from_bson(A1 && a1, A2 && a2,
  19933. const bool strict = true,
  19934. const bool allow_exceptions = true)
  19935. {
  19936. basic_json result;
  19937. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19938. const bool res = binary_reader<detail::input_buffer_adapter>(detail::span_input_adapter(std::forward<A1>(a1), std::forward<A2>(a2)).get()).sax_parse(input_format_t::bson, &sdp, strict);
  19939. return res ? result : basic_json(value_t::discarded);
  19940. }
  19941. JSON_HEDLEY_WARN_UNUSED_RESULT
  19942. static basic_json from_bson(detail::span_input_adapter&& i,
  19943. const bool strict = true,
  19944. const bool allow_exceptions = true)
  19945. {
  19946. basic_json result;
  19947. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19948. const bool res = binary_reader<detail::input_buffer_adapter>(i.get()).sax_parse(input_format_t::bson, &sdp, strict);
  19949. return res ? result : basic_json(value_t::discarded);
  19950. }
  19951. /// @}
  19952. //////////////////////////
  19953. // JSON Pointer support //
  19954. //////////////////////////
  19955. /// @name JSON Pointer functions
  19956. /// @{
  19957. /*!
  19958. @brief access specified element via JSON Pointer
  19959. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  19960. No bound checking is performed. Similar to @ref operator[](const typename
  19961. object_t::key_type&), `null` values are created in arrays and objects if
  19962. necessary.
  19963. In particular:
  19964. - If the JSON pointer points to an object key that does not exist, it
  19965. is created an filled with a `null` value before a reference to it
  19966. is returned.
  19967. - If the JSON pointer points to an array index that does not exist, it
  19968. is created an filled with a `null` value before a reference to it
  19969. is returned. All indices between the current maximum and the given
  19970. index are also filled with `null`.
  19971. - The special value `-` is treated as a synonym for the index past the
  19972. end.
  19973. @param[in] ptr a JSON pointer
  19974. @return reference to the element pointed to by @a ptr
  19975. @complexity Constant.
  19976. @throw parse_error.106 if an array index begins with '0'
  19977. @throw parse_error.109 if an array index was not a number
  19978. @throw out_of_range.404 if the JSON pointer can not be resolved
  19979. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  19980. @since version 2.0.0
  19981. */
  19982. reference operator[](const json_pointer& ptr)
  19983. {
  19984. return ptr.get_unchecked(this);
  19985. }
  19986. /*!
  19987. @brief access specified element via JSON Pointer
  19988. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  19989. No bound checking is performed. The function does not change the JSON
  19990. value; no `null` values are created. In particular, the special value
  19991. `-` yields an exception.
  19992. @param[in] ptr JSON pointer to the desired element
  19993. @return const reference to the element pointed to by @a ptr
  19994. @complexity Constant.
  19995. @throw parse_error.106 if an array index begins with '0'
  19996. @throw parse_error.109 if an array index was not a number
  19997. @throw out_of_range.402 if the array index '-' is used
  19998. @throw out_of_range.404 if the JSON pointer can not be resolved
  19999. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  20000. @since version 2.0.0
  20001. */
  20002. const_reference operator[](const json_pointer& ptr) const
  20003. {
  20004. return ptr.get_unchecked(this);
  20005. }
  20006. /*!
  20007. @brief access specified element via JSON Pointer
  20008. Returns a reference to the element at with specified JSON pointer @a ptr,
  20009. with bounds checking.
  20010. @param[in] ptr JSON pointer to the desired element
  20011. @return reference to the element pointed to by @a ptr
  20012. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  20013. begins with '0'. See example below.
  20014. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  20015. is not a number. See example below.
  20016. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  20017. is out of range. See example below.
  20018. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  20019. pointer @a ptr. As `at` provides checked access (and no elements are
  20020. implicitly inserted), the index '-' is always invalid. See example below.
  20021. @throw out_of_range.403 if the JSON pointer describes a key of an object
  20022. which cannot be found. See example below.
  20023. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  20024. See example below.
  20025. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  20026. changes in the JSON value.
  20027. @complexity Constant.
  20028. @since version 2.0.0
  20029. @liveexample{The behavior is shown in the example.,at_json_pointer}
  20030. */
  20031. reference at(const json_pointer& ptr)
  20032. {
  20033. return ptr.get_checked(this);
  20034. }
  20035. /*!
  20036. @brief access specified element via JSON Pointer
  20037. Returns a const reference to the element at with specified JSON pointer @a
  20038. ptr, with bounds checking.
  20039. @param[in] ptr JSON pointer to the desired element
  20040. @return reference to the element pointed to by @a ptr
  20041. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  20042. begins with '0'. See example below.
  20043. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  20044. is not a number. See example below.
  20045. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  20046. is out of range. See example below.
  20047. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  20048. pointer @a ptr. As `at` provides checked access (and no elements are
  20049. implicitly inserted), the index '-' is always invalid. See example below.
  20050. @throw out_of_range.403 if the JSON pointer describes a key of an object
  20051. which cannot be found. See example below.
  20052. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  20053. See example below.
  20054. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  20055. changes in the JSON value.
  20056. @complexity Constant.
  20057. @since version 2.0.0
  20058. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  20059. */
  20060. const_reference at(const json_pointer& ptr) const
  20061. {
  20062. return ptr.get_checked(this);
  20063. }
  20064. /*!
  20065. @brief return flattened JSON value
  20066. The function creates a JSON object whose keys are JSON pointers (see [RFC
  20067. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  20068. primitive. The original JSON value can be restored using the @ref
  20069. unflatten() function.
  20070. @return an object that maps JSON pointers to primitive values
  20071. @note Empty objects and arrays are flattened to `null` and will not be
  20072. reconstructed correctly by the @ref unflatten() function.
  20073. @complexity Linear in the size the JSON value.
  20074. @liveexample{The following code shows how a JSON object is flattened to an
  20075. object whose keys consist of JSON pointers.,flatten}
  20076. @sa @ref unflatten() for the reverse function
  20077. @since version 2.0.0
  20078. */
  20079. basic_json flatten() const
  20080. {
  20081. basic_json result(value_t::object);
  20082. json_pointer::flatten("", *this, result);
  20083. return result;
  20084. }
  20085. /*!
  20086. @brief unflatten a previously flattened JSON value
  20087. The function restores the arbitrary nesting of a JSON value that has been
  20088. flattened before using the @ref flatten() function. The JSON value must
  20089. meet certain constraints:
  20090. 1. The value must be an object.
  20091. 2. The keys must be JSON pointers (see
  20092. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  20093. 3. The mapped values must be primitive JSON types.
  20094. @return the original JSON from a flattened version
  20095. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  20096. values and can not unflattened to their original type. Apart from
  20097. this example, for a JSON value `j`, the following is always true:
  20098. `j == j.flatten().unflatten()`.
  20099. @complexity Linear in the size the JSON value.
  20100. @throw type_error.314 if value is not an object
  20101. @throw type_error.315 if object values are not primitive
  20102. @liveexample{The following code shows how a flattened JSON object is
  20103. unflattened into the original nested JSON object.,unflatten}
  20104. @sa @ref flatten() for the reverse function
  20105. @since version 2.0.0
  20106. */
  20107. basic_json unflatten() const
  20108. {
  20109. return json_pointer::unflatten(*this);
  20110. }
  20111. /// @}
  20112. //////////////////////////
  20113. // JSON Patch functions //
  20114. //////////////////////////
  20115. /// @name JSON Patch functions
  20116. /// @{
  20117. /*!
  20118. @brief applies a JSON patch
  20119. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  20120. expressing a sequence of operations to apply to a JSON) document. With
  20121. this function, a JSON Patch is applied to the current JSON value by
  20122. executing all operations from the patch.
  20123. @param[in] json_patch JSON patch document
  20124. @return patched document
  20125. @note The application of a patch is atomic: Either all operations succeed
  20126. and the patched document is returned or an exception is thrown. In
  20127. any case, the original value is not changed: the patch is applied
  20128. to a copy of the value.
  20129. @throw parse_error.104 if the JSON patch does not consist of an array of
  20130. objects
  20131. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  20132. attributes are missing); example: `"operation add must have member path"`
  20133. @throw out_of_range.401 if an array index is out of range.
  20134. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  20135. resolved successfully in the current JSON value; example: `"key baz not
  20136. found"`
  20137. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  20138. "move")
  20139. @throw other_error.501 if "test" operation was unsuccessful
  20140. @complexity Linear in the size of the JSON value and the length of the
  20141. JSON patch. As usually only a fraction of the JSON value is affected by
  20142. the patch, the complexity can usually be neglected.
  20143. @liveexample{The following code shows how a JSON patch is applied to a
  20144. value.,patch}
  20145. @sa @ref diff -- create a JSON patch by comparing two JSON values
  20146. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20147. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  20148. @since version 2.0.0
  20149. */
  20150. basic_json patch(const basic_json& json_patch) const
  20151. {
  20152. // make a working copy to apply the patch to
  20153. basic_json result = *this;
  20154. // the valid JSON Patch operations
  20155. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  20156. const auto get_op = [](const std::string & op)
  20157. {
  20158. if (op == "add")
  20159. {
  20160. return patch_operations::add;
  20161. }
  20162. if (op == "remove")
  20163. {
  20164. return patch_operations::remove;
  20165. }
  20166. if (op == "replace")
  20167. {
  20168. return patch_operations::replace;
  20169. }
  20170. if (op == "move")
  20171. {
  20172. return patch_operations::move;
  20173. }
  20174. if (op == "copy")
  20175. {
  20176. return patch_operations::copy;
  20177. }
  20178. if (op == "test")
  20179. {
  20180. return patch_operations::test;
  20181. }
  20182. return patch_operations::invalid;
  20183. };
  20184. // wrapper for "add" operation; add value at ptr
  20185. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  20186. {
  20187. // adding to the root of the target document means replacing it
  20188. if (ptr.empty())
  20189. {
  20190. result = val;
  20191. return;
  20192. }
  20193. // make sure the top element of the pointer exists
  20194. json_pointer top_pointer = ptr.top();
  20195. if (top_pointer != ptr)
  20196. {
  20197. result.at(top_pointer);
  20198. }
  20199. // get reference to parent of JSON pointer ptr
  20200. const auto last_path = ptr.back();
  20201. ptr.pop_back();
  20202. basic_json& parent = result[ptr];
  20203. switch (parent.m_type)
  20204. {
  20205. case value_t::null:
  20206. case value_t::object:
  20207. {
  20208. // use operator[] to add value
  20209. parent[last_path] = val;
  20210. break;
  20211. }
  20212. case value_t::array:
  20213. {
  20214. if (last_path == "-")
  20215. {
  20216. // special case: append to back
  20217. parent.push_back(val);
  20218. }
  20219. else
  20220. {
  20221. const auto idx = json_pointer::array_index(last_path);
  20222. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  20223. {
  20224. // avoid undefined behavior
  20225. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  20226. }
  20227. // default case: insert add offset
  20228. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  20229. }
  20230. break;
  20231. }
  20232. // if there exists a parent it cannot be primitive
  20233. default: // LCOV_EXCL_LINE
  20234. assert(false); // LCOV_EXCL_LINE
  20235. }
  20236. };
  20237. // wrapper for "remove" operation; remove value at ptr
  20238. const auto operation_remove = [&result](json_pointer & ptr)
  20239. {
  20240. // get reference to parent of JSON pointer ptr
  20241. const auto last_path = ptr.back();
  20242. ptr.pop_back();
  20243. basic_json& parent = result.at(ptr);
  20244. // remove child
  20245. if (parent.is_object())
  20246. {
  20247. // perform range check
  20248. auto it = parent.find(last_path);
  20249. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  20250. {
  20251. parent.erase(it);
  20252. }
  20253. else
  20254. {
  20255. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  20256. }
  20257. }
  20258. else if (parent.is_array())
  20259. {
  20260. // note erase performs range check
  20261. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  20262. }
  20263. };
  20264. // type check: top level value must be an array
  20265. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  20266. {
  20267. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20268. }
  20269. // iterate and apply the operations
  20270. for (const auto& val : json_patch)
  20271. {
  20272. // wrapper to get a value for an operation
  20273. const auto get_value = [&val](const std::string & op,
  20274. const std::string & member,
  20275. bool string_type) -> basic_json &
  20276. {
  20277. // find value
  20278. auto it = val.m_value.object->find(member);
  20279. // context-sensitive error message
  20280. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  20281. // check if desired value is present
  20282. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  20283. {
  20284. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  20285. }
  20286. // check if result is of type string
  20287. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  20288. {
  20289. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  20290. }
  20291. // no error: return value
  20292. return it->second;
  20293. };
  20294. // type check: every element of the array must be an object
  20295. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  20296. {
  20297. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20298. }
  20299. // collect mandatory members
  20300. const std::string op = get_value("op", "op", true);
  20301. const std::string path = get_value(op, "path", true);
  20302. json_pointer ptr(path);
  20303. switch (get_op(op))
  20304. {
  20305. case patch_operations::add:
  20306. {
  20307. operation_add(ptr, get_value("add", "value", false));
  20308. break;
  20309. }
  20310. case patch_operations::remove:
  20311. {
  20312. operation_remove(ptr);
  20313. break;
  20314. }
  20315. case patch_operations::replace:
  20316. {
  20317. // the "path" location must exist - use at()
  20318. result.at(ptr) = get_value("replace", "value", false);
  20319. break;
  20320. }
  20321. case patch_operations::move:
  20322. {
  20323. const std::string from_path = get_value("move", "from", true);
  20324. json_pointer from_ptr(from_path);
  20325. // the "from" location must exist - use at()
  20326. basic_json v = result.at(from_ptr);
  20327. // The move operation is functionally identical to a
  20328. // "remove" operation on the "from" location, followed
  20329. // immediately by an "add" operation at the target
  20330. // location with the value that was just removed.
  20331. operation_remove(from_ptr);
  20332. operation_add(ptr, v);
  20333. break;
  20334. }
  20335. case patch_operations::copy:
  20336. {
  20337. const std::string from_path = get_value("copy", "from", true);
  20338. const json_pointer from_ptr(from_path);
  20339. // the "from" location must exist - use at()
  20340. basic_json v = result.at(from_ptr);
  20341. // The copy is functionally identical to an "add"
  20342. // operation at the target location using the value
  20343. // specified in the "from" member.
  20344. operation_add(ptr, v);
  20345. break;
  20346. }
  20347. case patch_operations::test:
  20348. {
  20349. bool success = false;
  20350. JSON_TRY
  20351. {
  20352. // check if "value" matches the one at "path"
  20353. // the "path" location must exist - use at()
  20354. success = (result.at(ptr) == get_value("test", "value", false));
  20355. }
  20356. JSON_INTERNAL_CATCH (out_of_range&)
  20357. {
  20358. // ignore out of range errors: success remains false
  20359. }
  20360. // throw an exception if test fails
  20361. if (JSON_HEDLEY_UNLIKELY(not success))
  20362. {
  20363. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  20364. }
  20365. break;
  20366. }
  20367. default:
  20368. {
  20369. // op must be "add", "remove", "replace", "move", "copy", or
  20370. // "test"
  20371. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  20372. }
  20373. }
  20374. }
  20375. return result;
  20376. }
  20377. /*!
  20378. @brief creates a diff as a JSON patch
  20379. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  20380. be changed into the value @a target by calling @ref patch function.
  20381. @invariant For two JSON values @a source and @a target, the following code
  20382. yields always `true`:
  20383. @code {.cpp}
  20384. source.patch(diff(source, target)) == target;
  20385. @endcode
  20386. @note Currently, only `remove`, `add`, and `replace` operations are
  20387. generated.
  20388. @param[in] source JSON value to compare from
  20389. @param[in] target JSON value to compare against
  20390. @param[in] path helper value to create JSON pointers
  20391. @return a JSON patch to convert the @a source to @a target
  20392. @complexity Linear in the lengths of @a source and @a target.
  20393. @liveexample{The following code shows how a JSON patch is created as a
  20394. diff for two JSON values.,diff}
  20395. @sa @ref patch -- apply a JSON patch
  20396. @sa @ref merge_patch -- apply a JSON Merge Patch
  20397. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20398. @since version 2.0.0
  20399. */
  20400. JSON_HEDLEY_WARN_UNUSED_RESULT
  20401. static basic_json diff(const basic_json& source, const basic_json& target,
  20402. const std::string& path = "")
  20403. {
  20404. // the patch
  20405. basic_json result(value_t::array);
  20406. // if the values are the same, return empty patch
  20407. if (source == target)
  20408. {
  20409. return result;
  20410. }
  20411. if (source.type() != target.type())
  20412. {
  20413. // different types: replace value
  20414. result.push_back(
  20415. {
  20416. {"op", "replace"}, {"path", path}, {"value", target}
  20417. });
  20418. return result;
  20419. }
  20420. switch (source.type())
  20421. {
  20422. case value_t::array:
  20423. {
  20424. // first pass: traverse common elements
  20425. std::size_t i = 0;
  20426. while (i < source.size() and i < target.size())
  20427. {
  20428. // recursive call to compare array values at index i
  20429. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  20430. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20431. ++i;
  20432. }
  20433. // i now reached the end of at least one array
  20434. // in a second pass, traverse the remaining elements
  20435. // remove my remaining elements
  20436. const auto end_index = static_cast<difference_type>(result.size());
  20437. while (i < source.size())
  20438. {
  20439. // add operations in reverse order to avoid invalid
  20440. // indices
  20441. result.insert(result.begin() + end_index, object(
  20442. {
  20443. {"op", "remove"},
  20444. {"path", path + "/" + std::to_string(i)}
  20445. }));
  20446. ++i;
  20447. }
  20448. // add other remaining elements
  20449. while (i < target.size())
  20450. {
  20451. result.push_back(
  20452. {
  20453. {"op", "add"},
  20454. {"path", path + "/-"},
  20455. {"value", target[i]}
  20456. });
  20457. ++i;
  20458. }
  20459. break;
  20460. }
  20461. case value_t::object:
  20462. {
  20463. // first pass: traverse this object's elements
  20464. for (auto it = source.cbegin(); it != source.cend(); ++it)
  20465. {
  20466. // escape the key name to be used in a JSON patch
  20467. const auto key = json_pointer::escape(it.key());
  20468. if (target.find(it.key()) != target.end())
  20469. {
  20470. // recursive call to compare object values at key it
  20471. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  20472. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20473. }
  20474. else
  20475. {
  20476. // found a key that is not in o -> remove it
  20477. result.push_back(object(
  20478. {
  20479. {"op", "remove"}, {"path", path + "/" + key}
  20480. }));
  20481. }
  20482. }
  20483. // second pass: traverse other object's elements
  20484. for (auto it = target.cbegin(); it != target.cend(); ++it)
  20485. {
  20486. if (source.find(it.key()) == source.end())
  20487. {
  20488. // found a key that is not in this -> add it
  20489. const auto key = json_pointer::escape(it.key());
  20490. result.push_back(
  20491. {
  20492. {"op", "add"}, {"path", path + "/" + key},
  20493. {"value", it.value()}
  20494. });
  20495. }
  20496. }
  20497. break;
  20498. }
  20499. default:
  20500. {
  20501. // both primitive type: replace value
  20502. result.push_back(
  20503. {
  20504. {"op", "replace"}, {"path", path}, {"value", target}
  20505. });
  20506. break;
  20507. }
  20508. }
  20509. return result;
  20510. }
  20511. /// @}
  20512. ////////////////////////////////
  20513. // JSON Merge Patch functions //
  20514. ////////////////////////////////
  20515. /// @name JSON Merge Patch functions
  20516. /// @{
  20517. /*!
  20518. @brief applies a JSON Merge Patch
  20519. The merge patch format is primarily intended for use with the HTTP PATCH
  20520. method as a means of describing a set of modifications to a target
  20521. resource's content. This function applies a merge patch to the current
  20522. JSON value.
  20523. The function implements the following algorithm from Section 2 of
  20524. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  20525. ```
  20526. define MergePatch(Target, Patch):
  20527. if Patch is an Object:
  20528. if Target is not an Object:
  20529. Target = {} // Ignore the contents and set it to an empty Object
  20530. for each Name/Value pair in Patch:
  20531. if Value is null:
  20532. if Name exists in Target:
  20533. remove the Name/Value pair from Target
  20534. else:
  20535. Target[Name] = MergePatch(Target[Name], Value)
  20536. return Target
  20537. else:
  20538. return Patch
  20539. ```
  20540. Thereby, `Target` is the current object; that is, the patch is applied to
  20541. the current value.
  20542. @param[in] apply_patch the patch to apply
  20543. @complexity Linear in the lengths of @a patch.
  20544. @liveexample{The following code shows how a JSON Merge Patch is applied to
  20545. a JSON document.,merge_patch}
  20546. @sa @ref patch -- apply a JSON patch
  20547. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  20548. @since version 3.0.0
  20549. */
  20550. void merge_patch(const basic_json& apply_patch)
  20551. {
  20552. if (apply_patch.is_object())
  20553. {
  20554. if (not is_object())
  20555. {
  20556. *this = object();
  20557. }
  20558. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  20559. {
  20560. if (it.value().is_null())
  20561. {
  20562. erase(it.key());
  20563. }
  20564. else
  20565. {
  20566. operator[](it.key()).merge_patch(it.value());
  20567. }
  20568. }
  20569. }
  20570. else
  20571. {
  20572. *this = apply_patch;
  20573. }
  20574. }
  20575. /// @}
  20576. };
  20577. /*!
  20578. @brief user-defined to_string function for JSON values
  20579. This function implements a user-defined to_string for JSON objects.
  20580. @param[in] j a JSON object
  20581. @return a std::string object
  20582. */
  20583. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20584. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  20585. {
  20586. return j.dump();
  20587. }
  20588. } // namespace nlohmann
  20589. ///////////////////////
  20590. // nonmember support //
  20591. ///////////////////////
  20592. // specialization of std::swap, and std::hash
  20593. namespace std
  20594. {
  20595. /// hash value for JSON objects
  20596. template<>
  20597. struct hash<nlohmann::json>
  20598. {
  20599. /*!
  20600. @brief return a hash value for a JSON object
  20601. @since version 1.0.0
  20602. */
  20603. std::size_t operator()(const nlohmann::json& j) const
  20604. {
  20605. // a naive hashing via the string representation
  20606. const auto& h = hash<nlohmann::json::string_t>();
  20607. return h(j.dump());
  20608. }
  20609. };
  20610. /// specialization for std::less<value_t>
  20611. /// @note: do not remove the space after '<',
  20612. /// see https://github.com/nlohmann/json/pull/679
  20613. template<>
  20614. struct less<::nlohmann::detail::value_t>
  20615. {
  20616. /*!
  20617. @brief compare two value_t enum values
  20618. @since version 3.0.0
  20619. */
  20620. bool operator()(nlohmann::detail::value_t lhs,
  20621. nlohmann::detail::value_t rhs) const noexcept
  20622. {
  20623. return nlohmann::detail::operator<(lhs, rhs);
  20624. }
  20625. };
  20626. /*!
  20627. @brief exchanges the values of two JSON objects
  20628. @since version 1.0.0
  20629. */
  20630. template<>
  20631. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  20632. is_nothrow_move_constructible<nlohmann::json>::value and
  20633. is_nothrow_move_assignable<nlohmann::json>::value
  20634. )
  20635. {
  20636. j1.swap(j2);
  20637. }
  20638. } // namespace std
  20639. /*!
  20640. @brief user-defined string literal for JSON values
  20641. This operator implements a user-defined string literal for JSON objects. It
  20642. can be used by adding `"_json"` to a string literal and returns a JSON object
  20643. if no parse error occurred.
  20644. @param[in] s a string representation of a JSON object
  20645. @param[in] n the length of string @a s
  20646. @return a JSON object
  20647. @since version 1.0.0
  20648. */
  20649. JSON_HEDLEY_NON_NULL(1)
  20650. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  20651. {
  20652. return nlohmann::json::parse(s, s + n);
  20653. }
  20654. /*!
  20655. @brief user-defined string literal for JSON pointer
  20656. This operator implements a user-defined string literal for JSON Pointers. It
  20657. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  20658. object if no parse error occurred.
  20659. @param[in] s a string representation of a JSON Pointer
  20660. @param[in] n the length of string @a s
  20661. @return a JSON pointer object
  20662. @since version 2.0.0
  20663. */
  20664. JSON_HEDLEY_NON_NULL(1)
  20665. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  20666. {
  20667. return nlohmann::json::json_pointer(std::string(s, n));
  20668. }
  20669. // #include <nlohmann/detail/macro_unscope.hpp>
  20670. // restore GCC/clang diagnostic settings
  20671. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  20672. #pragma GCC diagnostic pop
  20673. #endif
  20674. #if defined(__clang__)
  20675. #pragma GCC diagnostic pop
  20676. #endif
  20677. // clean up
  20678. #undef JSON_INTERNAL_CATCH
  20679. #undef JSON_CATCH
  20680. #undef JSON_THROW
  20681. #undef JSON_TRY
  20682. #undef JSON_HAS_CPP_14
  20683. #undef JSON_HAS_CPP_17
  20684. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20685. #undef NLOHMANN_BASIC_JSON_TPL
  20686. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  20687. #undef JSON_HEDLEY_ALWAYS_INLINE
  20688. #undef JSON_HEDLEY_ARM_VERSION
  20689. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  20690. #undef JSON_HEDLEY_ARRAY_PARAM
  20691. #undef JSON_HEDLEY_ASSUME
  20692. #undef JSON_HEDLEY_BEGIN_C_DECLS
  20693. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  20694. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  20695. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  20696. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  20697. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  20698. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  20699. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  20700. #undef JSON_HEDLEY_COMPCERT_VERSION
  20701. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  20702. #undef JSON_HEDLEY_CONCAT
  20703. #undef JSON_HEDLEY_CONCAT3
  20704. #undef JSON_HEDLEY_CONCAT3_EX
  20705. #undef JSON_HEDLEY_CONCAT_EX
  20706. #undef JSON_HEDLEY_CONST
  20707. #undef JSON_HEDLEY_CONSTEXPR
  20708. #undef JSON_HEDLEY_CONST_CAST
  20709. #undef JSON_HEDLEY_CPP_CAST
  20710. #undef JSON_HEDLEY_CRAY_VERSION
  20711. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  20712. #undef JSON_HEDLEY_C_DECL
  20713. #undef JSON_HEDLEY_DEPRECATED
  20714. #undef JSON_HEDLEY_DEPRECATED_FOR
  20715. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  20716. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  20717. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  20718. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  20719. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  20720. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  20721. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  20722. #undef JSON_HEDLEY_DMC_VERSION
  20723. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  20724. #undef JSON_HEDLEY_EMPTY_BASES
  20725. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  20726. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  20727. #undef JSON_HEDLEY_END_C_DECLS
  20728. #undef JSON_HEDLEY_FLAGS
  20729. #undef JSON_HEDLEY_FLAGS_CAST
  20730. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  20731. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  20732. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  20733. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  20734. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  20735. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  20736. #undef JSON_HEDLEY_GCC_HAS_WARNING
  20737. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  20738. #undef JSON_HEDLEY_GCC_VERSION
  20739. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  20740. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  20741. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  20742. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  20743. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  20744. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  20745. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  20746. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  20747. #undef JSON_HEDLEY_GNUC_VERSION
  20748. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  20749. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  20750. #undef JSON_HEDLEY_HAS_BUILTIN
  20751. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  20752. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  20753. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  20754. #undef JSON_HEDLEY_HAS_EXTENSION
  20755. #undef JSON_HEDLEY_HAS_FEATURE
  20756. #undef JSON_HEDLEY_HAS_WARNING
  20757. #undef JSON_HEDLEY_IAR_VERSION
  20758. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  20759. #undef JSON_HEDLEY_IBM_VERSION
  20760. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  20761. #undef JSON_HEDLEY_IMPORT
  20762. #undef JSON_HEDLEY_INLINE
  20763. #undef JSON_HEDLEY_INTEL_VERSION
  20764. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  20765. #undef JSON_HEDLEY_IS_CONSTANT
  20766. #undef JSON_HEDLEY_IS_CONSTEXPR_
  20767. #undef JSON_HEDLEY_LIKELY
  20768. #undef JSON_HEDLEY_MALLOC
  20769. #undef JSON_HEDLEY_MESSAGE
  20770. #undef JSON_HEDLEY_MSVC_VERSION
  20771. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  20772. #undef JSON_HEDLEY_NEVER_INLINE
  20773. #undef JSON_HEDLEY_NON_NULL
  20774. #undef JSON_HEDLEY_NO_ESCAPE
  20775. #undef JSON_HEDLEY_NO_RETURN
  20776. #undef JSON_HEDLEY_NO_THROW
  20777. #undef JSON_HEDLEY_NULL
  20778. #undef JSON_HEDLEY_PELLES_VERSION
  20779. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  20780. #undef JSON_HEDLEY_PGI_VERSION
  20781. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  20782. #undef JSON_HEDLEY_PREDICT
  20783. #undef JSON_HEDLEY_PRINTF_FORMAT
  20784. #undef JSON_HEDLEY_PRIVATE
  20785. #undef JSON_HEDLEY_PUBLIC
  20786. #undef JSON_HEDLEY_PURE
  20787. #undef JSON_HEDLEY_REINTERPRET_CAST
  20788. #undef JSON_HEDLEY_REQUIRE
  20789. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  20790. #undef JSON_HEDLEY_REQUIRE_MSG
  20791. #undef JSON_HEDLEY_RESTRICT
  20792. #undef JSON_HEDLEY_RETURNS_NON_NULL
  20793. #undef JSON_HEDLEY_SENTINEL
  20794. #undef JSON_HEDLEY_STATIC_ASSERT
  20795. #undef JSON_HEDLEY_STATIC_CAST
  20796. #undef JSON_HEDLEY_STRINGIFY
  20797. #undef JSON_HEDLEY_STRINGIFY_EX
  20798. #undef JSON_HEDLEY_SUNPRO_VERSION
  20799. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  20800. #undef JSON_HEDLEY_TINYC_VERSION
  20801. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  20802. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  20803. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  20804. #undef JSON_HEDLEY_TI_CL2000_VERSION
  20805. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  20806. #undef JSON_HEDLEY_TI_CL430_VERSION
  20807. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  20808. #undef JSON_HEDLEY_TI_CL6X_VERSION
  20809. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  20810. #undef JSON_HEDLEY_TI_CL7X_VERSION
  20811. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  20812. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  20813. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  20814. #undef JSON_HEDLEY_TI_VERSION
  20815. #undef JSON_HEDLEY_TI_VERSION_CHECK
  20816. #undef JSON_HEDLEY_UNAVAILABLE
  20817. #undef JSON_HEDLEY_UNLIKELY
  20818. #undef JSON_HEDLEY_UNPREDICTABLE
  20819. #undef JSON_HEDLEY_UNREACHABLE
  20820. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  20821. #undef JSON_HEDLEY_VERSION
  20822. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  20823. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  20824. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  20825. #undef JSON_HEDLEY_VERSION_ENCODE
  20826. #undef JSON_HEDLEY_WARNING
  20827. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  20828. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  20829. #undef JSON_HEDLEY_FALL_THROUGH
  20830. #endif // INCLUDE_NLOHMANN_JSON_HPP_