json.hpp 788 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.7.0
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  26. #define INCLUDE_NLOHMANN_JSON_HPP_
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 7
  29. #define NLOHMANN_JSON_VERSION_PATCH 0
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <ciso646> // and, not, or
  33. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  34. #include <functional> // hash, less
  35. #include <initializer_list> // initializer_list
  36. #include <iosfwd> // istream, ostream
  37. #include <iterator> // random_access_iterator_tag
  38. #include <memory> // unique_ptr
  39. #include <numeric> // accumulate
  40. #include <string> // string, stoi, to_string
  41. #include <utility> // declval, forward, move, pair, swap
  42. #include <vector> // vector
  43. // #include <nlohmann/adl_serializer.hpp>
  44. #include <utility>
  45. // #include <nlohmann/detail/conversions/from_json.hpp>
  46. #include <algorithm> // transform
  47. #include <array> // array
  48. #include <ciso646> // and, not
  49. #include <forward_list> // forward_list
  50. #include <iterator> // inserter, front_inserter, end
  51. #include <map> // map
  52. #include <string> // string
  53. #include <tuple> // tuple, make_tuple
  54. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  55. #include <unordered_map> // unordered_map
  56. #include <utility> // pair, declval
  57. #include <valarray> // valarray
  58. // #include <nlohmann/detail/exceptions.hpp>
  59. #include <exception> // exception
  60. #include <stdexcept> // runtime_error
  61. #include <string> // to_string
  62. // #include <nlohmann/detail/input/position_t.hpp>
  63. #include <cstddef> // size_t
  64. namespace nlohmann
  65. {
  66. namespace detail
  67. {
  68. /// struct to capture the start position of the current token
  69. struct position_t
  70. {
  71. /// the total number of characters read
  72. std::size_t chars_read_total = 0;
  73. /// the number of characters read in the current line
  74. std::size_t chars_read_current_line = 0;
  75. /// the number of lines read
  76. std::size_t lines_read = 0;
  77. /// conversion to size_t to preserve SAX interface
  78. constexpr operator size_t() const
  79. {
  80. return chars_read_total;
  81. }
  82. };
  83. } // namespace detail
  84. } // namespace nlohmann
  85. // #include <nlohmann/detail/macro_scope.hpp>
  86. #include <utility> // pair
  87. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  88. /* Hedley - https://nemequ.github.io/hedley
  89. * Created by Evan Nemerson <evan@nemerson.com>
  90. *
  91. * To the extent possible under law, the author(s) have dedicated all
  92. * copyright and related and neighboring rights to this software to
  93. * the public domain worldwide. This software is distributed without
  94. * any warranty.
  95. *
  96. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  97. * SPDX-License-Identifier: CC0-1.0
  98. */
  99. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 11)
  100. #if defined(JSON_HEDLEY_VERSION)
  101. #undef JSON_HEDLEY_VERSION
  102. #endif
  103. #define JSON_HEDLEY_VERSION 11
  104. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  105. #undef JSON_HEDLEY_STRINGIFY_EX
  106. #endif
  107. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  108. #if defined(JSON_HEDLEY_STRINGIFY)
  109. #undef JSON_HEDLEY_STRINGIFY
  110. #endif
  111. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  112. #if defined(JSON_HEDLEY_CONCAT_EX)
  113. #undef JSON_HEDLEY_CONCAT_EX
  114. #endif
  115. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  116. #if defined(JSON_HEDLEY_CONCAT)
  117. #undef JSON_HEDLEY_CONCAT
  118. #endif
  119. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  120. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  121. #undef JSON_HEDLEY_VERSION_ENCODE
  122. #endif
  123. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  124. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  125. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  126. #endif
  127. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  128. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  129. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  130. #endif
  131. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  132. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  133. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  134. #endif
  135. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  136. #if defined(JSON_HEDLEY_GNUC_VERSION)
  137. #undef JSON_HEDLEY_GNUC_VERSION
  138. #endif
  139. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  140. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  141. #elif defined(__GNUC__)
  142. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  143. #endif
  144. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  145. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  146. #endif
  147. #if defined(JSON_HEDLEY_GNUC_VERSION)
  148. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  149. #else
  150. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  151. #endif
  152. #if defined(JSON_HEDLEY_MSVC_VERSION)
  153. #undef JSON_HEDLEY_MSVC_VERSION
  154. #endif
  155. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  156. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  157. #elif defined(_MSC_FULL_VER)
  158. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  159. #elif defined(_MSC_VER)
  160. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  161. #endif
  162. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  163. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  164. #endif
  165. #if !defined(_MSC_VER)
  166. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  167. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  168. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  169. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  170. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  171. #else
  172. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  173. #endif
  174. #if defined(JSON_HEDLEY_INTEL_VERSION)
  175. #undef JSON_HEDLEY_INTEL_VERSION
  176. #endif
  177. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  178. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  179. #elif defined(__INTEL_COMPILER)
  180. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  181. #endif
  182. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  183. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  184. #endif
  185. #if defined(JSON_HEDLEY_INTEL_VERSION)
  186. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  187. #else
  188. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  189. #endif
  190. #if defined(JSON_HEDLEY_PGI_VERSION)
  191. #undef JSON_HEDLEY_PGI_VERSION
  192. #endif
  193. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  194. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  195. #endif
  196. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  197. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  198. #endif
  199. #if defined(JSON_HEDLEY_PGI_VERSION)
  200. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  201. #else
  202. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  203. #endif
  204. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  205. #undef JSON_HEDLEY_SUNPRO_VERSION
  206. #endif
  207. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  208. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10)
  209. #elif defined(__SUNPRO_C)
  210. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  211. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  212. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10)
  213. #elif defined(__SUNPRO_CC)
  214. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  215. #endif
  216. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  217. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  218. #endif
  219. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  220. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  221. #else
  222. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  223. #endif
  224. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  225. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  226. #endif
  227. #if defined(__EMSCRIPTEN__)
  228. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  229. #endif
  230. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  231. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  232. #endif
  233. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  234. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  235. #else
  236. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  237. #endif
  238. #if defined(JSON_HEDLEY_ARM_VERSION)
  239. #undef JSON_HEDLEY_ARM_VERSION
  240. #endif
  241. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  242. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  243. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  244. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  245. #endif
  246. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  247. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  248. #endif
  249. #if defined(JSON_HEDLEY_ARM_VERSION)
  250. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  251. #else
  252. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  253. #endif
  254. #if defined(JSON_HEDLEY_IBM_VERSION)
  255. #undef JSON_HEDLEY_IBM_VERSION
  256. #endif
  257. #if defined(__ibmxl__)
  258. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  259. #elif defined(__xlC__) && defined(__xlC_ver__)
  260. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  261. #elif defined(__xlC__)
  262. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  263. #endif
  264. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  265. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  266. #endif
  267. #if defined(JSON_HEDLEY_IBM_VERSION)
  268. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  269. #else
  270. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  271. #endif
  272. #if defined(JSON_HEDLEY_TI_VERSION)
  273. #undef JSON_HEDLEY_TI_VERSION
  274. #endif
  275. #if defined(__TI_COMPILER_VERSION__)
  276. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  277. #endif
  278. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  279. #undef JSON_HEDLEY_TI_VERSION_CHECK
  280. #endif
  281. #if defined(JSON_HEDLEY_TI_VERSION)
  282. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  283. #else
  284. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  285. #endif
  286. #if defined(JSON_HEDLEY_CRAY_VERSION)
  287. #undef JSON_HEDLEY_CRAY_VERSION
  288. #endif
  289. #if defined(_CRAYC)
  290. #if defined(_RELEASE_PATCHLEVEL)
  291. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  292. #else
  293. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  294. #endif
  295. #endif
  296. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  297. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  298. #endif
  299. #if defined(JSON_HEDLEY_CRAY_VERSION)
  300. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  301. #else
  302. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  303. #endif
  304. #if defined(JSON_HEDLEY_IAR_VERSION)
  305. #undef JSON_HEDLEY_IAR_VERSION
  306. #endif
  307. #if defined(__IAR_SYSTEMS_ICC__)
  308. #if __VER__ > 1000
  309. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  310. #else
  311. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  312. #endif
  313. #endif
  314. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  315. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  316. #endif
  317. #if defined(JSON_HEDLEY_IAR_VERSION)
  318. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  319. #else
  320. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  321. #endif
  322. #if defined(JSON_HEDLEY_TINYC_VERSION)
  323. #undef JSON_HEDLEY_TINYC_VERSION
  324. #endif
  325. #if defined(__TINYC__)
  326. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  327. #endif
  328. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  329. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  330. #endif
  331. #if defined(JSON_HEDLEY_TINYC_VERSION)
  332. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  333. #else
  334. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  335. #endif
  336. #if defined(JSON_HEDLEY_DMC_VERSION)
  337. #undef JSON_HEDLEY_DMC_VERSION
  338. #endif
  339. #if defined(__DMC__)
  340. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  341. #endif
  342. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  343. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  344. #endif
  345. #if defined(JSON_HEDLEY_DMC_VERSION)
  346. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  347. #else
  348. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  349. #endif
  350. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  351. #undef JSON_HEDLEY_COMPCERT_VERSION
  352. #endif
  353. #if defined(__COMPCERT_VERSION__)
  354. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  355. #endif
  356. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  357. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  358. #endif
  359. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  360. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  361. #else
  362. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  363. #endif
  364. #if defined(JSON_HEDLEY_PELLES_VERSION)
  365. #undef JSON_HEDLEY_PELLES_VERSION
  366. #endif
  367. #if defined(__POCC__)
  368. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  369. #endif
  370. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  371. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  372. #endif
  373. #if defined(JSON_HEDLEY_PELLES_VERSION)
  374. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  375. #else
  376. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  377. #endif
  378. #if defined(JSON_HEDLEY_GCC_VERSION)
  379. #undef JSON_HEDLEY_GCC_VERSION
  380. #endif
  381. #if \
  382. defined(JSON_HEDLEY_GNUC_VERSION) && \
  383. !defined(__clang__) && \
  384. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  385. !defined(JSON_HEDLEY_PGI_VERSION) && \
  386. !defined(JSON_HEDLEY_ARM_VERSION) && \
  387. !defined(JSON_HEDLEY_TI_VERSION) && \
  388. !defined(__COMPCERT__)
  389. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  390. #endif
  391. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  392. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  393. #endif
  394. #if defined(JSON_HEDLEY_GCC_VERSION)
  395. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  396. #else
  397. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  398. #endif
  399. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  400. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  401. #endif
  402. #if defined(__has_attribute)
  403. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  404. #else
  405. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  406. #endif
  407. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  408. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  409. #endif
  410. #if defined(__has_attribute)
  411. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  412. #else
  413. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  414. #endif
  415. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  416. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  417. #endif
  418. #if defined(__has_attribute)
  419. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  420. #else
  421. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  422. #endif
  423. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  424. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  425. #endif
  426. #if \
  427. defined(__has_cpp_attribute) && \
  428. defined(__cplusplus) && \
  429. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  430. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  431. #else
  432. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  433. #endif
  434. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  435. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  436. #endif
  437. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  438. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  439. #elif \
  440. !defined(JSON_HEDLEY_PGI_VERSION) && \
  441. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  442. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  443. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  444. #else
  445. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  446. #endif
  447. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  448. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  449. #endif
  450. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  451. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  452. #else
  453. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  454. #endif
  455. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  456. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  457. #endif
  458. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  459. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  460. #else
  461. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  462. #endif
  463. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  464. #undef JSON_HEDLEY_HAS_BUILTIN
  465. #endif
  466. #if defined(__has_builtin)
  467. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  468. #else
  469. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  470. #endif
  471. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  472. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  473. #endif
  474. #if defined(__has_builtin)
  475. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  476. #else
  477. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  478. #endif
  479. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  480. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  481. #endif
  482. #if defined(__has_builtin)
  483. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  484. #else
  485. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  486. #endif
  487. #if defined(JSON_HEDLEY_HAS_FEATURE)
  488. #undef JSON_HEDLEY_HAS_FEATURE
  489. #endif
  490. #if defined(__has_feature)
  491. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  492. #else
  493. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  494. #endif
  495. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  496. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  497. #endif
  498. #if defined(__has_feature)
  499. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  500. #else
  501. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  502. #endif
  503. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  504. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  505. #endif
  506. #if defined(__has_feature)
  507. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  508. #else
  509. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  510. #endif
  511. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  512. #undef JSON_HEDLEY_HAS_EXTENSION
  513. #endif
  514. #if defined(__has_extension)
  515. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  516. #else
  517. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  518. #endif
  519. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  520. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  521. #endif
  522. #if defined(__has_extension)
  523. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  524. #else
  525. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  526. #endif
  527. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  528. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  529. #endif
  530. #if defined(__has_extension)
  531. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  532. #else
  533. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  534. #endif
  535. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  536. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  537. #endif
  538. #if defined(__has_declspec_attribute)
  539. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  540. #else
  541. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  542. #endif
  543. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  544. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  545. #endif
  546. #if defined(__has_declspec_attribute)
  547. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  548. #else
  549. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  550. #endif
  551. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  552. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  553. #endif
  554. #if defined(__has_declspec_attribute)
  555. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  556. #else
  557. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  558. #endif
  559. #if defined(JSON_HEDLEY_HAS_WARNING)
  560. #undef JSON_HEDLEY_HAS_WARNING
  561. #endif
  562. #if defined(__has_warning)
  563. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  564. #else
  565. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  566. #endif
  567. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  568. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  569. #endif
  570. #if defined(__has_warning)
  571. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  572. #else
  573. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  574. #endif
  575. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  576. #undef JSON_HEDLEY_GCC_HAS_WARNING
  577. #endif
  578. #if defined(__has_warning)
  579. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  580. #else
  581. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  582. #endif
  583. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  584. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  585. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  586. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  587. #endif
  588. #if defined(__cplusplus) && JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  589. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  590. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  591. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  592. xpr \
  593. JSON_HEDLEY_DIAGNOSTIC_POP
  594. #else
  595. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  596. #endif
  597. #if \
  598. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  599. defined(__clang__) || \
  600. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  601. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  602. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  603. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  604. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  605. JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) || \
  606. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  607. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  608. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  609. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  610. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  611. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  612. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  613. #else
  614. #define JSON_HEDLEY_PRAGMA(value)
  615. #endif
  616. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  617. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  618. #endif
  619. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  620. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  621. #endif
  622. #if defined(__clang__)
  623. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  624. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  625. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  626. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  627. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  628. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  629. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  630. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  631. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  632. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  633. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  634. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  635. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  636. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  637. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,1,0)
  638. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  639. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  640. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  641. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  642. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  643. #else
  644. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  645. #define JSON_HEDLEY_DIAGNOSTIC_POP
  646. #endif
  647. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  648. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  649. #endif
  650. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  651. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  652. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  653. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  654. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  655. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  656. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  657. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  658. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  659. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  660. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  661. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  662. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  663. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  664. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  665. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  666. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  667. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  668. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  669. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  670. #else
  671. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  672. #endif
  673. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  674. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  675. #endif
  676. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  677. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  678. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  679. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  680. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  681. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  682. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  683. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  684. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  685. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  686. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  687. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  688. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  689. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  690. #else
  691. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  692. #endif
  693. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  694. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  695. #endif
  696. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  697. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  698. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  699. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  700. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  701. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  702. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  703. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  704. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  705. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  706. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  707. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  708. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  709. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  710. #else
  711. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  712. #endif
  713. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  714. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  715. #endif
  716. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  717. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  718. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  719. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  720. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  721. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  722. #else
  723. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  724. #endif
  725. #if defined(JSON_HEDLEY_DEPRECATED)
  726. #undef JSON_HEDLEY_DEPRECATED
  727. #endif
  728. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  729. #undef JSON_HEDLEY_DEPRECATED_FOR
  730. #endif
  731. #if defined(__cplusplus) && (__cplusplus >= 201402L)
  732. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  733. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  734. #elif \
  735. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  736. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  737. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  738. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  739. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  740. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  741. JSON_HEDLEY_TI_VERSION_CHECK(8,3,0)
  742. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  743. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  744. #elif \
  745. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  746. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  747. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  748. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  749. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  750. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  751. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  752. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  753. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  754. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  755. #elif \
  756. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  757. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  758. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  759. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  760. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  761. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  762. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  763. #else
  764. #define JSON_HEDLEY_DEPRECATED(since)
  765. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  766. #endif
  767. #if defined(JSON_HEDLEY_UNAVAILABLE)
  768. #undef JSON_HEDLEY_UNAVAILABLE
  769. #endif
  770. #if \
  771. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  772. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  773. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  774. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  775. #else
  776. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  777. #endif
  778. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  779. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  780. #endif
  781. #if defined(__cplusplus) && (__cplusplus >= 201703L)
  782. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  783. #elif \
  784. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  785. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  786. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  787. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  788. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  789. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  790. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  791. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  792. #elif defined(_Check_return_) /* SAL */
  793. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  794. #else
  795. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  796. #endif
  797. #if defined(JSON_HEDLEY_SENTINEL)
  798. #undef JSON_HEDLEY_SENTINEL
  799. #endif
  800. #if \
  801. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  802. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  803. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  804. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  805. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  806. #else
  807. #define JSON_HEDLEY_SENTINEL(position)
  808. #endif
  809. #if defined(JSON_HEDLEY_NO_RETURN)
  810. #undef JSON_HEDLEY_NO_RETURN
  811. #endif
  812. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  813. #define JSON_HEDLEY_NO_RETURN __noreturn
  814. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  815. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  816. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  817. #define JSON_HEDLEY_NO_RETURN _Noreturn
  818. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  819. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  820. #elif \
  821. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  822. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  823. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  824. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  825. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  826. JSON_HEDLEY_TI_VERSION_CHECK(18,0,0) || \
  827. (JSON_HEDLEY_TI_VERSION_CHECK(17,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  828. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  829. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  830. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  831. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  832. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  833. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  834. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  835. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  836. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  837. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  838. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  839. #else
  840. #define JSON_HEDLEY_NO_RETURN
  841. #endif
  842. #if defined(JSON_HEDLEY_NO_ESCAPE)
  843. #undef JSON_HEDLEY_NO_ESCAPE
  844. #endif
  845. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  846. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  847. #else
  848. #define JSON_HEDLEY_NO_ESCAPE
  849. #endif
  850. #if defined(JSON_HEDLEY_UNREACHABLE)
  851. #undef JSON_HEDLEY_UNREACHABLE
  852. #endif
  853. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  854. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  855. #endif
  856. #if \
  857. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  858. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  859. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  860. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  861. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  862. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  863. #define JSON_HEDLEY_UNREACHABLE() __assume(0)
  864. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  865. #if defined(__cplusplus)
  866. #define JSON_HEDLEY_UNREACHABLE() std::_nassert(0)
  867. #else
  868. #define JSON_HEDLEY_UNREACHABLE() _nassert(0)
  869. #endif
  870. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  871. #elif defined(EXIT_FAILURE)
  872. #define JSON_HEDLEY_UNREACHABLE() abort()
  873. #else
  874. #define JSON_HEDLEY_UNREACHABLE()
  875. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  876. #endif
  877. #if !defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  878. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  879. #endif
  880. #if defined(JSON_HEDLEY_ASSUME)
  881. #undef JSON_HEDLEY_ASSUME
  882. #endif
  883. #if \
  884. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  885. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  886. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  887. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  888. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  889. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  890. #if defined(__cplusplus)
  891. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  892. #else
  893. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  894. #endif
  895. #elif \
  896. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && !defined(JSON_HEDLEY_ARM_VERSION)) || \
  897. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  898. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  899. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  900. #define JSON_HEDLEY_ASSUME(expr) ((void) ((expr) ? 1 : (__builtin_unreachable(), 1)))
  901. #else
  902. #define JSON_HEDLEY_ASSUME(expr) ((void) (expr))
  903. #endif
  904. JSON_HEDLEY_DIAGNOSTIC_PUSH
  905. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  906. #pragma clang diagnostic ignored "-Wpedantic"
  907. #endif
  908. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  909. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  910. #endif
  911. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  912. #if defined(__clang__)
  913. #pragma clang diagnostic ignored "-Wvariadic-macros"
  914. #elif defined(JSON_HEDLEY_GCC_VERSION)
  915. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  916. #endif
  917. #endif
  918. #if defined(JSON_HEDLEY_NON_NULL)
  919. #undef JSON_HEDLEY_NON_NULL
  920. #endif
  921. #if \
  922. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  923. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  924. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  925. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  926. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  927. #else
  928. #define JSON_HEDLEY_NON_NULL(...)
  929. #endif
  930. JSON_HEDLEY_DIAGNOSTIC_POP
  931. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  932. #undef JSON_HEDLEY_PRINTF_FORMAT
  933. #endif
  934. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  935. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  936. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  937. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  938. #elif \
  939. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  940. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  941. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  942. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  943. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  944. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  945. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  946. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  947. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  948. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  949. #else
  950. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  951. #endif
  952. #if defined(JSON_HEDLEY_CONSTEXPR)
  953. #undef JSON_HEDLEY_CONSTEXPR
  954. #endif
  955. #if defined(__cplusplus)
  956. #if __cplusplus >= 201103L
  957. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  958. #endif
  959. #endif
  960. #if !defined(JSON_HEDLEY_CONSTEXPR)
  961. #define JSON_HEDLEY_CONSTEXPR
  962. #endif
  963. #if defined(JSON_HEDLEY_PREDICT)
  964. #undef JSON_HEDLEY_PREDICT
  965. #endif
  966. #if defined(JSON_HEDLEY_LIKELY)
  967. #undef JSON_HEDLEY_LIKELY
  968. #endif
  969. #if defined(JSON_HEDLEY_UNLIKELY)
  970. #undef JSON_HEDLEY_UNLIKELY
  971. #endif
  972. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  973. #undef JSON_HEDLEY_UNPREDICTABLE
  974. #endif
  975. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  976. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable(!!(expr))
  977. #endif
  978. #if \
  979. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  980. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  981. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability(expr, value, probability)
  982. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1, probability)
  983. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0, probability)
  984. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  985. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  986. #if !defined(JSON_HEDLEY_BUILTIN_UNPREDICTABLE)
  987. #define JSON_HEDLEY_BUILTIN_UNPREDICTABLE(expr) __builtin_expect_with_probability(!!(expr), 1, 0.5)
  988. #endif
  989. #elif \
  990. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  991. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  992. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  993. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  994. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  995. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  996. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  997. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27)
  998. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  999. (((probability) >= 0.9) ? __builtin_expect(!!(expr), (expected)) : (((void) (expected)), !!(expr)))
  1000. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1001. (__extension__ ({ \
  1002. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  1003. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1004. }))
  1005. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1006. (__extension__ ({ \
  1007. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  1008. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1009. }))
  1010. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1011. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1012. #else
  1013. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (((void) (expected)), !!(expr))
  1014. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1015. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1016. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1017. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1018. #endif
  1019. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1020. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1021. #endif
  1022. #if defined(JSON_HEDLEY_MALLOC)
  1023. #undef JSON_HEDLEY_MALLOC
  1024. #endif
  1025. #if \
  1026. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1027. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1028. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1029. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1030. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1031. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1032. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1033. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1034. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1035. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1036. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1037. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  1038. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1039. #else
  1040. #define JSON_HEDLEY_MALLOC
  1041. #endif
  1042. #if defined(JSON_HEDLEY_PURE)
  1043. #undef JSON_HEDLEY_PURE
  1044. #endif
  1045. #if \
  1046. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1047. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1048. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1049. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1050. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1051. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1052. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1053. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1054. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1055. #define JSON_HEDLEY_PURE __attribute__((__pure__))
  1056. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1057. #define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1058. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1059. #define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1060. #else
  1061. #define JSON_HEDLEY_PURE
  1062. #endif
  1063. #if defined(JSON_HEDLEY_CONST)
  1064. #undef JSON_HEDLEY_CONST
  1065. #endif
  1066. #if \
  1067. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1068. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1069. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1070. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1071. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1072. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1073. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1074. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1075. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1076. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1077. #elif \
  1078. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1079. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1080. #else
  1081. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1082. #endif
  1083. #if defined(JSON_HEDLEY_RESTRICT)
  1084. #undef JSON_HEDLEY_RESTRICT
  1085. #endif
  1086. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1087. #define JSON_HEDLEY_RESTRICT restrict
  1088. #elif \
  1089. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1090. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1091. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1092. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1093. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1094. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1095. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1096. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1097. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1098. defined(__clang__)
  1099. #define JSON_HEDLEY_RESTRICT __restrict
  1100. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1101. #define JSON_HEDLEY_RESTRICT _Restrict
  1102. #else
  1103. #define JSON_HEDLEY_RESTRICT
  1104. #endif
  1105. #if defined(JSON_HEDLEY_INLINE)
  1106. #undef JSON_HEDLEY_INLINE
  1107. #endif
  1108. #if \
  1109. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1110. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1111. #define JSON_HEDLEY_INLINE inline
  1112. #elif \
  1113. defined(JSON_HEDLEY_GCC_VERSION) || \
  1114. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1115. #define JSON_HEDLEY_INLINE __inline__
  1116. #elif \
  1117. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1118. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1119. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  1120. #define JSON_HEDLEY_INLINE __inline
  1121. #else
  1122. #define JSON_HEDLEY_INLINE
  1123. #endif
  1124. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1125. #undef JSON_HEDLEY_ALWAYS_INLINE
  1126. #endif
  1127. #if \
  1128. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1129. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1130. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1131. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1132. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1133. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1134. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1135. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1136. #define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1137. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1138. #define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1139. #elif JSON_HEDLEY_TI_VERSION_CHECK(7,0,0) && defined(__cplusplus)
  1140. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1141. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1142. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1143. #else
  1144. #define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1145. #endif
  1146. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1147. #undef JSON_HEDLEY_NEVER_INLINE
  1148. #endif
  1149. #if \
  1150. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1151. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1152. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1153. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1154. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1155. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1156. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1157. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1158. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1159. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1160. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1161. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1162. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1163. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1164. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1165. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1166. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1167. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1168. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1169. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1170. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1171. #else
  1172. #define JSON_HEDLEY_NEVER_INLINE
  1173. #endif
  1174. #if defined(JSON_HEDLEY_PRIVATE)
  1175. #undef JSON_HEDLEY_PRIVATE
  1176. #endif
  1177. #if defined(JSON_HEDLEY_PUBLIC)
  1178. #undef JSON_HEDLEY_PUBLIC
  1179. #endif
  1180. #if defined(JSON_HEDLEY_IMPORT)
  1181. #undef JSON_HEDLEY_IMPORT
  1182. #endif
  1183. #if defined(_WIN32) || defined(__CYGWIN__)
  1184. #define JSON_HEDLEY_PRIVATE
  1185. #define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1186. #define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1187. #else
  1188. #if \
  1189. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1190. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1191. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1192. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1193. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1194. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1195. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1196. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_EABI__) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1197. #define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1198. #define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1199. #else
  1200. #define JSON_HEDLEY_PRIVATE
  1201. #define JSON_HEDLEY_PUBLIC
  1202. #endif
  1203. #define JSON_HEDLEY_IMPORT extern
  1204. #endif
  1205. #if defined(JSON_HEDLEY_NO_THROW)
  1206. #undef JSON_HEDLEY_NO_THROW
  1207. #endif
  1208. #if \
  1209. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1210. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1211. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1212. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1213. #elif \
  1214. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1215. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1216. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1217. #else
  1218. #define JSON_HEDLEY_NO_THROW
  1219. #endif
  1220. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1221. #undef JSON_HEDLEY_FALL_THROUGH
  1222. #endif
  1223. #if JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(fallthrough,7,0,0) && !defined(JSON_HEDLEY_PGI_VERSION)
  1224. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1225. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1226. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1227. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1228. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1229. #elif defined(__fallthrough) /* SAL */
  1230. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1231. #else
  1232. #define JSON_HEDLEY_FALL_THROUGH
  1233. #endif
  1234. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1235. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1236. #endif
  1237. #if \
  1238. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1239. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1240. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1241. #elif defined(_Ret_notnull_) /* SAL */
  1242. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1243. #else
  1244. #define JSON_HEDLEY_RETURNS_NON_NULL
  1245. #endif
  1246. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1247. #undef JSON_HEDLEY_ARRAY_PARAM
  1248. #endif
  1249. #if \
  1250. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1251. !defined(__STDC_NO_VLA__) && \
  1252. !defined(__cplusplus) && \
  1253. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1254. !defined(JSON_HEDLEY_TINYC_VERSION)
  1255. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1256. #else
  1257. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1258. #endif
  1259. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1260. #undef JSON_HEDLEY_IS_CONSTANT
  1261. #endif
  1262. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1263. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1264. #endif
  1265. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1266. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1267. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1268. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1269. #endif
  1270. #if \
  1271. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1272. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1273. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1274. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1275. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1276. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1277. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  1278. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1279. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1280. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1281. #endif
  1282. #if !defined(__cplusplus)
  1283. # if \
  1284. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1285. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1286. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1287. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1288. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1289. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1290. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1291. #if defined(__INTPTR_TYPE__)
  1292. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1293. #else
  1294. #include <stdint.h>
  1295. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1296. #endif
  1297. # elif \
  1298. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(JSON_HEDLEY_SUNPRO_VERSION) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1299. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1300. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1301. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1302. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1303. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1304. #if defined(__INTPTR_TYPE__)
  1305. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1306. #else
  1307. #include <stdint.h>
  1308. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1309. #endif
  1310. # elif \
  1311. defined(JSON_HEDLEY_GCC_VERSION) || \
  1312. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1313. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1314. defined(JSON_HEDLEY_TI_VERSION) || \
  1315. defined(__clang__)
  1316. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1317. sizeof(void) != \
  1318. sizeof(*( \
  1319. 1 ? \
  1320. ((void*) ((expr) * 0L) ) : \
  1321. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1322. ) \
  1323. ) \
  1324. )
  1325. # endif
  1326. #endif
  1327. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1328. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1329. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1330. #endif
  1331. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1332. #else
  1333. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1334. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1335. #endif
  1336. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1337. #endif
  1338. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1339. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1340. #endif
  1341. #if defined(JSON_HEDLEY_END_C_DECLS)
  1342. #undef JSON_HEDLEY_END_C_DECLS
  1343. #endif
  1344. #if defined(JSON_HEDLEY_C_DECL)
  1345. #undef JSON_HEDLEY_C_DECL
  1346. #endif
  1347. #if defined(__cplusplus)
  1348. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1349. #define JSON_HEDLEY_END_C_DECLS }
  1350. #define JSON_HEDLEY_C_DECL extern "C"
  1351. #else
  1352. #define JSON_HEDLEY_BEGIN_C_DECLS
  1353. #define JSON_HEDLEY_END_C_DECLS
  1354. #define JSON_HEDLEY_C_DECL
  1355. #endif
  1356. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1357. #undef JSON_HEDLEY_STATIC_ASSERT
  1358. #endif
  1359. #if \
  1360. !defined(__cplusplus) && ( \
  1361. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1362. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1363. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1364. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1365. defined(_Static_assert) \
  1366. )
  1367. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1368. #elif \
  1369. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1370. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1371. (defined(__cplusplus) && JSON_HEDLEY_TI_VERSION_CHECK(8,3,0))
  1372. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1373. #else
  1374. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1375. #endif
  1376. #if defined(JSON_HEDLEY_CONST_CAST)
  1377. #undef JSON_HEDLEY_CONST_CAST
  1378. #endif
  1379. #if defined(__cplusplus)
  1380. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  1381. #elif \
  1382. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  1383. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  1384. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1385. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  1386. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1387. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  1388. ((T) (expr)); \
  1389. JSON_HEDLEY_DIAGNOSTIC_POP \
  1390. }))
  1391. #else
  1392. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  1393. #endif
  1394. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  1395. #undef JSON_HEDLEY_REINTERPRET_CAST
  1396. #endif
  1397. #if defined(__cplusplus)
  1398. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  1399. #else
  1400. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (*((T*) &(expr)))
  1401. #endif
  1402. #if defined(JSON_HEDLEY_STATIC_CAST)
  1403. #undef JSON_HEDLEY_STATIC_CAST
  1404. #endif
  1405. #if defined(__cplusplus)
  1406. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  1407. #else
  1408. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  1409. #endif
  1410. #if defined(JSON_HEDLEY_CPP_CAST)
  1411. #undef JSON_HEDLEY_CPP_CAST
  1412. #endif
  1413. #if defined(__cplusplus)
  1414. #define JSON_HEDLEY_CPP_CAST(T, expr) static_cast<T>(expr)
  1415. #else
  1416. #define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  1417. #endif
  1418. #if defined(JSON_HEDLEY_NULL)
  1419. #undef JSON_HEDLEY_NULL
  1420. #endif
  1421. #if defined(__cplusplus)
  1422. #if __cplusplus >= 201103L
  1423. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1424. #elif defined(NULL)
  1425. #define JSON_HEDLEY_NULL NULL
  1426. #else
  1427. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1428. #endif
  1429. #elif defined(NULL)
  1430. #define JSON_HEDLEY_NULL NULL
  1431. #else
  1432. #define JSON_HEDLEY_NULL ((void*) 0)
  1433. #endif
  1434. #if defined(JSON_HEDLEY_MESSAGE)
  1435. #undef JSON_HEDLEY_MESSAGE
  1436. #endif
  1437. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1438. # define JSON_HEDLEY_MESSAGE(msg) \
  1439. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1440. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1441. JSON_HEDLEY_PRAGMA(message msg) \
  1442. JSON_HEDLEY_DIAGNOSTIC_POP
  1443. #elif \
  1444. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1445. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1446. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1447. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1448. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1449. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1450. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1451. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1452. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1453. #else
  1454. # define JSON_HEDLEY_MESSAGE(msg)
  1455. #endif
  1456. #if defined(JSON_HEDLEY_WARNING)
  1457. #undef JSON_HEDLEY_WARNING
  1458. #endif
  1459. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1460. # define JSON_HEDLEY_WARNING(msg) \
  1461. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1462. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1463. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1464. JSON_HEDLEY_DIAGNOSTIC_POP
  1465. #elif \
  1466. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1467. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0)
  1468. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1469. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1470. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1471. #else
  1472. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1473. #endif
  1474. #if defined(JSON_HEDLEY_REQUIRE)
  1475. #undef JSON_HEDLEY_REQUIRE
  1476. #endif
  1477. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1478. #undef JSON_HEDLEY_REQUIRE_MSG
  1479. #endif
  1480. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1481. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1482. # define JSON_HEDLEY_REQUIRE(expr) \
  1483. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1484. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1485. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1486. JSON_HEDLEY_DIAGNOSTIC_POP
  1487. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1488. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1489. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1490. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1491. JSON_HEDLEY_DIAGNOSTIC_POP
  1492. # else
  1493. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1494. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1495. # endif
  1496. #else
  1497. # define JSON_HEDLEY_REQUIRE(expr)
  1498. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1499. #endif
  1500. #if defined(JSON_HEDLEY_FLAGS)
  1501. #undef JSON_HEDLEY_FLAGS
  1502. #endif
  1503. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1504. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1505. #endif
  1506. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1507. #undef JSON_HEDLEY_FLAGS_CAST
  1508. #endif
  1509. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1510. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1511. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1512. _Pragma("warning(disable:188)") \
  1513. ((T) (expr)); \
  1514. JSON_HEDLEY_DIAGNOSTIC_POP \
  1515. }))
  1516. #else
  1517. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1518. #endif
  1519. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1520. #undef JSON_HEDLEY_EMPTY_BASES
  1521. #endif
  1522. #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
  1523. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  1524. #else
  1525. #define JSON_HEDLEY_EMPTY_BASES
  1526. #endif
  1527. /* Remaining macros are deprecated. */
  1528. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1529. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1530. #endif
  1531. #if defined(__clang__)
  1532. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1533. #else
  1534. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1535. #endif
  1536. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1537. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1538. #endif
  1539. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1540. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1541. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1542. #endif
  1543. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1544. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1545. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1546. #endif
  1547. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1548. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1549. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1550. #endif
  1551. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1552. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1553. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1554. #endif
  1555. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1556. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1557. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1558. #endif
  1559. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1560. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1561. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1562. #endif
  1563. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1564. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1565. // This file contains all internal macro definitions
  1566. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1567. // exclude unsupported compilers
  1568. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1569. #if defined(__clang__)
  1570. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1571. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1572. #endif
  1573. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1574. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1575. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1576. #endif
  1577. #endif
  1578. #endif
  1579. // C++ language standard detection
  1580. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1581. #define JSON_HAS_CPP_17
  1582. #define JSON_HAS_CPP_14
  1583. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1584. #define JSON_HAS_CPP_14
  1585. #endif
  1586. // disable float-equal warnings on GCC/clang
  1587. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1588. #pragma GCC diagnostic push
  1589. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1590. #endif
  1591. // disable documentation warnings on clang
  1592. #if defined(__clang__)
  1593. #pragma GCC diagnostic push
  1594. #pragma GCC diagnostic ignored "-Wdocumentation"
  1595. #endif
  1596. // allow to disable exceptions
  1597. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1598. #define JSON_THROW(exception) throw exception
  1599. #define JSON_TRY try
  1600. #define JSON_CATCH(exception) catch(exception)
  1601. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1602. #else
  1603. #include <cstdlib>
  1604. #define JSON_THROW(exception) std::abort()
  1605. #define JSON_TRY if(true)
  1606. #define JSON_CATCH(exception) if(false)
  1607. #define JSON_INTERNAL_CATCH(exception) if(false)
  1608. #endif
  1609. // override exception macros
  1610. #if defined(JSON_THROW_USER)
  1611. #undef JSON_THROW
  1612. #define JSON_THROW JSON_THROW_USER
  1613. #endif
  1614. #if defined(JSON_TRY_USER)
  1615. #undef JSON_TRY
  1616. #define JSON_TRY JSON_TRY_USER
  1617. #endif
  1618. #if defined(JSON_CATCH_USER)
  1619. #undef JSON_CATCH
  1620. #define JSON_CATCH JSON_CATCH_USER
  1621. #undef JSON_INTERNAL_CATCH
  1622. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1623. #endif
  1624. #if defined(JSON_INTERNAL_CATCH_USER)
  1625. #undef JSON_INTERNAL_CATCH
  1626. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1627. #endif
  1628. /*!
  1629. @brief macro to briefly define a mapping between an enum and JSON
  1630. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1631. @since version 3.4.0
  1632. */
  1633. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1634. template<typename BasicJsonType> \
  1635. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1636. { \
  1637. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1638. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1639. auto it = std::find_if(std::begin(m), std::end(m), \
  1640. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1641. { \
  1642. return ej_pair.first == e; \
  1643. }); \
  1644. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1645. } \
  1646. template<typename BasicJsonType> \
  1647. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1648. { \
  1649. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1650. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1651. auto it = std::find_if(std::begin(m), std::end(m), \
  1652. [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1653. { \
  1654. return ej_pair.second == j; \
  1655. }); \
  1656. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1657. }
  1658. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1659. // may be removed in the future once the class is split.
  1660. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1661. template<template<typename, typename, typename...> class ObjectType, \
  1662. template<typename, typename...> class ArrayType, \
  1663. class StringType, class BooleanType, class NumberIntegerType, \
  1664. class NumberUnsignedType, class NumberFloatType, \
  1665. template<typename> class AllocatorType, \
  1666. template<typename, typename = void> class JSONSerializer>
  1667. #define NLOHMANN_BASIC_JSON_TPL \
  1668. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1669. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1670. AllocatorType, JSONSerializer>
  1671. namespace nlohmann
  1672. {
  1673. namespace detail
  1674. {
  1675. ////////////////
  1676. // exceptions //
  1677. ////////////////
  1678. /*!
  1679. @brief general exception of the @ref basic_json class
  1680. This class is an extension of `std::exception` objects with a member @a id for
  1681. exception ids. It is used as the base class for all exceptions thrown by the
  1682. @ref basic_json class. This class can hence be used as "wildcard" to catch
  1683. exceptions.
  1684. Subclasses:
  1685. - @ref parse_error for exceptions indicating a parse error
  1686. - @ref invalid_iterator for exceptions indicating errors with iterators
  1687. - @ref type_error for exceptions indicating executing a member function with
  1688. a wrong type
  1689. - @ref out_of_range for exceptions indicating access out of the defined range
  1690. - @ref other_error for exceptions indicating other library errors
  1691. @internal
  1692. @note To have nothrow-copy-constructible exceptions, we internally use
  1693. `std::runtime_error` which can cope with arbitrary-length error messages.
  1694. Intermediate strings are built with static functions and then passed to
  1695. the actual constructor.
  1696. @endinternal
  1697. @liveexample{The following code shows how arbitrary library exceptions can be
  1698. caught.,exception}
  1699. @since version 3.0.0
  1700. */
  1701. class exception : public std::exception
  1702. {
  1703. public:
  1704. /// returns the explanatory string
  1705. JSON_HEDLEY_RETURNS_NON_NULL
  1706. const char* what() const noexcept override
  1707. {
  1708. return m.what();
  1709. }
  1710. /// the id of the exception
  1711. const int id;
  1712. protected:
  1713. JSON_HEDLEY_NON_NULL(3)
  1714. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  1715. static std::string name(const std::string& ename, int id_)
  1716. {
  1717. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  1718. }
  1719. private:
  1720. /// an exception object as storage for error messages
  1721. std::runtime_error m;
  1722. };
  1723. /*!
  1724. @brief exception indicating a parse error
  1725. This exception is thrown by the library when a parse error occurs. Parse errors
  1726. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  1727. as when using JSON Patch.
  1728. Member @a byte holds the byte index of the last read character in the input
  1729. file.
  1730. Exceptions have ids 1xx.
  1731. name / id | example message | description
  1732. ------------------------------ | --------------- | -------------------------
  1733. 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.
  1734. 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.
  1735. 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.
  1736. 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.
  1737. 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.
  1738. 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`.
  1739. 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.
  1740. 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.
  1741. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  1742. 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.
  1743. 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.
  1744. 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.
  1745. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  1746. @note For an input with n bytes, 1 is the index of the first character and n+1
  1747. is the index of the terminating null byte or the end of file. This also
  1748. holds true when reading a byte vector (CBOR or MessagePack).
  1749. @liveexample{The following code shows how a `parse_error` exception can be
  1750. caught.,parse_error}
  1751. @sa - @ref exception for the base class of the library exceptions
  1752. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1753. @sa - @ref type_error for exceptions indicating executing a member function with
  1754. a wrong type
  1755. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1756. @sa - @ref other_error for exceptions indicating other library errors
  1757. @since version 3.0.0
  1758. */
  1759. class parse_error : public exception
  1760. {
  1761. public:
  1762. /*!
  1763. @brief create a parse error exception
  1764. @param[in] id_ the id of the exception
  1765. @param[in] pos the position where the error occurred (or with
  1766. chars_read_total=0 if the position cannot be
  1767. determined)
  1768. @param[in] what_arg the explanatory string
  1769. @return parse_error object
  1770. */
  1771. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  1772. {
  1773. std::string w = exception::name("parse_error", id_) + "parse error" +
  1774. position_string(pos) + ": " + what_arg;
  1775. return parse_error(id_, pos.chars_read_total, w.c_str());
  1776. }
  1777. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  1778. {
  1779. std::string w = exception::name("parse_error", id_) + "parse error" +
  1780. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  1781. ": " + what_arg;
  1782. return parse_error(id_, byte_, w.c_str());
  1783. }
  1784. /*!
  1785. @brief byte index of the parse error
  1786. The byte index of the last read character in the input file.
  1787. @note For an input with n bytes, 1 is the index of the first character and
  1788. n+1 is the index of the terminating null byte or the end of file.
  1789. This also holds true when reading a byte vector (CBOR or MessagePack).
  1790. */
  1791. const std::size_t byte;
  1792. private:
  1793. parse_error(int id_, std::size_t byte_, const char* what_arg)
  1794. : exception(id_, what_arg), byte(byte_) {}
  1795. static std::string position_string(const position_t& pos)
  1796. {
  1797. return " at line " + std::to_string(pos.lines_read + 1) +
  1798. ", column " + std::to_string(pos.chars_read_current_line);
  1799. }
  1800. };
  1801. /*!
  1802. @brief exception indicating errors with iterators
  1803. This exception is thrown if iterators passed to a library function do not match
  1804. the expected semantics.
  1805. Exceptions have ids 2xx.
  1806. name / id | example message | description
  1807. ----------------------------------- | --------------- | -------------------------
  1808. 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.
  1809. 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.
  1810. 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.
  1811. 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.
  1812. 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.
  1813. 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.
  1814. 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.
  1815. 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.
  1816. 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.
  1817. 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.
  1818. 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.
  1819. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  1820. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  1821. 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().
  1822. @liveexample{The following code shows how an `invalid_iterator` exception can be
  1823. caught.,invalid_iterator}
  1824. @sa - @ref exception for the base class of the library exceptions
  1825. @sa - @ref parse_error for exceptions indicating a parse error
  1826. @sa - @ref type_error for exceptions indicating executing a member function with
  1827. a wrong type
  1828. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1829. @sa - @ref other_error for exceptions indicating other library errors
  1830. @since version 3.0.0
  1831. */
  1832. class invalid_iterator : public exception
  1833. {
  1834. public:
  1835. static invalid_iterator create(int id_, const std::string& what_arg)
  1836. {
  1837. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  1838. return invalid_iterator(id_, w.c_str());
  1839. }
  1840. private:
  1841. JSON_HEDLEY_NON_NULL(3)
  1842. invalid_iterator(int id_, const char* what_arg)
  1843. : exception(id_, what_arg) {}
  1844. };
  1845. /*!
  1846. @brief exception indicating executing a member function with a wrong type
  1847. This exception is thrown in case of a type error; that is, a library function is
  1848. executed on a JSON value whose type does not match the expected semantics.
  1849. Exceptions have ids 3xx.
  1850. name / id | example message | description
  1851. ----------------------------- | --------------- | -------------------------
  1852. 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.
  1853. 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.
  1854. 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 &.
  1855. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  1856. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  1857. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  1858. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  1859. 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.
  1860. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  1861. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  1862. 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.
  1863. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  1864. 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.
  1865. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  1866. 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.
  1867. 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. |
  1868. 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) |
  1869. @liveexample{The following code shows how a `type_error` exception can be
  1870. caught.,type_error}
  1871. @sa - @ref exception for the base class of the library exceptions
  1872. @sa - @ref parse_error for exceptions indicating a parse error
  1873. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1874. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1875. @sa - @ref other_error for exceptions indicating other library errors
  1876. @since version 3.0.0
  1877. */
  1878. class type_error : public exception
  1879. {
  1880. public:
  1881. static type_error create(int id_, const std::string& what_arg)
  1882. {
  1883. std::string w = exception::name("type_error", id_) + what_arg;
  1884. return type_error(id_, w.c_str());
  1885. }
  1886. private:
  1887. JSON_HEDLEY_NON_NULL(3)
  1888. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1889. };
  1890. /*!
  1891. @brief exception indicating access out of the defined range
  1892. This exception is thrown in case a library function is called on an input
  1893. parameter that exceeds the expected range, for instance in case of array
  1894. indices or nonexisting object keys.
  1895. Exceptions have ids 4xx.
  1896. name / id | example message | description
  1897. ------------------------------- | --------------- | -------------------------
  1898. 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.
  1899. 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.
  1900. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  1901. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  1902. 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.
  1903. 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.
  1904. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  1905. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  1906. 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 |
  1907. @liveexample{The following code shows how an `out_of_range` exception can be
  1908. caught.,out_of_range}
  1909. @sa - @ref exception for the base class of the library exceptions
  1910. @sa - @ref parse_error for exceptions indicating a parse error
  1911. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1912. @sa - @ref type_error for exceptions indicating executing a member function with
  1913. a wrong type
  1914. @sa - @ref other_error for exceptions indicating other library errors
  1915. @since version 3.0.0
  1916. */
  1917. class out_of_range : public exception
  1918. {
  1919. public:
  1920. static out_of_range create(int id_, const std::string& what_arg)
  1921. {
  1922. std::string w = exception::name("out_of_range", id_) + what_arg;
  1923. return out_of_range(id_, w.c_str());
  1924. }
  1925. private:
  1926. JSON_HEDLEY_NON_NULL(3)
  1927. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1928. };
  1929. /*!
  1930. @brief exception indicating other library errors
  1931. This exception is thrown in case of errors that cannot be classified with the
  1932. other exception types.
  1933. Exceptions have ids 5xx.
  1934. name / id | example message | description
  1935. ------------------------------ | --------------- | -------------------------
  1936. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  1937. @sa - @ref exception for the base class of the library exceptions
  1938. @sa - @ref parse_error for exceptions indicating a parse error
  1939. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1940. @sa - @ref type_error for exceptions indicating executing a member function with
  1941. a wrong type
  1942. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1943. @liveexample{The following code shows how an `other_error` exception can be
  1944. caught.,other_error}
  1945. @since version 3.0.0
  1946. */
  1947. class other_error : public exception
  1948. {
  1949. public:
  1950. static other_error create(int id_, const std::string& what_arg)
  1951. {
  1952. std::string w = exception::name("other_error", id_) + what_arg;
  1953. return other_error(id_, w.c_str());
  1954. }
  1955. private:
  1956. JSON_HEDLEY_NON_NULL(3)
  1957. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1958. };
  1959. } // namespace detail
  1960. } // namespace nlohmann
  1961. // #include <nlohmann/detail/macro_scope.hpp>
  1962. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1963. #include <ciso646> // not
  1964. #include <cstddef> // size_t
  1965. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  1966. namespace nlohmann
  1967. {
  1968. namespace detail
  1969. {
  1970. // alias templates to reduce boilerplate
  1971. template<bool B, typename T = void>
  1972. using enable_if_t = typename std::enable_if<B, T>::type;
  1973. template<typename T>
  1974. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  1975. // implementation of C++14 index_sequence and affiliates
  1976. // source: https://stackoverflow.com/a/32223343
  1977. template<std::size_t... Ints>
  1978. struct index_sequence
  1979. {
  1980. using type = index_sequence;
  1981. using value_type = std::size_t;
  1982. static constexpr std::size_t size() noexcept
  1983. {
  1984. return sizeof...(Ints);
  1985. }
  1986. };
  1987. template<class Sequence1, class Sequence2>
  1988. struct merge_and_renumber;
  1989. template<std::size_t... I1, std::size_t... I2>
  1990. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  1991. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  1992. template<std::size_t N>
  1993. struct make_index_sequence
  1994. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  1995. typename make_index_sequence < N - N / 2 >::type > {};
  1996. template<> struct make_index_sequence<0> : index_sequence<> {};
  1997. template<> struct make_index_sequence<1> : index_sequence<0> {};
  1998. template<typename... Ts>
  1999. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2000. // dispatch utility (taken from ranges-v3)
  2001. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2002. template<> struct priority_tag<0> {};
  2003. // taken from ranges-v3
  2004. template<typename T>
  2005. struct static_const
  2006. {
  2007. static constexpr T value{};
  2008. };
  2009. template<typename T>
  2010. constexpr T static_const<T>::value;
  2011. } // namespace detail
  2012. } // namespace nlohmann
  2013. // #include <nlohmann/detail/meta/type_traits.hpp>
  2014. #include <ciso646> // not
  2015. #include <limits> // numeric_limits
  2016. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2017. #include <utility> // declval
  2018. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2019. #include <iterator> // random_access_iterator_tag
  2020. // #include <nlohmann/detail/meta/void_t.hpp>
  2021. namespace nlohmann
  2022. {
  2023. namespace detail
  2024. {
  2025. template <typename ...Ts> struct make_void
  2026. {
  2027. using type = void;
  2028. };
  2029. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2030. } // namespace detail
  2031. } // namespace nlohmann
  2032. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2033. namespace nlohmann
  2034. {
  2035. namespace detail
  2036. {
  2037. template <typename It, typename = void>
  2038. struct iterator_types {};
  2039. template <typename It>
  2040. struct iterator_types <
  2041. It,
  2042. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2043. typename It::reference, typename It::iterator_category >>
  2044. {
  2045. using difference_type = typename It::difference_type;
  2046. using value_type = typename It::value_type;
  2047. using pointer = typename It::pointer;
  2048. using reference = typename It::reference;
  2049. using iterator_category = typename It::iterator_category;
  2050. };
  2051. // This is required as some compilers implement std::iterator_traits in a way that
  2052. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2053. template <typename T, typename = void>
  2054. struct iterator_traits
  2055. {
  2056. };
  2057. template <typename T>
  2058. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2059. : iterator_types<T>
  2060. {
  2061. };
  2062. template <typename T>
  2063. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2064. {
  2065. using iterator_category = std::random_access_iterator_tag;
  2066. using value_type = T;
  2067. using difference_type = ptrdiff_t;
  2068. using pointer = T*;
  2069. using reference = T&;
  2070. };
  2071. } // namespace detail
  2072. } // namespace nlohmann
  2073. // #include <nlohmann/detail/macro_scope.hpp>
  2074. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2075. // #include <nlohmann/detail/meta/detected.hpp>
  2076. #include <type_traits>
  2077. // #include <nlohmann/detail/meta/void_t.hpp>
  2078. // http://en.cppreference.com/w/cpp/experimental/is_detected
  2079. namespace nlohmann
  2080. {
  2081. namespace detail
  2082. {
  2083. struct nonesuch
  2084. {
  2085. nonesuch() = delete;
  2086. ~nonesuch() = delete;
  2087. nonesuch(nonesuch const&) = delete;
  2088. nonesuch(nonesuch const&&) = delete;
  2089. void operator=(nonesuch const&) = delete;
  2090. void operator=(nonesuch&&) = delete;
  2091. };
  2092. template <class Default,
  2093. class AlwaysVoid,
  2094. template <class...> class Op,
  2095. class... Args>
  2096. struct detector
  2097. {
  2098. using value_t = std::false_type;
  2099. using type = Default;
  2100. };
  2101. template <class Default, template <class...> class Op, class... Args>
  2102. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2103. {
  2104. using value_t = std::true_type;
  2105. using type = Op<Args...>;
  2106. };
  2107. template <template <class...> class Op, class... Args>
  2108. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2109. template <template <class...> class Op, class... Args>
  2110. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2111. template <class Default, template <class...> class Op, class... Args>
  2112. using detected_or = detector<Default, void, Op, Args...>;
  2113. template <class Default, template <class...> class Op, class... Args>
  2114. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2115. template <class Expected, template <class...> class Op, class... Args>
  2116. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2117. template <class To, template <class...> class Op, class... Args>
  2118. using is_detected_convertible =
  2119. std::is_convertible<detected_t<Op, Args...>, To>;
  2120. } // namespace detail
  2121. } // namespace nlohmann
  2122. // #include <nlohmann/json_fwd.hpp>
  2123. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2124. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2125. #include <cstdint> // int64_t, uint64_t
  2126. #include <map> // map
  2127. #include <memory> // allocator
  2128. #include <string> // string
  2129. #include <vector> // vector
  2130. /*!
  2131. @brief namespace for Niels Lohmann
  2132. @see https://github.com/nlohmann
  2133. @since version 1.0.0
  2134. */
  2135. namespace nlohmann
  2136. {
  2137. /*!
  2138. @brief default JSONSerializer template argument
  2139. This serializer ignores the template arguments and uses ADL
  2140. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2141. for serialization.
  2142. */
  2143. template<typename T = void, typename SFINAE = void>
  2144. struct adl_serializer;
  2145. template<template<typename U, typename V, typename... Args> class ObjectType =
  2146. std::map,
  2147. template<typename U, typename... Args> class ArrayType = std::vector,
  2148. class StringType = std::string, class BooleanType = bool,
  2149. class NumberIntegerType = std::int64_t,
  2150. class NumberUnsignedType = std::uint64_t,
  2151. class NumberFloatType = double,
  2152. template<typename U> class AllocatorType = std::allocator,
  2153. template<typename T, typename SFINAE = void> class JSONSerializer =
  2154. adl_serializer>
  2155. class basic_json;
  2156. /*!
  2157. @brief JSON Pointer
  2158. A JSON pointer defines a string syntax for identifying a specific value
  2159. within a JSON document. It can be used with functions `at` and
  2160. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2161. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2162. @since version 2.0.0
  2163. */
  2164. template<typename BasicJsonType>
  2165. class json_pointer;
  2166. /*!
  2167. @brief default JSON class
  2168. This type is the default specialization of the @ref basic_json class which
  2169. uses the standard template types.
  2170. @since version 1.0.0
  2171. */
  2172. using json = basic_json<>;
  2173. } // namespace nlohmann
  2174. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2175. namespace nlohmann
  2176. {
  2177. /*!
  2178. @brief detail namespace with internal helper functions
  2179. This namespace collects functions that should not be exposed,
  2180. implementations of some @ref basic_json methods, and meta-programming helpers.
  2181. @since version 2.1.0
  2182. */
  2183. namespace detail
  2184. {
  2185. /////////////
  2186. // helpers //
  2187. /////////////
  2188. // Note to maintainers:
  2189. //
  2190. // Every trait in this file expects a non CV-qualified type.
  2191. // The only exceptions are in the 'aliases for detected' section
  2192. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2193. //
  2194. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2195. // (e.g. to_json(BasicJsonType&, const T&))
  2196. template<typename> struct is_basic_json : std::false_type {};
  2197. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2198. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2199. //////////////////////////
  2200. // aliases for detected //
  2201. //////////////////////////
  2202. template <typename T>
  2203. using mapped_type_t = typename T::mapped_type;
  2204. template <typename T>
  2205. using key_type_t = typename T::key_type;
  2206. template <typename T>
  2207. using value_type_t = typename T::value_type;
  2208. template <typename T>
  2209. using difference_type_t = typename T::difference_type;
  2210. template <typename T>
  2211. using pointer_t = typename T::pointer;
  2212. template <typename T>
  2213. using reference_t = typename T::reference;
  2214. template <typename T>
  2215. using iterator_category_t = typename T::iterator_category;
  2216. template <typename T>
  2217. using iterator_t = typename T::iterator;
  2218. template <typename T, typename... Args>
  2219. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2220. template <typename T, typename... Args>
  2221. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2222. template <typename T, typename U>
  2223. using get_template_function = decltype(std::declval<T>().template get<U>());
  2224. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2225. template <typename BasicJsonType, typename T, typename = void>
  2226. struct has_from_json : std::false_type {};
  2227. template <typename BasicJsonType, typename T>
  2228. struct has_from_json<BasicJsonType, T,
  2229. enable_if_t<not is_basic_json<T>::value>>
  2230. {
  2231. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2232. static constexpr bool value =
  2233. is_detected_exact<void, from_json_function, serializer,
  2234. const BasicJsonType&, T&>::value;
  2235. };
  2236. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2237. // this overload is used for non-default-constructible user-defined-types
  2238. template <typename BasicJsonType, typename T, typename = void>
  2239. struct has_non_default_from_json : std::false_type {};
  2240. template<typename BasicJsonType, typename T>
  2241. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2242. {
  2243. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2244. static constexpr bool value =
  2245. is_detected_exact<T, from_json_function, serializer,
  2246. const BasicJsonType&>::value;
  2247. };
  2248. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2249. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2250. template <typename BasicJsonType, typename T, typename = void>
  2251. struct has_to_json : std::false_type {};
  2252. template <typename BasicJsonType, typename T>
  2253. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2254. {
  2255. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2256. static constexpr bool value =
  2257. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2258. T>::value;
  2259. };
  2260. ///////////////////
  2261. // is_ functions //
  2262. ///////////////////
  2263. template <typename T, typename = void>
  2264. struct is_iterator_traits : std::false_type {};
  2265. template <typename T>
  2266. struct is_iterator_traits<iterator_traits<T>>
  2267. {
  2268. private:
  2269. using traits = iterator_traits<T>;
  2270. public:
  2271. static constexpr auto value =
  2272. is_detected<value_type_t, traits>::value &&
  2273. is_detected<difference_type_t, traits>::value &&
  2274. is_detected<pointer_t, traits>::value &&
  2275. is_detected<iterator_category_t, traits>::value &&
  2276. is_detected<reference_t, traits>::value;
  2277. };
  2278. // source: https://stackoverflow.com/a/37193089/4116453
  2279. template <typename T, typename = void>
  2280. struct is_complete_type : std::false_type {};
  2281. template <typename T>
  2282. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2283. template <typename BasicJsonType, typename CompatibleObjectType,
  2284. typename = void>
  2285. struct is_compatible_object_type_impl : std::false_type {};
  2286. template <typename BasicJsonType, typename CompatibleObjectType>
  2287. struct is_compatible_object_type_impl <
  2288. BasicJsonType, CompatibleObjectType,
  2289. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  2290. is_detected<key_type_t, CompatibleObjectType>::value >>
  2291. {
  2292. using object_t = typename BasicJsonType::object_t;
  2293. // macOS's is_constructible does not play well with nonesuch...
  2294. static constexpr bool value =
  2295. std::is_constructible<typename object_t::key_type,
  2296. typename CompatibleObjectType::key_type>::value and
  2297. std::is_constructible<typename object_t::mapped_type,
  2298. typename CompatibleObjectType::mapped_type>::value;
  2299. };
  2300. template <typename BasicJsonType, typename CompatibleObjectType>
  2301. struct is_compatible_object_type
  2302. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2303. template <typename BasicJsonType, typename ConstructibleObjectType,
  2304. typename = void>
  2305. struct is_constructible_object_type_impl : std::false_type {};
  2306. template <typename BasicJsonType, typename ConstructibleObjectType>
  2307. struct is_constructible_object_type_impl <
  2308. BasicJsonType, ConstructibleObjectType,
  2309. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  2310. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2311. {
  2312. using object_t = typename BasicJsonType::object_t;
  2313. static constexpr bool value =
  2314. (std::is_default_constructible<ConstructibleObjectType>::value and
  2315. (std::is_move_assignable<ConstructibleObjectType>::value or
  2316. std::is_copy_assignable<ConstructibleObjectType>::value) and
  2317. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2318. typename object_t::key_type>::value and
  2319. std::is_same <
  2320. typename object_t::mapped_type,
  2321. typename ConstructibleObjectType::mapped_type >::value)) or
  2322. (has_from_json<BasicJsonType,
  2323. typename ConstructibleObjectType::mapped_type>::value or
  2324. has_non_default_from_json <
  2325. BasicJsonType,
  2326. typename ConstructibleObjectType::mapped_type >::value);
  2327. };
  2328. template <typename BasicJsonType, typename ConstructibleObjectType>
  2329. struct is_constructible_object_type
  2330. : is_constructible_object_type_impl<BasicJsonType,
  2331. ConstructibleObjectType> {};
  2332. template <typename BasicJsonType, typename CompatibleStringType,
  2333. typename = void>
  2334. struct is_compatible_string_type_impl : std::false_type {};
  2335. template <typename BasicJsonType, typename CompatibleStringType>
  2336. struct is_compatible_string_type_impl <
  2337. BasicJsonType, CompatibleStringType,
  2338. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2339. value_type_t, CompatibleStringType>::value >>
  2340. {
  2341. static constexpr auto value =
  2342. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2343. };
  2344. template <typename BasicJsonType, typename ConstructibleStringType>
  2345. struct is_compatible_string_type
  2346. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2347. template <typename BasicJsonType, typename ConstructibleStringType,
  2348. typename = void>
  2349. struct is_constructible_string_type_impl : std::false_type {};
  2350. template <typename BasicJsonType, typename ConstructibleStringType>
  2351. struct is_constructible_string_type_impl <
  2352. BasicJsonType, ConstructibleStringType,
  2353. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2354. value_type_t, ConstructibleStringType>::value >>
  2355. {
  2356. static constexpr auto value =
  2357. std::is_constructible<ConstructibleStringType,
  2358. typename BasicJsonType::string_t>::value;
  2359. };
  2360. template <typename BasicJsonType, typename ConstructibleStringType>
  2361. struct is_constructible_string_type
  2362. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2363. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2364. struct is_compatible_array_type_impl : std::false_type {};
  2365. template <typename BasicJsonType, typename CompatibleArrayType>
  2366. struct is_compatible_array_type_impl <
  2367. BasicJsonType, CompatibleArrayType,
  2368. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  2369. is_detected<iterator_t, CompatibleArrayType>::value and
  2370. // This is needed because json_reverse_iterator has a ::iterator type...
  2371. // Therefore it is detected as a CompatibleArrayType.
  2372. // The real fix would be to have an Iterable concept.
  2373. not is_iterator_traits<
  2374. iterator_traits<CompatibleArrayType>>::value >>
  2375. {
  2376. static constexpr bool value =
  2377. std::is_constructible<BasicJsonType,
  2378. typename CompatibleArrayType::value_type>::value;
  2379. };
  2380. template <typename BasicJsonType, typename CompatibleArrayType>
  2381. struct is_compatible_array_type
  2382. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2383. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2384. struct is_constructible_array_type_impl : std::false_type {};
  2385. template <typename BasicJsonType, typename ConstructibleArrayType>
  2386. struct is_constructible_array_type_impl <
  2387. BasicJsonType, ConstructibleArrayType,
  2388. enable_if_t<std::is_same<ConstructibleArrayType,
  2389. typename BasicJsonType::value_type>::value >>
  2390. : std::true_type {};
  2391. template <typename BasicJsonType, typename ConstructibleArrayType>
  2392. struct is_constructible_array_type_impl <
  2393. BasicJsonType, ConstructibleArrayType,
  2394. enable_if_t<not std::is_same<ConstructibleArrayType,
  2395. typename BasicJsonType::value_type>::value and
  2396. std::is_default_constructible<ConstructibleArrayType>::value and
  2397. (std::is_move_assignable<ConstructibleArrayType>::value or
  2398. std::is_copy_assignable<ConstructibleArrayType>::value) and
  2399. is_detected<value_type_t, ConstructibleArrayType>::value and
  2400. is_detected<iterator_t, ConstructibleArrayType>::value and
  2401. is_complete_type<
  2402. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  2403. {
  2404. static constexpr bool value =
  2405. // This is needed because json_reverse_iterator has a ::iterator type,
  2406. // furthermore, std::back_insert_iterator (and other iterators) have a
  2407. // base class `iterator`... Therefore it is detected as a
  2408. // ConstructibleArrayType. The real fix would be to have an Iterable
  2409. // concept.
  2410. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  2411. (std::is_same<typename ConstructibleArrayType::value_type,
  2412. typename BasicJsonType::array_t::value_type>::value or
  2413. has_from_json<BasicJsonType,
  2414. typename ConstructibleArrayType::value_type>::value or
  2415. has_non_default_from_json <
  2416. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2417. };
  2418. template <typename BasicJsonType, typename ConstructibleArrayType>
  2419. struct is_constructible_array_type
  2420. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2421. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  2422. typename = void>
  2423. struct is_compatible_integer_type_impl : std::false_type {};
  2424. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2425. struct is_compatible_integer_type_impl <
  2426. RealIntegerType, CompatibleNumberIntegerType,
  2427. enable_if_t<std::is_integral<RealIntegerType>::value and
  2428. std::is_integral<CompatibleNumberIntegerType>::value and
  2429. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2430. {
  2431. // is there an assert somewhere on overflows?
  2432. using RealLimits = std::numeric_limits<RealIntegerType>;
  2433. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2434. static constexpr auto value =
  2435. std::is_constructible<RealIntegerType,
  2436. CompatibleNumberIntegerType>::value and
  2437. CompatibleLimits::is_integer and
  2438. RealLimits::is_signed == CompatibleLimits::is_signed;
  2439. };
  2440. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2441. struct is_compatible_integer_type
  2442. : is_compatible_integer_type_impl<RealIntegerType,
  2443. CompatibleNumberIntegerType> {};
  2444. template <typename BasicJsonType, typename CompatibleType, typename = void>
  2445. struct is_compatible_type_impl: std::false_type {};
  2446. template <typename BasicJsonType, typename CompatibleType>
  2447. struct is_compatible_type_impl <
  2448. BasicJsonType, CompatibleType,
  2449. enable_if_t<is_complete_type<CompatibleType>::value >>
  2450. {
  2451. static constexpr bool value =
  2452. has_to_json<BasicJsonType, CompatibleType>::value;
  2453. };
  2454. template <typename BasicJsonType, typename CompatibleType>
  2455. struct is_compatible_type
  2456. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2457. } // namespace detail
  2458. } // namespace nlohmann
  2459. // #include <nlohmann/detail/value_t.hpp>
  2460. #include <array> // array
  2461. #include <ciso646> // and
  2462. #include <cstddef> // size_t
  2463. #include <cstdint> // uint8_t
  2464. #include <string> // string
  2465. namespace nlohmann
  2466. {
  2467. namespace detail
  2468. {
  2469. ///////////////////////////
  2470. // JSON type enumeration //
  2471. ///////////////////////////
  2472. /*!
  2473. @brief the JSON type enumeration
  2474. This enumeration collects the different JSON types. It is internally used to
  2475. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2476. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2477. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2478. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2479. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2480. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2481. @ref basic_json::is_structured() rely on it.
  2482. @note There are three enumeration entries (number_integer, number_unsigned, and
  2483. number_float), because the library distinguishes these three types for numbers:
  2484. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2485. @ref basic_json::number_integer_t is used for signed integers, and
  2486. @ref basic_json::number_float_t is used for floating-point numbers or to
  2487. approximate integers which do not fit in the limits of their respective type.
  2488. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2489. value with the default value for a given type
  2490. @since version 1.0.0
  2491. */
  2492. enum class value_t : std::uint8_t
  2493. {
  2494. null, ///< null value
  2495. object, ///< object (unordered set of name/value pairs)
  2496. array, ///< array (ordered collection of values)
  2497. string, ///< string value
  2498. boolean, ///< boolean value
  2499. number_integer, ///< number value (signed integer)
  2500. number_unsigned, ///< number value (unsigned integer)
  2501. number_float, ///< number value (floating-point)
  2502. discarded ///< discarded by the the parser callback function
  2503. };
  2504. /*!
  2505. @brief comparison operator for JSON types
  2506. Returns an ordering that is similar to Python:
  2507. - order: null < boolean < number < object < array < string
  2508. - furthermore, each type is not smaller than itself
  2509. - discarded values are not comparable
  2510. @since version 1.0.0
  2511. */
  2512. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2513. {
  2514. static constexpr std::array<std::uint8_t, 8> order = {{
  2515. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2516. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  2517. }
  2518. };
  2519. const auto l_index = static_cast<std::size_t>(lhs);
  2520. const auto r_index = static_cast<std::size_t>(rhs);
  2521. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  2522. }
  2523. } // namespace detail
  2524. } // namespace nlohmann
  2525. namespace nlohmann
  2526. {
  2527. namespace detail
  2528. {
  2529. template<typename BasicJsonType>
  2530. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2531. {
  2532. if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
  2533. {
  2534. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2535. }
  2536. n = nullptr;
  2537. }
  2538. // overloads for basic_json template parameters
  2539. template<typename BasicJsonType, typename ArithmeticType,
  2540. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  2541. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2542. int> = 0>
  2543. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2544. {
  2545. switch (static_cast<value_t>(j))
  2546. {
  2547. case value_t::number_unsigned:
  2548. {
  2549. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2550. break;
  2551. }
  2552. case value_t::number_integer:
  2553. {
  2554. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2555. break;
  2556. }
  2557. case value_t::number_float:
  2558. {
  2559. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2560. break;
  2561. }
  2562. default:
  2563. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2564. }
  2565. }
  2566. template<typename BasicJsonType>
  2567. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2568. {
  2569. if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
  2570. {
  2571. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2572. }
  2573. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2574. }
  2575. template<typename BasicJsonType>
  2576. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2577. {
  2578. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2579. {
  2580. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2581. }
  2582. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2583. }
  2584. template <
  2585. typename BasicJsonType, typename ConstructibleStringType,
  2586. enable_if_t <
  2587. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  2588. not std::is_same<typename BasicJsonType::string_t,
  2589. ConstructibleStringType>::value,
  2590. int > = 0 >
  2591. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2592. {
  2593. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2594. {
  2595. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2596. }
  2597. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2598. }
  2599. template<typename BasicJsonType>
  2600. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2601. {
  2602. get_arithmetic_value(j, val);
  2603. }
  2604. template<typename BasicJsonType>
  2605. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2606. {
  2607. get_arithmetic_value(j, val);
  2608. }
  2609. template<typename BasicJsonType>
  2610. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2611. {
  2612. get_arithmetic_value(j, val);
  2613. }
  2614. template<typename BasicJsonType, typename EnumType,
  2615. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2616. void from_json(const BasicJsonType& j, EnumType& e)
  2617. {
  2618. typename std::underlying_type<EnumType>::type val;
  2619. get_arithmetic_value(j, val);
  2620. e = static_cast<EnumType>(val);
  2621. }
  2622. // forward_list doesn't have an insert method
  2623. template<typename BasicJsonType, typename T, typename Allocator,
  2624. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2625. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  2626. {
  2627. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2628. {
  2629. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2630. }
  2631. l.clear();
  2632. std::transform(j.rbegin(), j.rend(),
  2633. std::front_inserter(l), [](const BasicJsonType & i)
  2634. {
  2635. return i.template get<T>();
  2636. });
  2637. }
  2638. // valarray doesn't have an insert method
  2639. template<typename BasicJsonType, typename T,
  2640. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2641. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  2642. {
  2643. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2644. {
  2645. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2646. }
  2647. l.resize(j.size());
  2648. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  2649. }
  2650. template <typename BasicJsonType, typename T, std::size_t N>
  2651. auto from_json(const BasicJsonType& j, T (&arr)[N])
  2652. -> decltype(j.template get<T>(), void())
  2653. {
  2654. for (std::size_t i = 0; i < N; ++i)
  2655. {
  2656. arr[i] = j.at(i).template get<T>();
  2657. }
  2658. }
  2659. template<typename BasicJsonType>
  2660. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  2661. {
  2662. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  2663. }
  2664. template <typename BasicJsonType, typename T, std::size_t N>
  2665. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  2666. priority_tag<2> /*unused*/)
  2667. -> decltype(j.template get<T>(), void())
  2668. {
  2669. for (std::size_t i = 0; i < N; ++i)
  2670. {
  2671. arr[i] = j.at(i).template get<T>();
  2672. }
  2673. }
  2674. template<typename BasicJsonType, typename ConstructibleArrayType>
  2675. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  2676. -> decltype(
  2677. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  2678. j.template get<typename ConstructibleArrayType::value_type>(),
  2679. void())
  2680. {
  2681. using std::end;
  2682. ConstructibleArrayType ret;
  2683. ret.reserve(j.size());
  2684. std::transform(j.begin(), j.end(),
  2685. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  2686. {
  2687. // get<BasicJsonType>() returns *this, this won't call a from_json
  2688. // method when value_type is BasicJsonType
  2689. return i.template get<typename ConstructibleArrayType::value_type>();
  2690. });
  2691. arr = std::move(ret);
  2692. }
  2693. template <typename BasicJsonType, typename ConstructibleArrayType>
  2694. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  2695. priority_tag<0> /*unused*/)
  2696. {
  2697. using std::end;
  2698. ConstructibleArrayType ret;
  2699. std::transform(
  2700. j.begin(), j.end(), std::inserter(ret, end(ret)),
  2701. [](const BasicJsonType & i)
  2702. {
  2703. // get<BasicJsonType>() returns *this, this won't call a from_json
  2704. // method when value_type is BasicJsonType
  2705. return i.template get<typename ConstructibleArrayType::value_type>();
  2706. });
  2707. arr = std::move(ret);
  2708. }
  2709. template <typename BasicJsonType, typename ConstructibleArrayType,
  2710. enable_if_t <
  2711. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  2712. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  2713. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  2714. not is_basic_json<ConstructibleArrayType>::value,
  2715. int > = 0 >
  2716. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  2717. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  2718. j.template get<typename ConstructibleArrayType::value_type>(),
  2719. void())
  2720. {
  2721. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2722. {
  2723. JSON_THROW(type_error::create(302, "type must be array, but is " +
  2724. std::string(j.type_name())));
  2725. }
  2726. from_json_array_impl(j, arr, priority_tag<3> {});
  2727. }
  2728. template<typename BasicJsonType, typename ConstructibleObjectType,
  2729. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  2730. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  2731. {
  2732. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  2733. {
  2734. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  2735. }
  2736. ConstructibleObjectType ret;
  2737. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  2738. using value_type = typename ConstructibleObjectType::value_type;
  2739. std::transform(
  2740. inner_object->begin(), inner_object->end(),
  2741. std::inserter(ret, ret.begin()),
  2742. [](typename BasicJsonType::object_t::value_type const & p)
  2743. {
  2744. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  2745. });
  2746. obj = std::move(ret);
  2747. }
  2748. // overload for arithmetic types, not chosen for basic_json template arguments
  2749. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  2750. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  2751. // an arithmetic type?
  2752. template<typename BasicJsonType, typename ArithmeticType,
  2753. enable_if_t <
  2754. std::is_arithmetic<ArithmeticType>::value and
  2755. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  2756. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  2757. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  2758. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2759. int> = 0>
  2760. void from_json(const BasicJsonType& j, ArithmeticType& val)
  2761. {
  2762. switch (static_cast<value_t>(j))
  2763. {
  2764. case value_t::number_unsigned:
  2765. {
  2766. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2767. break;
  2768. }
  2769. case value_t::number_integer:
  2770. {
  2771. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2772. break;
  2773. }
  2774. case value_t::number_float:
  2775. {
  2776. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2777. break;
  2778. }
  2779. case value_t::boolean:
  2780. {
  2781. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  2782. break;
  2783. }
  2784. default:
  2785. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2786. }
  2787. }
  2788. template<typename BasicJsonType, typename A1, typename A2>
  2789. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  2790. {
  2791. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  2792. }
  2793. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  2794. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  2795. {
  2796. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  2797. }
  2798. template<typename BasicJsonType, typename... Args>
  2799. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  2800. {
  2801. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  2802. }
  2803. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  2804. typename = enable_if_t<not std::is_constructible<
  2805. typename BasicJsonType::string_t, Key>::value>>
  2806. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  2807. {
  2808. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2809. {
  2810. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2811. }
  2812. m.clear();
  2813. for (const auto& p : j)
  2814. {
  2815. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2816. {
  2817. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2818. }
  2819. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2820. }
  2821. }
  2822. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  2823. typename = enable_if_t<not std::is_constructible<
  2824. typename BasicJsonType::string_t, Key>::value>>
  2825. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  2826. {
  2827. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2828. {
  2829. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2830. }
  2831. m.clear();
  2832. for (const auto& p : j)
  2833. {
  2834. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2835. {
  2836. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2837. }
  2838. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2839. }
  2840. }
  2841. struct from_json_fn
  2842. {
  2843. template<typename BasicJsonType, typename T>
  2844. auto operator()(const BasicJsonType& j, T& val) const
  2845. noexcept(noexcept(from_json(j, val)))
  2846. -> decltype(from_json(j, val), void())
  2847. {
  2848. return from_json(j, val);
  2849. }
  2850. };
  2851. } // namespace detail
  2852. /// namespace to hold default `from_json` function
  2853. /// to see why this is required:
  2854. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  2855. namespace
  2856. {
  2857. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  2858. } // namespace
  2859. } // namespace nlohmann
  2860. // #include <nlohmann/detail/conversions/to_json.hpp>
  2861. #include <algorithm> // copy
  2862. #include <ciso646> // or, and, not
  2863. #include <iterator> // begin, end
  2864. #include <string> // string
  2865. #include <tuple> // tuple, get
  2866. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  2867. #include <utility> // move, forward, declval, pair
  2868. #include <valarray> // valarray
  2869. #include <vector> // vector
  2870. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  2871. #include <cstddef> // size_t
  2872. #include <iterator> // input_iterator_tag
  2873. #include <string> // string, to_string
  2874. #include <tuple> // tuple_size, get, tuple_element
  2875. // #include <nlohmann/detail/meta/type_traits.hpp>
  2876. // #include <nlohmann/detail/value_t.hpp>
  2877. namespace nlohmann
  2878. {
  2879. namespace detail
  2880. {
  2881. template<typename string_type>
  2882. void int_to_string( string_type& target, std::size_t value )
  2883. {
  2884. target = std::to_string(value);
  2885. }
  2886. template <typename IteratorType> class iteration_proxy_value
  2887. {
  2888. public:
  2889. using difference_type = std::ptrdiff_t;
  2890. using value_type = iteration_proxy_value;
  2891. using pointer = value_type * ;
  2892. using reference = value_type & ;
  2893. using iterator_category = std::input_iterator_tag;
  2894. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  2895. private:
  2896. /// the iterator
  2897. IteratorType anchor;
  2898. /// an index for arrays (used to create key names)
  2899. std::size_t array_index = 0;
  2900. /// last stringified array index
  2901. mutable std::size_t array_index_last = 0;
  2902. /// a string representation of the array index
  2903. mutable string_type array_index_str = "0";
  2904. /// an empty string (to return a reference for primitive values)
  2905. const string_type empty_str = "";
  2906. public:
  2907. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  2908. /// dereference operator (needed for range-based for)
  2909. iteration_proxy_value& operator*()
  2910. {
  2911. return *this;
  2912. }
  2913. /// increment operator (needed for range-based for)
  2914. iteration_proxy_value& operator++()
  2915. {
  2916. ++anchor;
  2917. ++array_index;
  2918. return *this;
  2919. }
  2920. /// equality operator (needed for InputIterator)
  2921. bool operator==(const iteration_proxy_value& o) const
  2922. {
  2923. return anchor == o.anchor;
  2924. }
  2925. /// inequality operator (needed for range-based for)
  2926. bool operator!=(const iteration_proxy_value& o) const
  2927. {
  2928. return anchor != o.anchor;
  2929. }
  2930. /// return key of the iterator
  2931. const string_type& key() const
  2932. {
  2933. assert(anchor.m_object != nullptr);
  2934. switch (anchor.m_object->type())
  2935. {
  2936. // use integer array index as key
  2937. case value_t::array:
  2938. {
  2939. if (array_index != array_index_last)
  2940. {
  2941. int_to_string( array_index_str, array_index );
  2942. array_index_last = array_index;
  2943. }
  2944. return array_index_str;
  2945. }
  2946. // use key from the object
  2947. case value_t::object:
  2948. return anchor.key();
  2949. // use an empty key for all primitive types
  2950. default:
  2951. return empty_str;
  2952. }
  2953. }
  2954. /// return value of the iterator
  2955. typename IteratorType::reference value() const
  2956. {
  2957. return anchor.value();
  2958. }
  2959. };
  2960. /// proxy class for the items() function
  2961. template<typename IteratorType> class iteration_proxy
  2962. {
  2963. private:
  2964. /// the container to iterate
  2965. typename IteratorType::reference container;
  2966. public:
  2967. /// construct iteration proxy from a container
  2968. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  2969. : container(cont) {}
  2970. /// return iterator begin (needed for range-based for)
  2971. iteration_proxy_value<IteratorType> begin() noexcept
  2972. {
  2973. return iteration_proxy_value<IteratorType>(container.begin());
  2974. }
  2975. /// return iterator end (needed for range-based for)
  2976. iteration_proxy_value<IteratorType> end() noexcept
  2977. {
  2978. return iteration_proxy_value<IteratorType>(container.end());
  2979. }
  2980. };
  2981. // Structured Bindings Support
  2982. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2983. // And see https://github.com/nlohmann/json/pull/1391
  2984. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  2985. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  2986. {
  2987. return i.key();
  2988. }
  2989. // Structured Bindings Support
  2990. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2991. // And see https://github.com/nlohmann/json/pull/1391
  2992. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  2993. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  2994. {
  2995. return i.value();
  2996. }
  2997. } // namespace detail
  2998. } // namespace nlohmann
  2999. // The Addition to the STD Namespace is required to add
  3000. // Structured Bindings Support to the iteration_proxy_value class
  3001. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3002. // And see https://github.com/nlohmann/json/pull/1391
  3003. namespace std
  3004. {
  3005. #if defined(__clang__)
  3006. // Fix: https://github.com/nlohmann/json/issues/1401
  3007. #pragma clang diagnostic push
  3008. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3009. #endif
  3010. template <typename IteratorType>
  3011. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3012. : public std::integral_constant<std::size_t, 2> {};
  3013. template <std::size_t N, typename IteratorType>
  3014. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3015. {
  3016. public:
  3017. using type = decltype(
  3018. get<N>(std::declval <
  3019. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3020. };
  3021. #if defined(__clang__)
  3022. #pragma clang diagnostic pop
  3023. #endif
  3024. } // namespace std
  3025. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3026. // #include <nlohmann/detail/meta/type_traits.hpp>
  3027. // #include <nlohmann/detail/value_t.hpp>
  3028. namespace nlohmann
  3029. {
  3030. namespace detail
  3031. {
  3032. //////////////////
  3033. // constructors //
  3034. //////////////////
  3035. template<value_t> struct external_constructor;
  3036. template<>
  3037. struct external_constructor<value_t::boolean>
  3038. {
  3039. template<typename BasicJsonType>
  3040. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  3041. {
  3042. j.m_type = value_t::boolean;
  3043. j.m_value = b;
  3044. j.assert_invariant();
  3045. }
  3046. };
  3047. template<>
  3048. struct external_constructor<value_t::string>
  3049. {
  3050. template<typename BasicJsonType>
  3051. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  3052. {
  3053. j.m_type = value_t::string;
  3054. j.m_value = s;
  3055. j.assert_invariant();
  3056. }
  3057. template<typename BasicJsonType>
  3058. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3059. {
  3060. j.m_type = value_t::string;
  3061. j.m_value = std::move(s);
  3062. j.assert_invariant();
  3063. }
  3064. template<typename BasicJsonType, typename CompatibleStringType,
  3065. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  3066. int> = 0>
  3067. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  3068. {
  3069. j.m_type = value_t::string;
  3070. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  3071. j.assert_invariant();
  3072. }
  3073. };
  3074. template<>
  3075. struct external_constructor<value_t::number_float>
  3076. {
  3077. template<typename BasicJsonType>
  3078. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  3079. {
  3080. j.m_type = value_t::number_float;
  3081. j.m_value = val;
  3082. j.assert_invariant();
  3083. }
  3084. };
  3085. template<>
  3086. struct external_constructor<value_t::number_unsigned>
  3087. {
  3088. template<typename BasicJsonType>
  3089. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  3090. {
  3091. j.m_type = value_t::number_unsigned;
  3092. j.m_value = val;
  3093. j.assert_invariant();
  3094. }
  3095. };
  3096. template<>
  3097. struct external_constructor<value_t::number_integer>
  3098. {
  3099. template<typename BasicJsonType>
  3100. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3101. {
  3102. j.m_type = value_t::number_integer;
  3103. j.m_value = val;
  3104. j.assert_invariant();
  3105. }
  3106. };
  3107. template<>
  3108. struct external_constructor<value_t::array>
  3109. {
  3110. template<typename BasicJsonType>
  3111. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3112. {
  3113. j.m_type = value_t::array;
  3114. j.m_value = arr;
  3115. j.assert_invariant();
  3116. }
  3117. template<typename BasicJsonType>
  3118. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3119. {
  3120. j.m_type = value_t::array;
  3121. j.m_value = std::move(arr);
  3122. j.assert_invariant();
  3123. }
  3124. template<typename BasicJsonType, typename CompatibleArrayType,
  3125. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3126. int> = 0>
  3127. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3128. {
  3129. using std::begin;
  3130. using std::end;
  3131. j.m_type = value_t::array;
  3132. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3133. j.assert_invariant();
  3134. }
  3135. template<typename BasicJsonType>
  3136. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3137. {
  3138. j.m_type = value_t::array;
  3139. j.m_value = value_t::array;
  3140. j.m_value.array->reserve(arr.size());
  3141. for (const bool x : arr)
  3142. {
  3143. j.m_value.array->push_back(x);
  3144. }
  3145. j.assert_invariant();
  3146. }
  3147. template<typename BasicJsonType, typename T,
  3148. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3149. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3150. {
  3151. j.m_type = value_t::array;
  3152. j.m_value = value_t::array;
  3153. j.m_value.array->resize(arr.size());
  3154. if (arr.size() > 0)
  3155. {
  3156. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3157. }
  3158. j.assert_invariant();
  3159. }
  3160. };
  3161. template<>
  3162. struct external_constructor<value_t::object>
  3163. {
  3164. template<typename BasicJsonType>
  3165. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3166. {
  3167. j.m_type = value_t::object;
  3168. j.m_value = obj;
  3169. j.assert_invariant();
  3170. }
  3171. template<typename BasicJsonType>
  3172. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3173. {
  3174. j.m_type = value_t::object;
  3175. j.m_value = std::move(obj);
  3176. j.assert_invariant();
  3177. }
  3178. template<typename BasicJsonType, typename CompatibleObjectType,
  3179. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  3180. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3181. {
  3182. using std::begin;
  3183. using std::end;
  3184. j.m_type = value_t::object;
  3185. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3186. j.assert_invariant();
  3187. }
  3188. };
  3189. /////////////
  3190. // to_json //
  3191. /////////////
  3192. template<typename BasicJsonType, typename T,
  3193. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3194. void to_json(BasicJsonType& j, T b) noexcept
  3195. {
  3196. external_constructor<value_t::boolean>::construct(j, b);
  3197. }
  3198. template<typename BasicJsonType, typename CompatibleString,
  3199. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3200. void to_json(BasicJsonType& j, const CompatibleString& s)
  3201. {
  3202. external_constructor<value_t::string>::construct(j, s);
  3203. }
  3204. template<typename BasicJsonType>
  3205. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3206. {
  3207. external_constructor<value_t::string>::construct(j, std::move(s));
  3208. }
  3209. template<typename BasicJsonType, typename FloatType,
  3210. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3211. void to_json(BasicJsonType& j, FloatType val) noexcept
  3212. {
  3213. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3214. }
  3215. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3216. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3217. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3218. {
  3219. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3220. }
  3221. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3222. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3223. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3224. {
  3225. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3226. }
  3227. template<typename BasicJsonType, typename EnumType,
  3228. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3229. void to_json(BasicJsonType& j, EnumType e) noexcept
  3230. {
  3231. using underlying_type = typename std::underlying_type<EnumType>::type;
  3232. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3233. }
  3234. template<typename BasicJsonType>
  3235. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3236. {
  3237. external_constructor<value_t::array>::construct(j, e);
  3238. }
  3239. template <typename BasicJsonType, typename CompatibleArrayType,
  3240. enable_if_t<is_compatible_array_type<BasicJsonType,
  3241. CompatibleArrayType>::value and
  3242. not is_compatible_object_type<
  3243. BasicJsonType, CompatibleArrayType>::value and
  3244. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  3245. not is_basic_json<CompatibleArrayType>::value,
  3246. int> = 0>
  3247. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3248. {
  3249. external_constructor<value_t::array>::construct(j, arr);
  3250. }
  3251. template<typename BasicJsonType, typename T,
  3252. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3253. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3254. {
  3255. external_constructor<value_t::array>::construct(j, std::move(arr));
  3256. }
  3257. template<typename BasicJsonType>
  3258. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3259. {
  3260. external_constructor<value_t::array>::construct(j, std::move(arr));
  3261. }
  3262. template<typename BasicJsonType, typename CompatibleObjectType,
  3263. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  3264. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3265. {
  3266. external_constructor<value_t::object>::construct(j, obj);
  3267. }
  3268. template<typename BasicJsonType>
  3269. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3270. {
  3271. external_constructor<value_t::object>::construct(j, std::move(obj));
  3272. }
  3273. template <
  3274. typename BasicJsonType, typename T, std::size_t N,
  3275. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  3276. const T(&)[N]>::value,
  3277. int> = 0 >
  3278. void to_json(BasicJsonType& j, const T(&arr)[N])
  3279. {
  3280. external_constructor<value_t::array>::construct(j, arr);
  3281. }
  3282. template<typename BasicJsonType, typename... Args>
  3283. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  3284. {
  3285. j = { p.first, p.second };
  3286. }
  3287. // for https://github.com/nlohmann/json/pull/1134
  3288. template < typename BasicJsonType, typename T,
  3289. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3290. void to_json(BasicJsonType& j, const T& b)
  3291. {
  3292. j = { {b.key(), b.value()} };
  3293. }
  3294. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3295. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3296. {
  3297. j = { std::get<Idx>(t)... };
  3298. }
  3299. template<typename BasicJsonType, typename... Args>
  3300. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  3301. {
  3302. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3303. }
  3304. struct to_json_fn
  3305. {
  3306. template<typename BasicJsonType, typename T>
  3307. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3308. -> decltype(to_json(j, std::forward<T>(val)), void())
  3309. {
  3310. return to_json(j, std::forward<T>(val));
  3311. }
  3312. };
  3313. } // namespace detail
  3314. /// namespace to hold default `to_json` function
  3315. namespace
  3316. {
  3317. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3318. } // namespace
  3319. } // namespace nlohmann
  3320. namespace nlohmann
  3321. {
  3322. template<typename, typename>
  3323. struct adl_serializer
  3324. {
  3325. /*!
  3326. @brief convert a JSON value to any value type
  3327. This function is usually called by the `get()` function of the
  3328. @ref basic_json class (either explicit or via conversion operators).
  3329. @param[in] j JSON value to read from
  3330. @param[in,out] val value to write to
  3331. */
  3332. template<typename BasicJsonType, typename ValueType>
  3333. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3334. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3335. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3336. {
  3337. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3338. }
  3339. /*!
  3340. @brief convert any value type to a JSON value
  3341. This function is usually called by the constructors of the @ref basic_json
  3342. class.
  3343. @param[in,out] j JSON value to write to
  3344. @param[in] val value to read from
  3345. */
  3346. template <typename BasicJsonType, typename ValueType>
  3347. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3348. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3349. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3350. {
  3351. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3352. }
  3353. };
  3354. } // namespace nlohmann
  3355. // #include <nlohmann/detail/conversions/from_json.hpp>
  3356. // #include <nlohmann/detail/conversions/to_json.hpp>
  3357. // #include <nlohmann/detail/exceptions.hpp>
  3358. // #include <nlohmann/detail/input/binary_reader.hpp>
  3359. #include <algorithm> // generate_n
  3360. #include <array> // array
  3361. #include <cassert> // assert
  3362. #include <cmath> // ldexp
  3363. #include <cstddef> // size_t
  3364. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3365. #include <cstdio> // snprintf
  3366. #include <cstring> // memcpy
  3367. #include <iterator> // back_inserter
  3368. #include <limits> // numeric_limits
  3369. #include <string> // char_traits, string
  3370. #include <utility> // make_pair, move
  3371. // #include <nlohmann/detail/exceptions.hpp>
  3372. // #include <nlohmann/detail/input/input_adapters.hpp>
  3373. #include <array> // array
  3374. #include <cassert> // assert
  3375. #include <cstddef> // size_t
  3376. #include <cstdio> //FILE *
  3377. #include <cstring> // strlen
  3378. #include <istream> // istream
  3379. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3380. #include <memory> // shared_ptr, make_shared, addressof
  3381. #include <numeric> // accumulate
  3382. #include <string> // string, char_traits
  3383. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3384. #include <utility> // pair, declval
  3385. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3386. // #include <nlohmann/detail/macro_scope.hpp>
  3387. namespace nlohmann
  3388. {
  3389. namespace detail
  3390. {
  3391. /// the supported input formats
  3392. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3393. ////////////////////
  3394. // input adapters //
  3395. ////////////////////
  3396. /*!
  3397. @brief abstract input adapter interface
  3398. Produces a stream of std::char_traits<char>::int_type characters from a
  3399. std::istream, a buffer, or some other input type. Accepts the return of
  3400. exactly one non-EOF character for future input. The int_type characters
  3401. returned consist of all valid char values as positive values (typically
  3402. unsigned char), plus an EOF value outside that range, specified by the value
  3403. of the function std::char_traits<char>::eof(). This value is typically -1, but
  3404. could be any arbitrary value which is not a valid char value.
  3405. */
  3406. struct input_adapter_protocol
  3407. {
  3408. /// get a character [0,255] or std::char_traits<char>::eof().
  3409. virtual std::char_traits<char>::int_type get_character() = 0;
  3410. virtual ~input_adapter_protocol() = default;
  3411. };
  3412. /// a type to simplify interfaces
  3413. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  3414. /*!
  3415. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3416. buffer. This adapter is a very low level adapter.
  3417. */
  3418. class file_input_adapter : public input_adapter_protocol
  3419. {
  3420. public:
  3421. JSON_HEDLEY_NON_NULL(2)
  3422. explicit file_input_adapter(std::FILE* f) noexcept
  3423. : m_file(f)
  3424. {}
  3425. // make class move-only
  3426. file_input_adapter(const file_input_adapter&) = delete;
  3427. file_input_adapter(file_input_adapter&&) = default;
  3428. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3429. file_input_adapter& operator=(file_input_adapter&&) = default;
  3430. ~file_input_adapter() override = default;
  3431. std::char_traits<char>::int_type get_character() noexcept override
  3432. {
  3433. return std::fgetc(m_file);
  3434. }
  3435. private:
  3436. /// the file pointer to read from
  3437. std::FILE* m_file;
  3438. };
  3439. /*!
  3440. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3441. beginning of input. Does not support changing the underlying std::streambuf
  3442. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3443. subsequent use of standard std::istream operations to process any input
  3444. characters following those used in parsing the JSON input. Clears the
  3445. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3446. subsequent call for input from the std::istream.
  3447. */
  3448. class input_stream_adapter : public input_adapter_protocol
  3449. {
  3450. public:
  3451. ~input_stream_adapter() override
  3452. {
  3453. // clear stream flags; we use underlying streambuf I/O, do not
  3454. // maintain ifstream flags, except eof
  3455. is.clear(is.rdstate() & std::ios::eofbit);
  3456. }
  3457. explicit input_stream_adapter(std::istream& i)
  3458. : is(i), sb(*i.rdbuf())
  3459. {}
  3460. // delete because of pointer members
  3461. input_stream_adapter(const input_stream_adapter&) = delete;
  3462. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3463. input_stream_adapter(input_stream_adapter&&) = delete;
  3464. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  3465. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3466. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3467. // end up as the same value, eg. 0xFFFFFFFF.
  3468. std::char_traits<char>::int_type get_character() override
  3469. {
  3470. auto res = sb.sbumpc();
  3471. // set eof manually, as we don't use the istream interface.
  3472. if (res == EOF)
  3473. {
  3474. is.clear(is.rdstate() | std::ios::eofbit);
  3475. }
  3476. return res;
  3477. }
  3478. private:
  3479. /// the associated input stream
  3480. std::istream& is;
  3481. std::streambuf& sb;
  3482. };
  3483. /// input adapter for buffer input
  3484. class input_buffer_adapter : public input_adapter_protocol
  3485. {
  3486. public:
  3487. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3488. : cursor(b), limit(b == nullptr ? nullptr : (b + l))
  3489. {}
  3490. // delete because of pointer members
  3491. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3492. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3493. input_buffer_adapter(input_buffer_adapter&&) = delete;
  3494. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3495. ~input_buffer_adapter() override = default;
  3496. std::char_traits<char>::int_type get_character() noexcept override
  3497. {
  3498. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3499. {
  3500. assert(cursor != nullptr and limit != nullptr);
  3501. return std::char_traits<char>::to_int_type(*(cursor++));
  3502. }
  3503. return std::char_traits<char>::eof();
  3504. }
  3505. private:
  3506. /// pointer to the current character
  3507. const char* cursor;
  3508. /// pointer past the last character
  3509. const char* const limit;
  3510. };
  3511. template<typename WideStringType, size_t T>
  3512. struct wide_string_input_helper
  3513. {
  3514. // UTF-32
  3515. static void fill_buffer(const WideStringType& str,
  3516. size_t& current_wchar,
  3517. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3518. size_t& utf8_bytes_index,
  3519. size_t& utf8_bytes_filled)
  3520. {
  3521. utf8_bytes_index = 0;
  3522. if (current_wchar == str.size())
  3523. {
  3524. utf8_bytes[0] = std::char_traits<char>::eof();
  3525. utf8_bytes_filled = 1;
  3526. }
  3527. else
  3528. {
  3529. // get the current character
  3530. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3531. // UTF-32 to UTF-8 encoding
  3532. if (wc < 0x80)
  3533. {
  3534. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3535. utf8_bytes_filled = 1;
  3536. }
  3537. else if (wc <= 0x7FF)
  3538. {
  3539. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  3540. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3541. utf8_bytes_filled = 2;
  3542. }
  3543. else if (wc <= 0xFFFF)
  3544. {
  3545. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  3546. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3547. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3548. utf8_bytes_filled = 3;
  3549. }
  3550. else if (wc <= 0x10FFFF)
  3551. {
  3552. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  3553. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  3554. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3555. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3556. utf8_bytes_filled = 4;
  3557. }
  3558. else
  3559. {
  3560. // unknown character
  3561. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3562. utf8_bytes_filled = 1;
  3563. }
  3564. }
  3565. }
  3566. };
  3567. template<typename WideStringType>
  3568. struct wide_string_input_helper<WideStringType, 2>
  3569. {
  3570. // UTF-16
  3571. static void fill_buffer(const WideStringType& str,
  3572. size_t& current_wchar,
  3573. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3574. size_t& utf8_bytes_index,
  3575. size_t& utf8_bytes_filled)
  3576. {
  3577. utf8_bytes_index = 0;
  3578. if (current_wchar == str.size())
  3579. {
  3580. utf8_bytes[0] = std::char_traits<char>::eof();
  3581. utf8_bytes_filled = 1;
  3582. }
  3583. else
  3584. {
  3585. // get the current character
  3586. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3587. // UTF-16 to UTF-8 encoding
  3588. if (wc < 0x80)
  3589. {
  3590. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3591. utf8_bytes_filled = 1;
  3592. }
  3593. else if (wc <= 0x7FF)
  3594. {
  3595. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  3596. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3597. utf8_bytes_filled = 2;
  3598. }
  3599. else if (0xD800 > wc or wc >= 0xE000)
  3600. {
  3601. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  3602. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3603. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3604. utf8_bytes_filled = 3;
  3605. }
  3606. else
  3607. {
  3608. if (current_wchar < str.size())
  3609. {
  3610. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  3611. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  3612. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  3613. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  3614. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  3615. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  3616. utf8_bytes_filled = 4;
  3617. }
  3618. else
  3619. {
  3620. // unknown character
  3621. ++current_wchar;
  3622. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3623. utf8_bytes_filled = 1;
  3624. }
  3625. }
  3626. }
  3627. }
  3628. };
  3629. template<typename WideStringType>
  3630. class wide_string_input_adapter : public input_adapter_protocol
  3631. {
  3632. public:
  3633. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  3634. : str(w)
  3635. {}
  3636. std::char_traits<char>::int_type get_character() noexcept override
  3637. {
  3638. // check if buffer needs to be filled
  3639. if (utf8_bytes_index == utf8_bytes_filled)
  3640. {
  3641. fill_buffer<sizeof(typename WideStringType::value_type)>();
  3642. assert(utf8_bytes_filled > 0);
  3643. assert(utf8_bytes_index == 0);
  3644. }
  3645. // use buffer
  3646. assert(utf8_bytes_filled > 0);
  3647. assert(utf8_bytes_index < utf8_bytes_filled);
  3648. return utf8_bytes[utf8_bytes_index++];
  3649. }
  3650. private:
  3651. template<size_t T>
  3652. void fill_buffer()
  3653. {
  3654. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  3655. }
  3656. /// the wstring to process
  3657. const WideStringType& str;
  3658. /// index of the current wchar in str
  3659. std::size_t current_wchar = 0;
  3660. /// a buffer for UTF-8 bytes
  3661. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  3662. /// index to the utf8_codes array for the next valid byte
  3663. std::size_t utf8_bytes_index = 0;
  3664. /// number of valid bytes in the utf8_codes array
  3665. std::size_t utf8_bytes_filled = 0;
  3666. };
  3667. class input_adapter
  3668. {
  3669. public:
  3670. // native support
  3671. JSON_HEDLEY_NON_NULL(2)
  3672. input_adapter(std::FILE* file)
  3673. : ia(std::make_shared<file_input_adapter>(file)) {}
  3674. /// input adapter for input stream
  3675. input_adapter(std::istream& i)
  3676. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3677. /// input adapter for input stream
  3678. input_adapter(std::istream&& i)
  3679. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3680. input_adapter(const std::wstring& ws)
  3681. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  3682. input_adapter(const std::u16string& ws)
  3683. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  3684. input_adapter(const std::u32string& ws)
  3685. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  3686. /// input adapter for buffer
  3687. template<typename CharT,
  3688. typename std::enable_if<
  3689. std::is_pointer<CharT>::value and
  3690. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3691. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3692. int>::type = 0>
  3693. input_adapter(CharT b, std::size_t l)
  3694. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  3695. // derived support
  3696. /// input adapter for string literal
  3697. template<typename CharT,
  3698. typename std::enable_if<
  3699. std::is_pointer<CharT>::value and
  3700. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3701. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3702. int>::type = 0>
  3703. input_adapter(CharT b)
  3704. : input_adapter(reinterpret_cast<const char*>(b),
  3705. std::strlen(reinterpret_cast<const char*>(b))) {}
  3706. /// input adapter for iterator range with contiguous storage
  3707. template<class IteratorType,
  3708. typename std::enable_if<
  3709. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  3710. int>::type = 0>
  3711. input_adapter(IteratorType first, IteratorType last)
  3712. {
  3713. #ifndef NDEBUG
  3714. // assertion to check that the iterator range is indeed contiguous,
  3715. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  3716. const auto is_contiguous = std::accumulate(
  3717. first, last, std::pair<bool, int>(true, 0),
  3718. [&first](std::pair<bool, int> res, decltype(*first) val)
  3719. {
  3720. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  3721. return res;
  3722. }).first;
  3723. assert(is_contiguous);
  3724. #endif
  3725. // assertion to check that each element is 1 byte long
  3726. static_assert(
  3727. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  3728. "each element in the iterator range must have the size of 1 byte");
  3729. const auto len = static_cast<size_t>(std::distance(first, last));
  3730. if (JSON_HEDLEY_LIKELY(len > 0))
  3731. {
  3732. // there is at least one element: use the address of first
  3733. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  3734. }
  3735. else
  3736. {
  3737. // the address of first cannot be used: use nullptr
  3738. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  3739. }
  3740. }
  3741. /// input adapter for array
  3742. template<class T, std::size_t N>
  3743. input_adapter(T (&array)[N])
  3744. : input_adapter(std::begin(array), std::end(array)) {}
  3745. /// input adapter for contiguous container
  3746. template<class ContiguousContainer, typename
  3747. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  3748. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  3749. int>::type = 0>
  3750. input_adapter(const ContiguousContainer& c)
  3751. : input_adapter(std::begin(c), std::end(c)) {}
  3752. operator input_adapter_t()
  3753. {
  3754. return ia;
  3755. }
  3756. private:
  3757. /// the actual adapter
  3758. input_adapter_t ia = nullptr;
  3759. };
  3760. } // namespace detail
  3761. } // namespace nlohmann
  3762. // #include <nlohmann/detail/input/json_sax.hpp>
  3763. #include <cassert> // assert
  3764. #include <cstddef>
  3765. #include <string> // string
  3766. #include <utility> // move
  3767. #include <vector> // vector
  3768. // #include <nlohmann/detail/exceptions.hpp>
  3769. // #include <nlohmann/detail/macro_scope.hpp>
  3770. namespace nlohmann
  3771. {
  3772. /*!
  3773. @brief SAX interface
  3774. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  3775. Each function is called in different situations while the input is parsed. The
  3776. boolean return value informs the parser whether to continue processing the
  3777. input.
  3778. */
  3779. template<typename BasicJsonType>
  3780. struct json_sax
  3781. {
  3782. /// type for (signed) integers
  3783. using number_integer_t = typename BasicJsonType::number_integer_t;
  3784. /// type for unsigned integers
  3785. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3786. /// type for floating-point numbers
  3787. using number_float_t = typename BasicJsonType::number_float_t;
  3788. /// type for strings
  3789. using string_t = typename BasicJsonType::string_t;
  3790. /*!
  3791. @brief a null value was read
  3792. @return whether parsing should proceed
  3793. */
  3794. virtual bool null() = 0;
  3795. /*!
  3796. @brief a boolean value was read
  3797. @param[in] val boolean value
  3798. @return whether parsing should proceed
  3799. */
  3800. virtual bool boolean(bool val) = 0;
  3801. /*!
  3802. @brief an integer number was read
  3803. @param[in] val integer value
  3804. @return whether parsing should proceed
  3805. */
  3806. virtual bool number_integer(number_integer_t val) = 0;
  3807. /*!
  3808. @brief an unsigned integer number was read
  3809. @param[in] val unsigned integer value
  3810. @return whether parsing should proceed
  3811. */
  3812. virtual bool number_unsigned(number_unsigned_t val) = 0;
  3813. /*!
  3814. @brief an floating-point number was read
  3815. @param[in] val floating-point value
  3816. @param[in] s raw token value
  3817. @return whether parsing should proceed
  3818. */
  3819. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  3820. /*!
  3821. @brief a string was read
  3822. @param[in] val string value
  3823. @return whether parsing should proceed
  3824. @note It is safe to move the passed string.
  3825. */
  3826. virtual bool string(string_t& val) = 0;
  3827. /*!
  3828. @brief the beginning of an object was read
  3829. @param[in] elements number of object elements or -1 if unknown
  3830. @return whether parsing should proceed
  3831. @note binary formats may report the number of elements
  3832. */
  3833. virtual bool start_object(std::size_t elements) = 0;
  3834. /*!
  3835. @brief an object key was read
  3836. @param[in] val object key
  3837. @return whether parsing should proceed
  3838. @note It is safe to move the passed string.
  3839. */
  3840. virtual bool key(string_t& val) = 0;
  3841. /*!
  3842. @brief the end of an object was read
  3843. @return whether parsing should proceed
  3844. */
  3845. virtual bool end_object() = 0;
  3846. /*!
  3847. @brief the beginning of an array was read
  3848. @param[in] elements number of array elements or -1 if unknown
  3849. @return whether parsing should proceed
  3850. @note binary formats may report the number of elements
  3851. */
  3852. virtual bool start_array(std::size_t elements) = 0;
  3853. /*!
  3854. @brief the end of an array was read
  3855. @return whether parsing should proceed
  3856. */
  3857. virtual bool end_array() = 0;
  3858. /*!
  3859. @brief a parse error occurred
  3860. @param[in] position the position in the input where the error occurs
  3861. @param[in] last_token the last read token
  3862. @param[in] ex an exception object describing the error
  3863. @return whether parsing should proceed (must return false)
  3864. */
  3865. virtual bool parse_error(std::size_t position,
  3866. const std::string& last_token,
  3867. const detail::exception& ex) = 0;
  3868. virtual ~json_sax() = default;
  3869. };
  3870. namespace detail
  3871. {
  3872. /*!
  3873. @brief SAX implementation to create a JSON value from SAX events
  3874. This class implements the @ref json_sax interface and processes the SAX events
  3875. to create a JSON value which makes it basically a DOM parser. The structure or
  3876. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  3877. a pointer to the respective array or object for each recursion depth.
  3878. After successful parsing, the value that is passed by reference to the
  3879. constructor contains the parsed value.
  3880. @tparam BasicJsonType the JSON type
  3881. */
  3882. template<typename BasicJsonType>
  3883. class json_sax_dom_parser
  3884. {
  3885. public:
  3886. using number_integer_t = typename BasicJsonType::number_integer_t;
  3887. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3888. using number_float_t = typename BasicJsonType::number_float_t;
  3889. using string_t = typename BasicJsonType::string_t;
  3890. /*!
  3891. @param[in, out] r reference to a JSON value that is manipulated while
  3892. parsing
  3893. @param[in] allow_exceptions_ whether parse errors yield exceptions
  3894. */
  3895. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  3896. : root(r), allow_exceptions(allow_exceptions_)
  3897. {}
  3898. // make class move-only
  3899. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  3900. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  3901. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  3902. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  3903. ~json_sax_dom_parser() = default;
  3904. bool null()
  3905. {
  3906. handle_value(nullptr);
  3907. return true;
  3908. }
  3909. bool boolean(bool val)
  3910. {
  3911. handle_value(val);
  3912. return true;
  3913. }
  3914. bool number_integer(number_integer_t val)
  3915. {
  3916. handle_value(val);
  3917. return true;
  3918. }
  3919. bool number_unsigned(number_unsigned_t val)
  3920. {
  3921. handle_value(val);
  3922. return true;
  3923. }
  3924. bool number_float(number_float_t val, const string_t& /*unused*/)
  3925. {
  3926. handle_value(val);
  3927. return true;
  3928. }
  3929. bool string(string_t& val)
  3930. {
  3931. handle_value(val);
  3932. return true;
  3933. }
  3934. bool start_object(std::size_t len)
  3935. {
  3936. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  3937. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3938. {
  3939. JSON_THROW(out_of_range::create(408,
  3940. "excessive object size: " + std::to_string(len)));
  3941. }
  3942. return true;
  3943. }
  3944. bool key(string_t& val)
  3945. {
  3946. // add null at given key and store the reference for later
  3947. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  3948. return true;
  3949. }
  3950. bool end_object()
  3951. {
  3952. ref_stack.pop_back();
  3953. return true;
  3954. }
  3955. bool start_array(std::size_t len)
  3956. {
  3957. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  3958. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3959. {
  3960. JSON_THROW(out_of_range::create(408,
  3961. "excessive array size: " + std::to_string(len)));
  3962. }
  3963. return true;
  3964. }
  3965. bool end_array()
  3966. {
  3967. ref_stack.pop_back();
  3968. return true;
  3969. }
  3970. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  3971. const detail::exception& ex)
  3972. {
  3973. errored = true;
  3974. if (allow_exceptions)
  3975. {
  3976. // determine the proper exception type from the id
  3977. switch ((ex.id / 100) % 100)
  3978. {
  3979. case 1:
  3980. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  3981. case 4:
  3982. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  3983. // LCOV_EXCL_START
  3984. case 2:
  3985. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  3986. case 3:
  3987. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  3988. case 5:
  3989. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  3990. default:
  3991. assert(false);
  3992. // LCOV_EXCL_STOP
  3993. }
  3994. }
  3995. return false;
  3996. }
  3997. constexpr bool is_errored() const
  3998. {
  3999. return errored;
  4000. }
  4001. private:
  4002. /*!
  4003. @invariant If the ref stack is empty, then the passed value will be the new
  4004. root.
  4005. @invariant If the ref stack contains a value, then it is an array or an
  4006. object to which we can add elements
  4007. */
  4008. template<typename Value>
  4009. JSON_HEDLEY_RETURNS_NON_NULL
  4010. BasicJsonType* handle_value(Value&& v)
  4011. {
  4012. if (ref_stack.empty())
  4013. {
  4014. root = BasicJsonType(std::forward<Value>(v));
  4015. return &root;
  4016. }
  4017. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4018. if (ref_stack.back()->is_array())
  4019. {
  4020. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4021. return &(ref_stack.back()->m_value.array->back());
  4022. }
  4023. assert(ref_stack.back()->is_object());
  4024. assert(object_element);
  4025. *object_element = BasicJsonType(std::forward<Value>(v));
  4026. return object_element;
  4027. }
  4028. /// the parsed JSON value
  4029. BasicJsonType& root;
  4030. /// stack to model hierarchy of values
  4031. std::vector<BasicJsonType*> ref_stack {};
  4032. /// helper to hold the reference for the next object element
  4033. BasicJsonType* object_element = nullptr;
  4034. /// whether a syntax error occurred
  4035. bool errored = false;
  4036. /// whether to throw exceptions in case of errors
  4037. const bool allow_exceptions = true;
  4038. };
  4039. template<typename BasicJsonType>
  4040. class json_sax_dom_callback_parser
  4041. {
  4042. public:
  4043. using number_integer_t = typename BasicJsonType::number_integer_t;
  4044. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4045. using number_float_t = typename BasicJsonType::number_float_t;
  4046. using string_t = typename BasicJsonType::string_t;
  4047. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4048. using parse_event_t = typename BasicJsonType::parse_event_t;
  4049. json_sax_dom_callback_parser(BasicJsonType& r,
  4050. const parser_callback_t cb,
  4051. const bool allow_exceptions_ = true)
  4052. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4053. {
  4054. keep_stack.push_back(true);
  4055. }
  4056. // make class move-only
  4057. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4058. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4059. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4060. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4061. ~json_sax_dom_callback_parser() = default;
  4062. bool null()
  4063. {
  4064. handle_value(nullptr);
  4065. return true;
  4066. }
  4067. bool boolean(bool val)
  4068. {
  4069. handle_value(val);
  4070. return true;
  4071. }
  4072. bool number_integer(number_integer_t val)
  4073. {
  4074. handle_value(val);
  4075. return true;
  4076. }
  4077. bool number_unsigned(number_unsigned_t val)
  4078. {
  4079. handle_value(val);
  4080. return true;
  4081. }
  4082. bool number_float(number_float_t val, const string_t& /*unused*/)
  4083. {
  4084. handle_value(val);
  4085. return true;
  4086. }
  4087. bool string(string_t& val)
  4088. {
  4089. handle_value(val);
  4090. return true;
  4091. }
  4092. bool start_object(std::size_t len)
  4093. {
  4094. // check callback for object start
  4095. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4096. keep_stack.push_back(keep);
  4097. auto val = handle_value(BasicJsonType::value_t::object, true);
  4098. ref_stack.push_back(val.second);
  4099. // check object limit
  4100. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4101. {
  4102. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4103. }
  4104. return true;
  4105. }
  4106. bool key(string_t& val)
  4107. {
  4108. BasicJsonType k = BasicJsonType(val);
  4109. // check callback for key
  4110. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4111. key_keep_stack.push_back(keep);
  4112. // add discarded value at given key and store the reference for later
  4113. if (keep and ref_stack.back())
  4114. {
  4115. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4116. }
  4117. return true;
  4118. }
  4119. bool end_object()
  4120. {
  4121. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4122. {
  4123. // discard object
  4124. *ref_stack.back() = discarded;
  4125. }
  4126. assert(not ref_stack.empty());
  4127. assert(not keep_stack.empty());
  4128. ref_stack.pop_back();
  4129. keep_stack.pop_back();
  4130. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  4131. {
  4132. // remove discarded value
  4133. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4134. {
  4135. if (it->is_discarded())
  4136. {
  4137. ref_stack.back()->erase(it);
  4138. break;
  4139. }
  4140. }
  4141. }
  4142. return true;
  4143. }
  4144. bool start_array(std::size_t len)
  4145. {
  4146. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4147. keep_stack.push_back(keep);
  4148. auto val = handle_value(BasicJsonType::value_t::array, true);
  4149. ref_stack.push_back(val.second);
  4150. // check array limit
  4151. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4152. {
  4153. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4154. }
  4155. return true;
  4156. }
  4157. bool end_array()
  4158. {
  4159. bool keep = true;
  4160. if (ref_stack.back())
  4161. {
  4162. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4163. if (not keep)
  4164. {
  4165. // discard array
  4166. *ref_stack.back() = discarded;
  4167. }
  4168. }
  4169. assert(not ref_stack.empty());
  4170. assert(not keep_stack.empty());
  4171. ref_stack.pop_back();
  4172. keep_stack.pop_back();
  4173. // remove discarded value
  4174. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4175. {
  4176. ref_stack.back()->m_value.array->pop_back();
  4177. }
  4178. return true;
  4179. }
  4180. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4181. const detail::exception& ex)
  4182. {
  4183. errored = true;
  4184. if (allow_exceptions)
  4185. {
  4186. // determine the proper exception type from the id
  4187. switch ((ex.id / 100) % 100)
  4188. {
  4189. case 1:
  4190. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4191. case 4:
  4192. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4193. // LCOV_EXCL_START
  4194. case 2:
  4195. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4196. case 3:
  4197. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4198. case 5:
  4199. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4200. default:
  4201. assert(false);
  4202. // LCOV_EXCL_STOP
  4203. }
  4204. }
  4205. return false;
  4206. }
  4207. constexpr bool is_errored() const
  4208. {
  4209. return errored;
  4210. }
  4211. private:
  4212. /*!
  4213. @param[in] v value to add to the JSON value we build during parsing
  4214. @param[in] skip_callback whether we should skip calling the callback
  4215. function; this is required after start_array() and
  4216. start_object() SAX events, because otherwise we would call the
  4217. callback function with an empty array or object, respectively.
  4218. @invariant If the ref stack is empty, then the passed value will be the new
  4219. root.
  4220. @invariant If the ref stack contains a value, then it is an array or an
  4221. object to which we can add elements
  4222. @return pair of boolean (whether value should be kept) and pointer (to the
  4223. passed value in the ref_stack hierarchy; nullptr if not kept)
  4224. */
  4225. template<typename Value>
  4226. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4227. {
  4228. assert(not keep_stack.empty());
  4229. // do not handle this value if we know it would be added to a discarded
  4230. // container
  4231. if (not keep_stack.back())
  4232. {
  4233. return {false, nullptr};
  4234. }
  4235. // create value
  4236. auto value = BasicJsonType(std::forward<Value>(v));
  4237. // check callback
  4238. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4239. // do not handle this value if we just learnt it shall be discarded
  4240. if (not keep)
  4241. {
  4242. return {false, nullptr};
  4243. }
  4244. if (ref_stack.empty())
  4245. {
  4246. root = std::move(value);
  4247. return {true, &root};
  4248. }
  4249. // skip this value if we already decided to skip the parent
  4250. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4251. if (not ref_stack.back())
  4252. {
  4253. return {false, nullptr};
  4254. }
  4255. // we now only expect arrays and objects
  4256. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4257. // array
  4258. if (ref_stack.back()->is_array())
  4259. {
  4260. ref_stack.back()->m_value.array->push_back(std::move(value));
  4261. return {true, &(ref_stack.back()->m_value.array->back())};
  4262. }
  4263. // object
  4264. assert(ref_stack.back()->is_object());
  4265. // check if we should store an element for the current key
  4266. assert(not key_keep_stack.empty());
  4267. const bool store_element = key_keep_stack.back();
  4268. key_keep_stack.pop_back();
  4269. if (not store_element)
  4270. {
  4271. return {false, nullptr};
  4272. }
  4273. assert(object_element);
  4274. *object_element = std::move(value);
  4275. return {true, object_element};
  4276. }
  4277. /// the parsed JSON value
  4278. BasicJsonType& root;
  4279. /// stack to model hierarchy of values
  4280. std::vector<BasicJsonType*> ref_stack {};
  4281. /// stack to manage which values to keep
  4282. std::vector<bool> keep_stack {};
  4283. /// stack to manage which object keys to keep
  4284. std::vector<bool> key_keep_stack {};
  4285. /// helper to hold the reference for the next object element
  4286. BasicJsonType* object_element = nullptr;
  4287. /// whether a syntax error occurred
  4288. bool errored = false;
  4289. /// callback function
  4290. const parser_callback_t callback = nullptr;
  4291. /// whether to throw exceptions in case of errors
  4292. const bool allow_exceptions = true;
  4293. /// a discarded value for the callback
  4294. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4295. };
  4296. template<typename BasicJsonType>
  4297. class json_sax_acceptor
  4298. {
  4299. public:
  4300. using number_integer_t = typename BasicJsonType::number_integer_t;
  4301. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4302. using number_float_t = typename BasicJsonType::number_float_t;
  4303. using string_t = typename BasicJsonType::string_t;
  4304. bool null()
  4305. {
  4306. return true;
  4307. }
  4308. bool boolean(bool /*unused*/)
  4309. {
  4310. return true;
  4311. }
  4312. bool number_integer(number_integer_t /*unused*/)
  4313. {
  4314. return true;
  4315. }
  4316. bool number_unsigned(number_unsigned_t /*unused*/)
  4317. {
  4318. return true;
  4319. }
  4320. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4321. {
  4322. return true;
  4323. }
  4324. bool string(string_t& /*unused*/)
  4325. {
  4326. return true;
  4327. }
  4328. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4329. {
  4330. return true;
  4331. }
  4332. bool key(string_t& /*unused*/)
  4333. {
  4334. return true;
  4335. }
  4336. bool end_object()
  4337. {
  4338. return true;
  4339. }
  4340. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4341. {
  4342. return true;
  4343. }
  4344. bool end_array()
  4345. {
  4346. return true;
  4347. }
  4348. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4349. {
  4350. return false;
  4351. }
  4352. };
  4353. } // namespace detail
  4354. } // namespace nlohmann
  4355. // #include <nlohmann/detail/macro_scope.hpp>
  4356. // #include <nlohmann/detail/meta/is_sax.hpp>
  4357. #include <cstdint> // size_t
  4358. #include <utility> // declval
  4359. #include <string> // string
  4360. // #include <nlohmann/detail/meta/detected.hpp>
  4361. // #include <nlohmann/detail/meta/type_traits.hpp>
  4362. namespace nlohmann
  4363. {
  4364. namespace detail
  4365. {
  4366. template <typename T>
  4367. using null_function_t = decltype(std::declval<T&>().null());
  4368. template <typename T>
  4369. using boolean_function_t =
  4370. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4371. template <typename T, typename Integer>
  4372. using number_integer_function_t =
  4373. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4374. template <typename T, typename Unsigned>
  4375. using number_unsigned_function_t =
  4376. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4377. template <typename T, typename Float, typename String>
  4378. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4379. std::declval<Float>(), std::declval<const String&>()));
  4380. template <typename T, typename String>
  4381. using string_function_t =
  4382. decltype(std::declval<T&>().string(std::declval<String&>()));
  4383. template <typename T>
  4384. using start_object_function_t =
  4385. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4386. template <typename T, typename String>
  4387. using key_function_t =
  4388. decltype(std::declval<T&>().key(std::declval<String&>()));
  4389. template <typename T>
  4390. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4391. template <typename T>
  4392. using start_array_function_t =
  4393. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4394. template <typename T>
  4395. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4396. template <typename T, typename Exception>
  4397. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4398. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4399. std::declval<const Exception&>()));
  4400. template <typename SAX, typename BasicJsonType>
  4401. struct is_sax
  4402. {
  4403. private:
  4404. static_assert(is_basic_json<BasicJsonType>::value,
  4405. "BasicJsonType must be of type basic_json<...>");
  4406. using number_integer_t = typename BasicJsonType::number_integer_t;
  4407. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4408. using number_float_t = typename BasicJsonType::number_float_t;
  4409. using string_t = typename BasicJsonType::string_t;
  4410. using exception_t = typename BasicJsonType::exception;
  4411. public:
  4412. static constexpr bool value =
  4413. is_detected_exact<bool, null_function_t, SAX>::value &&
  4414. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4415. is_detected_exact<bool, number_integer_function_t, SAX,
  4416. number_integer_t>::value &&
  4417. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4418. number_unsigned_t>::value &&
  4419. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4420. string_t>::value &&
  4421. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4422. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4423. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4424. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4425. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4426. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4427. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4428. };
  4429. template <typename SAX, typename BasicJsonType>
  4430. struct is_sax_static_asserts
  4431. {
  4432. private:
  4433. static_assert(is_basic_json<BasicJsonType>::value,
  4434. "BasicJsonType must be of type basic_json<...>");
  4435. using number_integer_t = typename BasicJsonType::number_integer_t;
  4436. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4437. using number_float_t = typename BasicJsonType::number_float_t;
  4438. using string_t = typename BasicJsonType::string_t;
  4439. using exception_t = typename BasicJsonType::exception;
  4440. public:
  4441. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4442. "Missing/invalid function: bool null()");
  4443. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4444. "Missing/invalid function: bool boolean(bool)");
  4445. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4446. "Missing/invalid function: bool boolean(bool)");
  4447. static_assert(
  4448. is_detected_exact<bool, number_integer_function_t, SAX,
  4449. number_integer_t>::value,
  4450. "Missing/invalid function: bool number_integer(number_integer_t)");
  4451. static_assert(
  4452. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4453. number_unsigned_t>::value,
  4454. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  4455. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  4456. number_float_t, string_t>::value,
  4457. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  4458. static_assert(
  4459. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  4460. "Missing/invalid function: bool string(string_t&)");
  4461. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  4462. "Missing/invalid function: bool start_object(std::size_t)");
  4463. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  4464. "Missing/invalid function: bool key(string_t&)");
  4465. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  4466. "Missing/invalid function: bool end_object()");
  4467. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  4468. "Missing/invalid function: bool start_array(std::size_t)");
  4469. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  4470. "Missing/invalid function: bool end_array()");
  4471. static_assert(
  4472. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  4473. "Missing/invalid function: bool parse_error(std::size_t, const "
  4474. "std::string&, const exception&)");
  4475. };
  4476. } // namespace detail
  4477. } // namespace nlohmann
  4478. // #include <nlohmann/detail/value_t.hpp>
  4479. namespace nlohmann
  4480. {
  4481. namespace detail
  4482. {
  4483. ///////////////////
  4484. // binary reader //
  4485. ///////////////////
  4486. /*!
  4487. @brief deserialization of CBOR, MessagePack, and UBJSON values
  4488. */
  4489. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  4490. class binary_reader
  4491. {
  4492. using number_integer_t = typename BasicJsonType::number_integer_t;
  4493. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4494. using number_float_t = typename BasicJsonType::number_float_t;
  4495. using string_t = typename BasicJsonType::string_t;
  4496. using json_sax_t = SAX;
  4497. public:
  4498. /*!
  4499. @brief create a binary reader
  4500. @param[in] adapter input adapter to read from
  4501. */
  4502. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  4503. {
  4504. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4505. assert(ia);
  4506. }
  4507. // make class move-only
  4508. binary_reader(const binary_reader&) = delete;
  4509. binary_reader(binary_reader&&) = default;
  4510. binary_reader& operator=(const binary_reader&) = delete;
  4511. binary_reader& operator=(binary_reader&&) = default;
  4512. ~binary_reader() = default;
  4513. /*!
  4514. @param[in] format the binary format to parse
  4515. @param[in] sax_ a SAX event processor
  4516. @param[in] strict whether to expect the input to be consumed completed
  4517. @return
  4518. */
  4519. JSON_HEDLEY_NON_NULL(3)
  4520. bool sax_parse(const input_format_t format,
  4521. json_sax_t* sax_,
  4522. const bool strict = true)
  4523. {
  4524. sax = sax_;
  4525. bool result = false;
  4526. switch (format)
  4527. {
  4528. case input_format_t::bson:
  4529. result = parse_bson_internal();
  4530. break;
  4531. case input_format_t::cbor:
  4532. result = parse_cbor_internal();
  4533. break;
  4534. case input_format_t::msgpack:
  4535. result = parse_msgpack_internal();
  4536. break;
  4537. case input_format_t::ubjson:
  4538. result = parse_ubjson_internal();
  4539. break;
  4540. default: // LCOV_EXCL_LINE
  4541. assert(false); // LCOV_EXCL_LINE
  4542. }
  4543. // strict mode: next byte must be EOF
  4544. if (result and strict)
  4545. {
  4546. if (format == input_format_t::ubjson)
  4547. {
  4548. get_ignore_noop();
  4549. }
  4550. else
  4551. {
  4552. get();
  4553. }
  4554. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  4555. {
  4556. return sax->parse_error(chars_read, get_token_string(),
  4557. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  4558. }
  4559. }
  4560. return result;
  4561. }
  4562. /*!
  4563. @brief determine system byte order
  4564. @return true if and only if system's byte order is little endian
  4565. @note from http://stackoverflow.com/a/1001328/266378
  4566. */
  4567. static constexpr bool little_endianess(int num = 1) noexcept
  4568. {
  4569. return *reinterpret_cast<char*>(&num) == 1;
  4570. }
  4571. private:
  4572. //////////
  4573. // BSON //
  4574. //////////
  4575. /*!
  4576. @brief Reads in a BSON-object and passes it to the SAX-parser.
  4577. @return whether a valid BSON-value was passed to the SAX parser
  4578. */
  4579. bool parse_bson_internal()
  4580. {
  4581. std::int32_t document_size;
  4582. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4583. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4584. {
  4585. return false;
  4586. }
  4587. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  4588. {
  4589. return false;
  4590. }
  4591. return sax->end_object();
  4592. }
  4593. /*!
  4594. @brief Parses a C-style string from the BSON input.
  4595. @param[in, out] result A reference to the string variable where the read
  4596. string is to be stored.
  4597. @return `true` if the \x00-byte indicating the end of the string was
  4598. encountered before the EOF; false` indicates an unexpected EOF.
  4599. */
  4600. bool get_bson_cstr(string_t& result)
  4601. {
  4602. auto out = std::back_inserter(result);
  4603. while (true)
  4604. {
  4605. get();
  4606. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  4607. {
  4608. return false;
  4609. }
  4610. if (current == 0x00)
  4611. {
  4612. return true;
  4613. }
  4614. *out++ = static_cast<char>(current);
  4615. }
  4616. return true;
  4617. }
  4618. /*!
  4619. @brief Parses a zero-terminated string of length @a len from the BSON
  4620. input.
  4621. @param[in] len The length (including the zero-byte at the end) of the
  4622. string to be read.
  4623. @param[in, out] result A reference to the string variable where the read
  4624. string is to be stored.
  4625. @tparam NumberType The type of the length @a len
  4626. @pre len >= 1
  4627. @return `true` if the string was successfully parsed
  4628. */
  4629. template<typename NumberType>
  4630. bool get_bson_string(const NumberType len, string_t& result)
  4631. {
  4632. if (JSON_HEDLEY_UNLIKELY(len < 1))
  4633. {
  4634. auto last_token = get_token_string();
  4635. 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")));
  4636. }
  4637. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  4638. }
  4639. /*!
  4640. @brief Read a BSON document element of the given @a element_type.
  4641. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  4642. @param[in] element_type_parse_position The position in the input stream,
  4643. where the `element_type` was read.
  4644. @warning Not all BSON element types are supported yet. An unsupported
  4645. @a element_type will give rise to a parse_error.114:
  4646. Unsupported BSON record type 0x...
  4647. @return whether a valid BSON-object/array was passed to the SAX parser
  4648. */
  4649. bool parse_bson_element_internal(const int element_type,
  4650. const std::size_t element_type_parse_position)
  4651. {
  4652. switch (element_type)
  4653. {
  4654. case 0x01: // double
  4655. {
  4656. double number;
  4657. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4658. }
  4659. case 0x02: // string
  4660. {
  4661. std::int32_t len;
  4662. string_t value;
  4663. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  4664. }
  4665. case 0x03: // object
  4666. {
  4667. return parse_bson_internal();
  4668. }
  4669. case 0x04: // array
  4670. {
  4671. return parse_bson_array();
  4672. }
  4673. case 0x08: // boolean
  4674. {
  4675. return sax->boolean(get() != 0);
  4676. }
  4677. case 0x0A: // null
  4678. {
  4679. return sax->null();
  4680. }
  4681. case 0x10: // int32
  4682. {
  4683. std::int32_t value;
  4684. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4685. }
  4686. case 0x12: // int64
  4687. {
  4688. std::int64_t value;
  4689. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4690. }
  4691. default: // anything else not supported (yet)
  4692. {
  4693. std::array<char, 3> cr{{}};
  4694. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  4695. 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())));
  4696. }
  4697. }
  4698. }
  4699. /*!
  4700. @brief Read a BSON element list (as specified in the BSON-spec)
  4701. The same binary layout is used for objects and arrays, hence it must be
  4702. indicated with the argument @a is_array which one is expected
  4703. (true --> array, false --> object).
  4704. @param[in] is_array Determines if the element list being read is to be
  4705. treated as an object (@a is_array == false), or as an
  4706. array (@a is_array == true).
  4707. @return whether a valid BSON-object/array was passed to the SAX parser
  4708. */
  4709. bool parse_bson_element_list(const bool is_array)
  4710. {
  4711. string_t key;
  4712. while (int element_type = get())
  4713. {
  4714. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  4715. {
  4716. return false;
  4717. }
  4718. const std::size_t element_type_parse_position = chars_read;
  4719. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  4720. {
  4721. return false;
  4722. }
  4723. if (not is_array and not sax->key(key))
  4724. {
  4725. return false;
  4726. }
  4727. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  4728. {
  4729. return false;
  4730. }
  4731. // get_bson_cstr only appends
  4732. key.clear();
  4733. }
  4734. return true;
  4735. }
  4736. /*!
  4737. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  4738. @return whether a valid BSON-array was passed to the SAX parser
  4739. */
  4740. bool parse_bson_array()
  4741. {
  4742. std::int32_t document_size;
  4743. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4744. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4745. {
  4746. return false;
  4747. }
  4748. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  4749. {
  4750. return false;
  4751. }
  4752. return sax->end_array();
  4753. }
  4754. //////////
  4755. // CBOR //
  4756. //////////
  4757. /*!
  4758. @param[in] get_char whether a new character should be retrieved from the
  4759. input (true, default) or whether the last read
  4760. character should be considered instead
  4761. @return whether a valid CBOR value was passed to the SAX parser
  4762. */
  4763. bool parse_cbor_internal(const bool get_char = true)
  4764. {
  4765. switch (get_char ? get() : current)
  4766. {
  4767. // EOF
  4768. case std::char_traits<char>::eof():
  4769. return unexpect_eof(input_format_t::cbor, "value");
  4770. // Integer 0x00..0x17 (0..23)
  4771. case 0x00:
  4772. case 0x01:
  4773. case 0x02:
  4774. case 0x03:
  4775. case 0x04:
  4776. case 0x05:
  4777. case 0x06:
  4778. case 0x07:
  4779. case 0x08:
  4780. case 0x09:
  4781. case 0x0A:
  4782. case 0x0B:
  4783. case 0x0C:
  4784. case 0x0D:
  4785. case 0x0E:
  4786. case 0x0F:
  4787. case 0x10:
  4788. case 0x11:
  4789. case 0x12:
  4790. case 0x13:
  4791. case 0x14:
  4792. case 0x15:
  4793. case 0x16:
  4794. case 0x17:
  4795. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  4796. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  4797. {
  4798. std::uint8_t number;
  4799. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4800. }
  4801. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  4802. {
  4803. std::uint16_t number;
  4804. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4805. }
  4806. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  4807. {
  4808. std::uint32_t number;
  4809. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4810. }
  4811. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  4812. {
  4813. std::uint64_t number;
  4814. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4815. }
  4816. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  4817. case 0x20:
  4818. case 0x21:
  4819. case 0x22:
  4820. case 0x23:
  4821. case 0x24:
  4822. case 0x25:
  4823. case 0x26:
  4824. case 0x27:
  4825. case 0x28:
  4826. case 0x29:
  4827. case 0x2A:
  4828. case 0x2B:
  4829. case 0x2C:
  4830. case 0x2D:
  4831. case 0x2E:
  4832. case 0x2F:
  4833. case 0x30:
  4834. case 0x31:
  4835. case 0x32:
  4836. case 0x33:
  4837. case 0x34:
  4838. case 0x35:
  4839. case 0x36:
  4840. case 0x37:
  4841. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  4842. case 0x38: // Negative integer (one-byte uint8_t follows)
  4843. {
  4844. std::uint8_t number;
  4845. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4846. }
  4847. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4848. {
  4849. std::uint16_t number;
  4850. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4851. }
  4852. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  4853. {
  4854. std::uint32_t number;
  4855. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4856. }
  4857. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  4858. {
  4859. std::uint64_t number;
  4860. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  4861. - static_cast<number_integer_t>(number));
  4862. }
  4863. // UTF-8 string (0x00..0x17 bytes follow)
  4864. case 0x60:
  4865. case 0x61:
  4866. case 0x62:
  4867. case 0x63:
  4868. case 0x64:
  4869. case 0x65:
  4870. case 0x66:
  4871. case 0x67:
  4872. case 0x68:
  4873. case 0x69:
  4874. case 0x6A:
  4875. case 0x6B:
  4876. case 0x6C:
  4877. case 0x6D:
  4878. case 0x6E:
  4879. case 0x6F:
  4880. case 0x70:
  4881. case 0x71:
  4882. case 0x72:
  4883. case 0x73:
  4884. case 0x74:
  4885. case 0x75:
  4886. case 0x76:
  4887. case 0x77:
  4888. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4889. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4890. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4891. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4892. case 0x7F: // UTF-8 string (indefinite length)
  4893. {
  4894. string_t s;
  4895. return get_cbor_string(s) and sax->string(s);
  4896. }
  4897. // array (0x00..0x17 data items follow)
  4898. case 0x80:
  4899. case 0x81:
  4900. case 0x82:
  4901. case 0x83:
  4902. case 0x84:
  4903. case 0x85:
  4904. case 0x86:
  4905. case 0x87:
  4906. case 0x88:
  4907. case 0x89:
  4908. case 0x8A:
  4909. case 0x8B:
  4910. case 0x8C:
  4911. case 0x8D:
  4912. case 0x8E:
  4913. case 0x8F:
  4914. case 0x90:
  4915. case 0x91:
  4916. case 0x92:
  4917. case 0x93:
  4918. case 0x94:
  4919. case 0x95:
  4920. case 0x96:
  4921. case 0x97:
  4922. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4923. case 0x98: // array (one-byte uint8_t for n follows)
  4924. {
  4925. std::uint8_t len;
  4926. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4927. }
  4928. case 0x99: // array (two-byte uint16_t for n follow)
  4929. {
  4930. std::uint16_t len;
  4931. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4932. }
  4933. case 0x9A: // array (four-byte uint32_t for n follow)
  4934. {
  4935. std::uint32_t len;
  4936. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4937. }
  4938. case 0x9B: // array (eight-byte uint64_t for n follow)
  4939. {
  4940. std::uint64_t len;
  4941. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4942. }
  4943. case 0x9F: // array (indefinite length)
  4944. return get_cbor_array(std::size_t(-1));
  4945. // map (0x00..0x17 pairs of data items follow)
  4946. case 0xA0:
  4947. case 0xA1:
  4948. case 0xA2:
  4949. case 0xA3:
  4950. case 0xA4:
  4951. case 0xA5:
  4952. case 0xA6:
  4953. case 0xA7:
  4954. case 0xA8:
  4955. case 0xA9:
  4956. case 0xAA:
  4957. case 0xAB:
  4958. case 0xAC:
  4959. case 0xAD:
  4960. case 0xAE:
  4961. case 0xAF:
  4962. case 0xB0:
  4963. case 0xB1:
  4964. case 0xB2:
  4965. case 0xB3:
  4966. case 0xB4:
  4967. case 0xB5:
  4968. case 0xB6:
  4969. case 0xB7:
  4970. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4971. case 0xB8: // map (one-byte uint8_t for n follows)
  4972. {
  4973. std::uint8_t len;
  4974. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4975. }
  4976. case 0xB9: // map (two-byte uint16_t for n follow)
  4977. {
  4978. std::uint16_t len;
  4979. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4980. }
  4981. case 0xBA: // map (four-byte uint32_t for n follow)
  4982. {
  4983. std::uint32_t len;
  4984. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4985. }
  4986. case 0xBB: // map (eight-byte uint64_t for n follow)
  4987. {
  4988. std::uint64_t len;
  4989. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4990. }
  4991. case 0xBF: // map (indefinite length)
  4992. return get_cbor_object(std::size_t(-1));
  4993. case 0xF4: // false
  4994. return sax->boolean(false);
  4995. case 0xF5: // true
  4996. return sax->boolean(true);
  4997. case 0xF6: // null
  4998. return sax->null();
  4999. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5000. {
  5001. const int byte1_raw = get();
  5002. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5003. {
  5004. return false;
  5005. }
  5006. const int byte2_raw = get();
  5007. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5008. {
  5009. return false;
  5010. }
  5011. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  5012. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  5013. // code from RFC 7049, Appendix D, Figure 3:
  5014. // As half-precision floating-point numbers were only added
  5015. // to IEEE 754 in 2008, today's programming platforms often
  5016. // still only have limited support for them. It is very
  5017. // easy to include at least decoding support for them even
  5018. // without such support. An example of a small decoder for
  5019. // half-precision floating-point numbers in the C language
  5020. // is shown in Fig. 3.
  5021. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  5022. const double val = [&half]
  5023. {
  5024. const int exp = (half >> 10u) & 0x1Fu;
  5025. const unsigned int mant = half & 0x3FFu;
  5026. assert(0 <= exp and exp <= 32);
  5027. assert(mant <= 1024);
  5028. switch (exp)
  5029. {
  5030. case 0:
  5031. return std::ldexp(mant, -24);
  5032. case 31:
  5033. return (mant == 0)
  5034. ? std::numeric_limits<double>::infinity()
  5035. : std::numeric_limits<double>::quiet_NaN();
  5036. default:
  5037. return std::ldexp(mant + 1024, exp - 25);
  5038. }
  5039. }();
  5040. return sax->number_float((half & 0x8000u) != 0
  5041. ? static_cast<number_float_t>(-val)
  5042. : static_cast<number_float_t>(val), "");
  5043. }
  5044. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5045. {
  5046. float number;
  5047. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5048. }
  5049. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5050. {
  5051. double number;
  5052. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5053. }
  5054. default: // anything else (0xFF is handled inside the other types)
  5055. {
  5056. auto last_token = get_token_string();
  5057. 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")));
  5058. }
  5059. }
  5060. }
  5061. /*!
  5062. @brief reads a CBOR string
  5063. This function first reads starting bytes to determine the expected
  5064. string length and then copies this number of bytes into a string.
  5065. Additionally, CBOR's strings with indefinite lengths are supported.
  5066. @param[out] result created string
  5067. @return whether string creation completed
  5068. */
  5069. bool get_cbor_string(string_t& result)
  5070. {
  5071. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  5072. {
  5073. return false;
  5074. }
  5075. switch (current)
  5076. {
  5077. // UTF-8 string (0x00..0x17 bytes follow)
  5078. case 0x60:
  5079. case 0x61:
  5080. case 0x62:
  5081. case 0x63:
  5082. case 0x64:
  5083. case 0x65:
  5084. case 0x66:
  5085. case 0x67:
  5086. case 0x68:
  5087. case 0x69:
  5088. case 0x6A:
  5089. case 0x6B:
  5090. case 0x6C:
  5091. case 0x6D:
  5092. case 0x6E:
  5093. case 0x6F:
  5094. case 0x70:
  5095. case 0x71:
  5096. case 0x72:
  5097. case 0x73:
  5098. case 0x74:
  5099. case 0x75:
  5100. case 0x76:
  5101. case 0x77:
  5102. {
  5103. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5104. }
  5105. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5106. {
  5107. std::uint8_t len;
  5108. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5109. }
  5110. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5111. {
  5112. std::uint16_t len;
  5113. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5114. }
  5115. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5116. {
  5117. std::uint32_t len;
  5118. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5119. }
  5120. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5121. {
  5122. std::uint64_t len;
  5123. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5124. }
  5125. case 0x7F: // UTF-8 string (indefinite length)
  5126. {
  5127. while (get() != 0xFF)
  5128. {
  5129. string_t chunk;
  5130. if (not get_cbor_string(chunk))
  5131. {
  5132. return false;
  5133. }
  5134. result.append(chunk);
  5135. }
  5136. return true;
  5137. }
  5138. default:
  5139. {
  5140. auto last_token = get_token_string();
  5141. 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")));
  5142. }
  5143. }
  5144. }
  5145. /*!
  5146. @param[in] len the length of the array or std::size_t(-1) for an
  5147. array of indefinite size
  5148. @return whether array creation completed
  5149. */
  5150. bool get_cbor_array(const std::size_t len)
  5151. {
  5152. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5153. {
  5154. return false;
  5155. }
  5156. if (len != std::size_t(-1))
  5157. {
  5158. for (std::size_t i = 0; i < len; ++i)
  5159. {
  5160. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5161. {
  5162. return false;
  5163. }
  5164. }
  5165. }
  5166. else
  5167. {
  5168. while (get() != 0xFF)
  5169. {
  5170. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5171. {
  5172. return false;
  5173. }
  5174. }
  5175. }
  5176. return sax->end_array();
  5177. }
  5178. /*!
  5179. @param[in] len the length of the object or std::size_t(-1) for an
  5180. object of indefinite size
  5181. @return whether object creation completed
  5182. */
  5183. bool get_cbor_object(const std::size_t len)
  5184. {
  5185. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5186. {
  5187. return false;
  5188. }
  5189. string_t key;
  5190. if (len != std::size_t(-1))
  5191. {
  5192. for (std::size_t i = 0; i < len; ++i)
  5193. {
  5194. get();
  5195. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5196. {
  5197. return false;
  5198. }
  5199. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5200. {
  5201. return false;
  5202. }
  5203. key.clear();
  5204. }
  5205. }
  5206. else
  5207. {
  5208. while (get() != 0xFF)
  5209. {
  5210. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5211. {
  5212. return false;
  5213. }
  5214. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5215. {
  5216. return false;
  5217. }
  5218. key.clear();
  5219. }
  5220. }
  5221. return sax->end_object();
  5222. }
  5223. /////////////
  5224. // MsgPack //
  5225. /////////////
  5226. /*!
  5227. @return whether a valid MessagePack value was passed to the SAX parser
  5228. */
  5229. bool parse_msgpack_internal()
  5230. {
  5231. switch (get())
  5232. {
  5233. // EOF
  5234. case std::char_traits<char>::eof():
  5235. return unexpect_eof(input_format_t::msgpack, "value");
  5236. // positive fixint
  5237. case 0x00:
  5238. case 0x01:
  5239. case 0x02:
  5240. case 0x03:
  5241. case 0x04:
  5242. case 0x05:
  5243. case 0x06:
  5244. case 0x07:
  5245. case 0x08:
  5246. case 0x09:
  5247. case 0x0A:
  5248. case 0x0B:
  5249. case 0x0C:
  5250. case 0x0D:
  5251. case 0x0E:
  5252. case 0x0F:
  5253. case 0x10:
  5254. case 0x11:
  5255. case 0x12:
  5256. case 0x13:
  5257. case 0x14:
  5258. case 0x15:
  5259. case 0x16:
  5260. case 0x17:
  5261. case 0x18:
  5262. case 0x19:
  5263. case 0x1A:
  5264. case 0x1B:
  5265. case 0x1C:
  5266. case 0x1D:
  5267. case 0x1E:
  5268. case 0x1F:
  5269. case 0x20:
  5270. case 0x21:
  5271. case 0x22:
  5272. case 0x23:
  5273. case 0x24:
  5274. case 0x25:
  5275. case 0x26:
  5276. case 0x27:
  5277. case 0x28:
  5278. case 0x29:
  5279. case 0x2A:
  5280. case 0x2B:
  5281. case 0x2C:
  5282. case 0x2D:
  5283. case 0x2E:
  5284. case 0x2F:
  5285. case 0x30:
  5286. case 0x31:
  5287. case 0x32:
  5288. case 0x33:
  5289. case 0x34:
  5290. case 0x35:
  5291. case 0x36:
  5292. case 0x37:
  5293. case 0x38:
  5294. case 0x39:
  5295. case 0x3A:
  5296. case 0x3B:
  5297. case 0x3C:
  5298. case 0x3D:
  5299. case 0x3E:
  5300. case 0x3F:
  5301. case 0x40:
  5302. case 0x41:
  5303. case 0x42:
  5304. case 0x43:
  5305. case 0x44:
  5306. case 0x45:
  5307. case 0x46:
  5308. case 0x47:
  5309. case 0x48:
  5310. case 0x49:
  5311. case 0x4A:
  5312. case 0x4B:
  5313. case 0x4C:
  5314. case 0x4D:
  5315. case 0x4E:
  5316. case 0x4F:
  5317. case 0x50:
  5318. case 0x51:
  5319. case 0x52:
  5320. case 0x53:
  5321. case 0x54:
  5322. case 0x55:
  5323. case 0x56:
  5324. case 0x57:
  5325. case 0x58:
  5326. case 0x59:
  5327. case 0x5A:
  5328. case 0x5B:
  5329. case 0x5C:
  5330. case 0x5D:
  5331. case 0x5E:
  5332. case 0x5F:
  5333. case 0x60:
  5334. case 0x61:
  5335. case 0x62:
  5336. case 0x63:
  5337. case 0x64:
  5338. case 0x65:
  5339. case 0x66:
  5340. case 0x67:
  5341. case 0x68:
  5342. case 0x69:
  5343. case 0x6A:
  5344. case 0x6B:
  5345. case 0x6C:
  5346. case 0x6D:
  5347. case 0x6E:
  5348. case 0x6F:
  5349. case 0x70:
  5350. case 0x71:
  5351. case 0x72:
  5352. case 0x73:
  5353. case 0x74:
  5354. case 0x75:
  5355. case 0x76:
  5356. case 0x77:
  5357. case 0x78:
  5358. case 0x79:
  5359. case 0x7A:
  5360. case 0x7B:
  5361. case 0x7C:
  5362. case 0x7D:
  5363. case 0x7E:
  5364. case 0x7F:
  5365. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5366. // fixmap
  5367. case 0x80:
  5368. case 0x81:
  5369. case 0x82:
  5370. case 0x83:
  5371. case 0x84:
  5372. case 0x85:
  5373. case 0x86:
  5374. case 0x87:
  5375. case 0x88:
  5376. case 0x89:
  5377. case 0x8A:
  5378. case 0x8B:
  5379. case 0x8C:
  5380. case 0x8D:
  5381. case 0x8E:
  5382. case 0x8F:
  5383. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5384. // fixarray
  5385. case 0x90:
  5386. case 0x91:
  5387. case 0x92:
  5388. case 0x93:
  5389. case 0x94:
  5390. case 0x95:
  5391. case 0x96:
  5392. case 0x97:
  5393. case 0x98:
  5394. case 0x99:
  5395. case 0x9A:
  5396. case 0x9B:
  5397. case 0x9C:
  5398. case 0x9D:
  5399. case 0x9E:
  5400. case 0x9F:
  5401. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5402. // fixstr
  5403. case 0xA0:
  5404. case 0xA1:
  5405. case 0xA2:
  5406. case 0xA3:
  5407. case 0xA4:
  5408. case 0xA5:
  5409. case 0xA6:
  5410. case 0xA7:
  5411. case 0xA8:
  5412. case 0xA9:
  5413. case 0xAA:
  5414. case 0xAB:
  5415. case 0xAC:
  5416. case 0xAD:
  5417. case 0xAE:
  5418. case 0xAF:
  5419. case 0xB0:
  5420. case 0xB1:
  5421. case 0xB2:
  5422. case 0xB3:
  5423. case 0xB4:
  5424. case 0xB5:
  5425. case 0xB6:
  5426. case 0xB7:
  5427. case 0xB8:
  5428. case 0xB9:
  5429. case 0xBA:
  5430. case 0xBB:
  5431. case 0xBC:
  5432. case 0xBD:
  5433. case 0xBE:
  5434. case 0xBF:
  5435. case 0xD9: // str 8
  5436. case 0xDA: // str 16
  5437. case 0xDB: // str 32
  5438. {
  5439. string_t s;
  5440. return get_msgpack_string(s) and sax->string(s);
  5441. }
  5442. case 0xC0: // nil
  5443. return sax->null();
  5444. case 0xC2: // false
  5445. return sax->boolean(false);
  5446. case 0xC3: // true
  5447. return sax->boolean(true);
  5448. case 0xCA: // float 32
  5449. {
  5450. float number;
  5451. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5452. }
  5453. case 0xCB: // float 64
  5454. {
  5455. double number;
  5456. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5457. }
  5458. case 0xCC: // uint 8
  5459. {
  5460. std::uint8_t number;
  5461. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5462. }
  5463. case 0xCD: // uint 16
  5464. {
  5465. std::uint16_t number;
  5466. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5467. }
  5468. case 0xCE: // uint 32
  5469. {
  5470. std::uint32_t number;
  5471. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5472. }
  5473. case 0xCF: // uint 64
  5474. {
  5475. std::uint64_t number;
  5476. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5477. }
  5478. case 0xD0: // int 8
  5479. {
  5480. std::int8_t number;
  5481. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5482. }
  5483. case 0xD1: // int 16
  5484. {
  5485. std::int16_t number;
  5486. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5487. }
  5488. case 0xD2: // int 32
  5489. {
  5490. std::int32_t number;
  5491. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5492. }
  5493. case 0xD3: // int 64
  5494. {
  5495. std::int64_t number;
  5496. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5497. }
  5498. case 0xDC: // array 16
  5499. {
  5500. std::uint16_t len;
  5501. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5502. }
  5503. case 0xDD: // array 32
  5504. {
  5505. std::uint32_t len;
  5506. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5507. }
  5508. case 0xDE: // map 16
  5509. {
  5510. std::uint16_t len;
  5511. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5512. }
  5513. case 0xDF: // map 32
  5514. {
  5515. std::uint32_t len;
  5516. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5517. }
  5518. // negative fixint
  5519. case 0xE0:
  5520. case 0xE1:
  5521. case 0xE2:
  5522. case 0xE3:
  5523. case 0xE4:
  5524. case 0xE5:
  5525. case 0xE6:
  5526. case 0xE7:
  5527. case 0xE8:
  5528. case 0xE9:
  5529. case 0xEA:
  5530. case 0xEB:
  5531. case 0xEC:
  5532. case 0xED:
  5533. case 0xEE:
  5534. case 0xEF:
  5535. case 0xF0:
  5536. case 0xF1:
  5537. case 0xF2:
  5538. case 0xF3:
  5539. case 0xF4:
  5540. case 0xF5:
  5541. case 0xF6:
  5542. case 0xF7:
  5543. case 0xF8:
  5544. case 0xF9:
  5545. case 0xFA:
  5546. case 0xFB:
  5547. case 0xFC:
  5548. case 0xFD:
  5549. case 0xFE:
  5550. case 0xFF:
  5551. return sax->number_integer(static_cast<std::int8_t>(current));
  5552. default: // anything else
  5553. {
  5554. auto last_token = get_token_string();
  5555. 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")));
  5556. }
  5557. }
  5558. }
  5559. /*!
  5560. @brief reads a MessagePack string
  5561. This function first reads starting bytes to determine the expected
  5562. string length and then copies this number of bytes into a string.
  5563. @param[out] result created string
  5564. @return whether string creation completed
  5565. */
  5566. bool get_msgpack_string(string_t& result)
  5567. {
  5568. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  5569. {
  5570. return false;
  5571. }
  5572. switch (current)
  5573. {
  5574. // fixstr
  5575. case 0xA0:
  5576. case 0xA1:
  5577. case 0xA2:
  5578. case 0xA3:
  5579. case 0xA4:
  5580. case 0xA5:
  5581. case 0xA6:
  5582. case 0xA7:
  5583. case 0xA8:
  5584. case 0xA9:
  5585. case 0xAA:
  5586. case 0xAB:
  5587. case 0xAC:
  5588. case 0xAD:
  5589. case 0xAE:
  5590. case 0xAF:
  5591. case 0xB0:
  5592. case 0xB1:
  5593. case 0xB2:
  5594. case 0xB3:
  5595. case 0xB4:
  5596. case 0xB5:
  5597. case 0xB6:
  5598. case 0xB7:
  5599. case 0xB8:
  5600. case 0xB9:
  5601. case 0xBA:
  5602. case 0xBB:
  5603. case 0xBC:
  5604. case 0xBD:
  5605. case 0xBE:
  5606. case 0xBF:
  5607. {
  5608. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  5609. }
  5610. case 0xD9: // str 8
  5611. {
  5612. std::uint8_t len;
  5613. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5614. }
  5615. case 0xDA: // str 16
  5616. {
  5617. std::uint16_t len;
  5618. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5619. }
  5620. case 0xDB: // str 32
  5621. {
  5622. std::uint32_t len;
  5623. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5624. }
  5625. default:
  5626. {
  5627. auto last_token = get_token_string();
  5628. 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")));
  5629. }
  5630. }
  5631. }
  5632. /*!
  5633. @param[in] len the length of the array
  5634. @return whether array creation completed
  5635. */
  5636. bool get_msgpack_array(const std::size_t len)
  5637. {
  5638. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5639. {
  5640. return false;
  5641. }
  5642. for (std::size_t i = 0; i < len; ++i)
  5643. {
  5644. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5645. {
  5646. return false;
  5647. }
  5648. }
  5649. return sax->end_array();
  5650. }
  5651. /*!
  5652. @param[in] len the length of the object
  5653. @return whether object creation completed
  5654. */
  5655. bool get_msgpack_object(const std::size_t len)
  5656. {
  5657. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5658. {
  5659. return false;
  5660. }
  5661. string_t key;
  5662. for (std::size_t i = 0; i < len; ++i)
  5663. {
  5664. get();
  5665. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  5666. {
  5667. return false;
  5668. }
  5669. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5670. {
  5671. return false;
  5672. }
  5673. key.clear();
  5674. }
  5675. return sax->end_object();
  5676. }
  5677. ////////////
  5678. // UBJSON //
  5679. ////////////
  5680. /*!
  5681. @param[in] get_char whether a new character should be retrieved from the
  5682. input (true, default) or whether the last read
  5683. character should be considered instead
  5684. @return whether a valid UBJSON value was passed to the SAX parser
  5685. */
  5686. bool parse_ubjson_internal(const bool get_char = true)
  5687. {
  5688. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  5689. }
  5690. /*!
  5691. @brief reads a UBJSON string
  5692. This function is either called after reading the 'S' byte explicitly
  5693. indicating a string, or in case of an object key where the 'S' byte can be
  5694. left out.
  5695. @param[out] result created string
  5696. @param[in] get_char whether a new character should be retrieved from the
  5697. input (true, default) or whether the last read
  5698. character should be considered instead
  5699. @return whether string creation completed
  5700. */
  5701. bool get_ubjson_string(string_t& result, const bool get_char = true)
  5702. {
  5703. if (get_char)
  5704. {
  5705. get(); // TODO(niels): may we ignore N here?
  5706. }
  5707. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5708. {
  5709. return false;
  5710. }
  5711. switch (current)
  5712. {
  5713. case 'U':
  5714. {
  5715. std::uint8_t len;
  5716. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5717. }
  5718. case 'i':
  5719. {
  5720. std::int8_t len;
  5721. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5722. }
  5723. case 'I':
  5724. {
  5725. std::int16_t len;
  5726. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5727. }
  5728. case 'l':
  5729. {
  5730. std::int32_t len;
  5731. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5732. }
  5733. case 'L':
  5734. {
  5735. std::int64_t len;
  5736. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5737. }
  5738. default:
  5739. auto last_token = get_token_string();
  5740. 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")));
  5741. }
  5742. }
  5743. /*!
  5744. @param[out] result determined size
  5745. @return whether size determination completed
  5746. */
  5747. bool get_ubjson_size_value(std::size_t& result)
  5748. {
  5749. switch (get_ignore_noop())
  5750. {
  5751. case 'U':
  5752. {
  5753. std::uint8_t number;
  5754. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5755. {
  5756. return false;
  5757. }
  5758. result = static_cast<std::size_t>(number);
  5759. return true;
  5760. }
  5761. case 'i':
  5762. {
  5763. std::int8_t number;
  5764. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5765. {
  5766. return false;
  5767. }
  5768. result = static_cast<std::size_t>(number);
  5769. return true;
  5770. }
  5771. case 'I':
  5772. {
  5773. std::int16_t number;
  5774. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5775. {
  5776. return false;
  5777. }
  5778. result = static_cast<std::size_t>(number);
  5779. return true;
  5780. }
  5781. case 'l':
  5782. {
  5783. std::int32_t number;
  5784. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5785. {
  5786. return false;
  5787. }
  5788. result = static_cast<std::size_t>(number);
  5789. return true;
  5790. }
  5791. case 'L':
  5792. {
  5793. std::int64_t number;
  5794. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5795. {
  5796. return false;
  5797. }
  5798. result = static_cast<std::size_t>(number);
  5799. return true;
  5800. }
  5801. default:
  5802. {
  5803. auto last_token = get_token_string();
  5804. 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")));
  5805. }
  5806. }
  5807. }
  5808. /*!
  5809. @brief determine the type and size for a container
  5810. In the optimized UBJSON format, a type and a size can be provided to allow
  5811. for a more compact representation.
  5812. @param[out] result pair of the size and the type
  5813. @return whether pair creation completed
  5814. */
  5815. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  5816. {
  5817. result.first = string_t::npos; // size
  5818. result.second = 0; // type
  5819. get_ignore_noop();
  5820. if (current == '$')
  5821. {
  5822. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  5823. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  5824. {
  5825. return false;
  5826. }
  5827. get_ignore_noop();
  5828. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  5829. {
  5830. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5831. {
  5832. return false;
  5833. }
  5834. auto last_token = get_token_string();
  5835. 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")));
  5836. }
  5837. return get_ubjson_size_value(result.first);
  5838. }
  5839. if (current == '#')
  5840. {
  5841. return get_ubjson_size_value(result.first);
  5842. }
  5843. return true;
  5844. }
  5845. /*!
  5846. @param prefix the previously read or set type prefix
  5847. @return whether value creation completed
  5848. */
  5849. bool get_ubjson_value(const int prefix)
  5850. {
  5851. switch (prefix)
  5852. {
  5853. case std::char_traits<char>::eof(): // EOF
  5854. return unexpect_eof(input_format_t::ubjson, "value");
  5855. case 'T': // true
  5856. return sax->boolean(true);
  5857. case 'F': // false
  5858. return sax->boolean(false);
  5859. case 'Z': // null
  5860. return sax->null();
  5861. case 'U':
  5862. {
  5863. std::uint8_t number;
  5864. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  5865. }
  5866. case 'i':
  5867. {
  5868. std::int8_t number;
  5869. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5870. }
  5871. case 'I':
  5872. {
  5873. std::int16_t number;
  5874. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5875. }
  5876. case 'l':
  5877. {
  5878. std::int32_t number;
  5879. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5880. }
  5881. case 'L':
  5882. {
  5883. std::int64_t number;
  5884. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5885. }
  5886. case 'd':
  5887. {
  5888. float number;
  5889. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5890. }
  5891. case 'D':
  5892. {
  5893. double number;
  5894. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5895. }
  5896. case 'C': // char
  5897. {
  5898. get();
  5899. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  5900. {
  5901. return false;
  5902. }
  5903. if (JSON_HEDLEY_UNLIKELY(current > 127))
  5904. {
  5905. auto last_token = get_token_string();
  5906. 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")));
  5907. }
  5908. string_t s(1, static_cast<char>(current));
  5909. return sax->string(s);
  5910. }
  5911. case 'S': // string
  5912. {
  5913. string_t s;
  5914. return get_ubjson_string(s) and sax->string(s);
  5915. }
  5916. case '[': // array
  5917. return get_ubjson_array();
  5918. case '{': // object
  5919. return get_ubjson_object();
  5920. default: // anything else
  5921. {
  5922. auto last_token = get_token_string();
  5923. 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")));
  5924. }
  5925. }
  5926. }
  5927. /*!
  5928. @return whether array creation completed
  5929. */
  5930. bool get_ubjson_array()
  5931. {
  5932. std::pair<std::size_t, int> size_and_type;
  5933. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5934. {
  5935. return false;
  5936. }
  5937. if (size_and_type.first != string_t::npos)
  5938. {
  5939. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  5940. {
  5941. return false;
  5942. }
  5943. if (size_and_type.second != 0)
  5944. {
  5945. if (size_and_type.second != 'N')
  5946. {
  5947. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5948. {
  5949. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  5950. {
  5951. return false;
  5952. }
  5953. }
  5954. }
  5955. }
  5956. else
  5957. {
  5958. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5959. {
  5960. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5961. {
  5962. return false;
  5963. }
  5964. }
  5965. }
  5966. }
  5967. else
  5968. {
  5969. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5970. {
  5971. return false;
  5972. }
  5973. while (current != ']')
  5974. {
  5975. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  5976. {
  5977. return false;
  5978. }
  5979. get_ignore_noop();
  5980. }
  5981. }
  5982. return sax->end_array();
  5983. }
  5984. /*!
  5985. @return whether object creation completed
  5986. */
  5987. bool get_ubjson_object()
  5988. {
  5989. std::pair<std::size_t, int> size_and_type;
  5990. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5991. {
  5992. return false;
  5993. }
  5994. string_t key;
  5995. if (size_and_type.first != string_t::npos)
  5996. {
  5997. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  5998. {
  5999. return false;
  6000. }
  6001. if (size_and_type.second != 0)
  6002. {
  6003. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6004. {
  6005. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6006. {
  6007. return false;
  6008. }
  6009. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6010. {
  6011. return false;
  6012. }
  6013. key.clear();
  6014. }
  6015. }
  6016. else
  6017. {
  6018. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6019. {
  6020. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6021. {
  6022. return false;
  6023. }
  6024. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6025. {
  6026. return false;
  6027. }
  6028. key.clear();
  6029. }
  6030. }
  6031. }
  6032. else
  6033. {
  6034. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6035. {
  6036. return false;
  6037. }
  6038. while (current != '}')
  6039. {
  6040. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  6041. {
  6042. return false;
  6043. }
  6044. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6045. {
  6046. return false;
  6047. }
  6048. get_ignore_noop();
  6049. key.clear();
  6050. }
  6051. }
  6052. return sax->end_object();
  6053. }
  6054. ///////////////////////
  6055. // Utility functions //
  6056. ///////////////////////
  6057. /*!
  6058. @brief get next character from the input
  6059. This function provides the interface to the used input adapter. It does
  6060. not throw in case the input reached EOF, but returns a -'ve valued
  6061. `std::char_traits<char>::eof()` in that case.
  6062. @return character read from the input
  6063. */
  6064. int get()
  6065. {
  6066. ++chars_read;
  6067. return current = ia->get_character();
  6068. }
  6069. /*!
  6070. @return character read from the input after ignoring all 'N' entries
  6071. */
  6072. int get_ignore_noop()
  6073. {
  6074. do
  6075. {
  6076. get();
  6077. }
  6078. while (current == 'N');
  6079. return current;
  6080. }
  6081. /*
  6082. @brief read a number from the input
  6083. @tparam NumberType the type of the number
  6084. @param[in] format the current format (for diagnostics)
  6085. @param[out] result number of type @a NumberType
  6086. @return whether conversion completed
  6087. @note This function needs to respect the system's endianess, because
  6088. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  6089. (big endian) and therefore need reordering on little endian systems.
  6090. */
  6091. template<typename NumberType, bool InputIsLittleEndian = false>
  6092. bool get_number(const input_format_t format, NumberType& result)
  6093. {
  6094. // step 1: read input into array with system's byte order
  6095. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6096. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6097. {
  6098. get();
  6099. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6100. {
  6101. return false;
  6102. }
  6103. // reverse byte order prior to conversion if necessary
  6104. if (is_little_endian != InputIsLittleEndian)
  6105. {
  6106. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6107. }
  6108. else
  6109. {
  6110. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6111. }
  6112. }
  6113. // step 2: convert array into number of type T and return
  6114. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6115. return true;
  6116. }
  6117. /*!
  6118. @brief create a string by reading characters from the input
  6119. @tparam NumberType the type of the number
  6120. @param[in] format the current format (for diagnostics)
  6121. @param[in] len number of characters to read
  6122. @param[out] result string created by reading @a len bytes
  6123. @return whether string creation completed
  6124. @note We can not reserve @a len bytes for the result, because @a len
  6125. may be too large. Usually, @ref unexpect_eof() detects the end of
  6126. the input before we run out of string memory.
  6127. */
  6128. template<typename NumberType>
  6129. bool get_string(const input_format_t format,
  6130. const NumberType len,
  6131. string_t& result)
  6132. {
  6133. bool success = true;
  6134. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6135. {
  6136. get();
  6137. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6138. {
  6139. success = false;
  6140. }
  6141. return static_cast<char>(current);
  6142. });
  6143. return success;
  6144. }
  6145. /*!
  6146. @param[in] format the current format (for diagnostics)
  6147. @param[in] context further context information (for diagnostics)
  6148. @return whether the last read character is not EOF
  6149. */
  6150. JSON_HEDLEY_NON_NULL(3)
  6151. bool unexpect_eof(const input_format_t format, const char* context) const
  6152. {
  6153. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  6154. {
  6155. return sax->parse_error(chars_read, "<end of file>",
  6156. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  6157. }
  6158. return true;
  6159. }
  6160. /*!
  6161. @return a string representation of the last read byte
  6162. */
  6163. std::string get_token_string() const
  6164. {
  6165. std::array<char, 3> cr{{}};
  6166. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  6167. return std::string{cr.data()};
  6168. }
  6169. /*!
  6170. @param[in] format the current format
  6171. @param[in] detail a detailed error message
  6172. @param[in] context further context information
  6173. @return a message string to use in the parse_error exceptions
  6174. */
  6175. std::string exception_message(const input_format_t format,
  6176. const std::string& detail,
  6177. const std::string& context) const
  6178. {
  6179. std::string error_msg = "syntax error while parsing ";
  6180. switch (format)
  6181. {
  6182. case input_format_t::cbor:
  6183. error_msg += "CBOR";
  6184. break;
  6185. case input_format_t::msgpack:
  6186. error_msg += "MessagePack";
  6187. break;
  6188. case input_format_t::ubjson:
  6189. error_msg += "UBJSON";
  6190. break;
  6191. case input_format_t::bson:
  6192. error_msg += "BSON";
  6193. break;
  6194. default: // LCOV_EXCL_LINE
  6195. assert(false); // LCOV_EXCL_LINE
  6196. }
  6197. return error_msg + " " + context + ": " + detail;
  6198. }
  6199. private:
  6200. /// input adapter
  6201. input_adapter_t ia = nullptr;
  6202. /// the current character
  6203. int current = std::char_traits<char>::eof();
  6204. /// the number of characters read
  6205. std::size_t chars_read = 0;
  6206. /// whether we can assume little endianess
  6207. const bool is_little_endian = little_endianess();
  6208. /// the SAX parser
  6209. json_sax_t* sax = nullptr;
  6210. };
  6211. } // namespace detail
  6212. } // namespace nlohmann
  6213. // #include <nlohmann/detail/input/input_adapters.hpp>
  6214. // #include <nlohmann/detail/input/lexer.hpp>
  6215. #include <array> // array
  6216. #include <clocale> // localeconv
  6217. #include <cstddef> // size_t
  6218. #include <cstdio> // snprintf
  6219. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  6220. #include <initializer_list> // initializer_list
  6221. #include <string> // char_traits, string
  6222. #include <utility> // move
  6223. #include <vector> // vector
  6224. // #include <nlohmann/detail/input/input_adapters.hpp>
  6225. // #include <nlohmann/detail/input/position_t.hpp>
  6226. // #include <nlohmann/detail/macro_scope.hpp>
  6227. namespace nlohmann
  6228. {
  6229. namespace detail
  6230. {
  6231. ///////////
  6232. // lexer //
  6233. ///////////
  6234. /*!
  6235. @brief lexical analysis
  6236. This class organizes the lexical analysis during JSON deserialization.
  6237. */
  6238. template<typename BasicJsonType>
  6239. class lexer
  6240. {
  6241. using number_integer_t = typename BasicJsonType::number_integer_t;
  6242. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6243. using number_float_t = typename BasicJsonType::number_float_t;
  6244. using string_t = typename BasicJsonType::string_t;
  6245. public:
  6246. /// token types for the parser
  6247. enum class token_type
  6248. {
  6249. uninitialized, ///< indicating the scanner is uninitialized
  6250. literal_true, ///< the `true` literal
  6251. literal_false, ///< the `false` literal
  6252. literal_null, ///< the `null` literal
  6253. value_string, ///< a string -- use get_string() for actual value
  6254. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  6255. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  6256. value_float, ///< an floating point number -- use get_number_float() for actual value
  6257. begin_array, ///< the character for array begin `[`
  6258. begin_object, ///< the character for object begin `{`
  6259. end_array, ///< the character for array end `]`
  6260. end_object, ///< the character for object end `}`
  6261. name_separator, ///< the name separator `:`
  6262. value_separator, ///< the value separator `,`
  6263. parse_error, ///< indicating a parse error
  6264. end_of_input, ///< indicating the end of the input buffer
  6265. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  6266. };
  6267. /// return name of values of type token_type (only used for errors)
  6268. JSON_HEDLEY_RETURNS_NON_NULL
  6269. JSON_HEDLEY_CONST
  6270. static const char* token_type_name(const token_type t) noexcept
  6271. {
  6272. switch (t)
  6273. {
  6274. case token_type::uninitialized:
  6275. return "<uninitialized>";
  6276. case token_type::literal_true:
  6277. return "true literal";
  6278. case token_type::literal_false:
  6279. return "false literal";
  6280. case token_type::literal_null:
  6281. return "null literal";
  6282. case token_type::value_string:
  6283. return "string literal";
  6284. case lexer::token_type::value_unsigned:
  6285. case lexer::token_type::value_integer:
  6286. case lexer::token_type::value_float:
  6287. return "number literal";
  6288. case token_type::begin_array:
  6289. return "'['";
  6290. case token_type::begin_object:
  6291. return "'{'";
  6292. case token_type::end_array:
  6293. return "']'";
  6294. case token_type::end_object:
  6295. return "'}'";
  6296. case token_type::name_separator:
  6297. return "':'";
  6298. case token_type::value_separator:
  6299. return "','";
  6300. case token_type::parse_error:
  6301. return "<parse error>";
  6302. case token_type::end_of_input:
  6303. return "end of input";
  6304. case token_type::literal_or_value:
  6305. return "'[', '{', or a literal";
  6306. // LCOV_EXCL_START
  6307. default: // catch non-enum values
  6308. return "unknown token";
  6309. // LCOV_EXCL_STOP
  6310. }
  6311. }
  6312. explicit lexer(detail::input_adapter_t&& adapter)
  6313. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  6314. // delete because of pointer members
  6315. lexer(const lexer&) = delete;
  6316. lexer(lexer&&) = delete;
  6317. lexer& operator=(lexer&) = delete;
  6318. lexer& operator=(lexer&&) = delete;
  6319. ~lexer() = default;
  6320. private:
  6321. /////////////////////
  6322. // locales
  6323. /////////////////////
  6324. /// return the locale-dependent decimal point
  6325. JSON_HEDLEY_PURE
  6326. static char get_decimal_point() noexcept
  6327. {
  6328. const auto loc = localeconv();
  6329. assert(loc != nullptr);
  6330. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  6331. }
  6332. /////////////////////
  6333. // scan functions
  6334. /////////////////////
  6335. /*!
  6336. @brief get codepoint from 4 hex characters following `\u`
  6337. For input "\u c1 c2 c3 c4" the codepoint is:
  6338. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  6339. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  6340. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  6341. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  6342. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  6343. between the ASCII value of the character and the desired integer value.
  6344. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  6345. non-hex character)
  6346. */
  6347. int get_codepoint()
  6348. {
  6349. // this function only makes sense after reading `\u`
  6350. assert(current == 'u');
  6351. int codepoint = 0;
  6352. const auto factors = { 12u, 8u, 4u, 0u };
  6353. for (const auto factor : factors)
  6354. {
  6355. get();
  6356. if (current >= '0' and current <= '9')
  6357. {
  6358. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  6359. }
  6360. else if (current >= 'A' and current <= 'F')
  6361. {
  6362. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  6363. }
  6364. else if (current >= 'a' and current <= 'f')
  6365. {
  6366. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  6367. }
  6368. else
  6369. {
  6370. return -1;
  6371. }
  6372. }
  6373. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  6374. return codepoint;
  6375. }
  6376. /*!
  6377. @brief check if the next byte(s) are inside a given range
  6378. Adds the current byte and, for each passed range, reads a new byte and
  6379. checks if it is inside the range. If a violation was detected, set up an
  6380. error message and return false. Otherwise, return true.
  6381. @param[in] ranges list of integers; interpreted as list of pairs of
  6382. inclusive lower and upper bound, respectively
  6383. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  6384. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  6385. @return true if and only if no range violation was detected
  6386. */
  6387. bool next_byte_in_range(std::initializer_list<int> ranges)
  6388. {
  6389. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  6390. add(current);
  6391. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  6392. {
  6393. get();
  6394. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  6395. {
  6396. add(current);
  6397. }
  6398. else
  6399. {
  6400. error_message = "invalid string: ill-formed UTF-8 byte";
  6401. return false;
  6402. }
  6403. }
  6404. return true;
  6405. }
  6406. /*!
  6407. @brief scan a string literal
  6408. This function scans a string according to Sect. 7 of RFC 7159. While
  6409. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  6410. function returns successfully, token_buffer is *not* null-terminated (as it
  6411. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  6412. string.
  6413. @return token_type::value_string if string could be successfully scanned,
  6414. token_type::parse_error otherwise
  6415. @note In case of errors, variable error_message contains a textual
  6416. description.
  6417. */
  6418. token_type scan_string()
  6419. {
  6420. // reset token_buffer (ignore opening quote)
  6421. reset();
  6422. // we entered the function by reading an open quote
  6423. assert(current == '\"');
  6424. while (true)
  6425. {
  6426. // get next character
  6427. switch (get())
  6428. {
  6429. // end of file while parsing string
  6430. case std::char_traits<char>::eof():
  6431. {
  6432. error_message = "invalid string: missing closing quote";
  6433. return token_type::parse_error;
  6434. }
  6435. // closing quote
  6436. case '\"':
  6437. {
  6438. return token_type::value_string;
  6439. }
  6440. // escapes
  6441. case '\\':
  6442. {
  6443. switch (get())
  6444. {
  6445. // quotation mark
  6446. case '\"':
  6447. add('\"');
  6448. break;
  6449. // reverse solidus
  6450. case '\\':
  6451. add('\\');
  6452. break;
  6453. // solidus
  6454. case '/':
  6455. add('/');
  6456. break;
  6457. // backspace
  6458. case 'b':
  6459. add('\b');
  6460. break;
  6461. // form feed
  6462. case 'f':
  6463. add('\f');
  6464. break;
  6465. // line feed
  6466. case 'n':
  6467. add('\n');
  6468. break;
  6469. // carriage return
  6470. case 'r':
  6471. add('\r');
  6472. break;
  6473. // tab
  6474. case 't':
  6475. add('\t');
  6476. break;
  6477. // unicode escapes
  6478. case 'u':
  6479. {
  6480. const int codepoint1 = get_codepoint();
  6481. int codepoint = codepoint1; // start with codepoint1
  6482. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  6483. {
  6484. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6485. return token_type::parse_error;
  6486. }
  6487. // check if code point is a high surrogate
  6488. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  6489. {
  6490. // expect next \uxxxx entry
  6491. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  6492. {
  6493. const int codepoint2 = get_codepoint();
  6494. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  6495. {
  6496. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6497. return token_type::parse_error;
  6498. }
  6499. // check if codepoint2 is a low surrogate
  6500. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  6501. {
  6502. // overwrite codepoint
  6503. codepoint = static_cast<int>(
  6504. // high surrogate occupies the most significant 22 bits
  6505. (static_cast<unsigned int>(codepoint1) << 10u)
  6506. // low surrogate occupies the least significant 15 bits
  6507. + static_cast<unsigned int>(codepoint2)
  6508. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6509. // in the result so we have to subtract with:
  6510. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6511. - 0x35FDC00u);
  6512. }
  6513. else
  6514. {
  6515. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6516. return token_type::parse_error;
  6517. }
  6518. }
  6519. else
  6520. {
  6521. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6522. return token_type::parse_error;
  6523. }
  6524. }
  6525. else
  6526. {
  6527. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  6528. {
  6529. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6530. return token_type::parse_error;
  6531. }
  6532. }
  6533. // result of the above calculation yields a proper codepoint
  6534. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  6535. // translate codepoint into bytes
  6536. if (codepoint < 0x80)
  6537. {
  6538. // 1-byte characters: 0xxxxxxx (ASCII)
  6539. add(codepoint);
  6540. }
  6541. else if (codepoint <= 0x7FF)
  6542. {
  6543. // 2-byte characters: 110xxxxx 10xxxxxx
  6544. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6545. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6546. }
  6547. else if (codepoint <= 0xFFFF)
  6548. {
  6549. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6550. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6551. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6552. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6553. }
  6554. else
  6555. {
  6556. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6557. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6558. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6559. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6560. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6561. }
  6562. break;
  6563. }
  6564. // other characters after escape
  6565. default:
  6566. error_message = "invalid string: forbidden character after backslash";
  6567. return token_type::parse_error;
  6568. }
  6569. break;
  6570. }
  6571. // invalid control characters
  6572. case 0x00:
  6573. {
  6574. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6575. return token_type::parse_error;
  6576. }
  6577. case 0x01:
  6578. {
  6579. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6580. return token_type::parse_error;
  6581. }
  6582. case 0x02:
  6583. {
  6584. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6585. return token_type::parse_error;
  6586. }
  6587. case 0x03:
  6588. {
  6589. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6590. return token_type::parse_error;
  6591. }
  6592. case 0x04:
  6593. {
  6594. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6595. return token_type::parse_error;
  6596. }
  6597. case 0x05:
  6598. {
  6599. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6600. return token_type::parse_error;
  6601. }
  6602. case 0x06:
  6603. {
  6604. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6605. return token_type::parse_error;
  6606. }
  6607. case 0x07:
  6608. {
  6609. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6610. return token_type::parse_error;
  6611. }
  6612. case 0x08:
  6613. {
  6614. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6615. return token_type::parse_error;
  6616. }
  6617. case 0x09:
  6618. {
  6619. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6620. return token_type::parse_error;
  6621. }
  6622. case 0x0A:
  6623. {
  6624. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6625. return token_type::parse_error;
  6626. }
  6627. case 0x0B:
  6628. {
  6629. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6630. return token_type::parse_error;
  6631. }
  6632. case 0x0C:
  6633. {
  6634. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6635. return token_type::parse_error;
  6636. }
  6637. case 0x0D:
  6638. {
  6639. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6640. return token_type::parse_error;
  6641. }
  6642. case 0x0E:
  6643. {
  6644. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6645. return token_type::parse_error;
  6646. }
  6647. case 0x0F:
  6648. {
  6649. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6650. return token_type::parse_error;
  6651. }
  6652. case 0x10:
  6653. {
  6654. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6655. return token_type::parse_error;
  6656. }
  6657. case 0x11:
  6658. {
  6659. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6660. return token_type::parse_error;
  6661. }
  6662. case 0x12:
  6663. {
  6664. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6665. return token_type::parse_error;
  6666. }
  6667. case 0x13:
  6668. {
  6669. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6670. return token_type::parse_error;
  6671. }
  6672. case 0x14:
  6673. {
  6674. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6675. return token_type::parse_error;
  6676. }
  6677. case 0x15:
  6678. {
  6679. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6680. return token_type::parse_error;
  6681. }
  6682. case 0x16:
  6683. {
  6684. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6685. return token_type::parse_error;
  6686. }
  6687. case 0x17:
  6688. {
  6689. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6690. return token_type::parse_error;
  6691. }
  6692. case 0x18:
  6693. {
  6694. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6695. return token_type::parse_error;
  6696. }
  6697. case 0x19:
  6698. {
  6699. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6700. return token_type::parse_error;
  6701. }
  6702. case 0x1A:
  6703. {
  6704. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6705. return token_type::parse_error;
  6706. }
  6707. case 0x1B:
  6708. {
  6709. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6710. return token_type::parse_error;
  6711. }
  6712. case 0x1C:
  6713. {
  6714. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6715. return token_type::parse_error;
  6716. }
  6717. case 0x1D:
  6718. {
  6719. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6720. return token_type::parse_error;
  6721. }
  6722. case 0x1E:
  6723. {
  6724. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6725. return token_type::parse_error;
  6726. }
  6727. case 0x1F:
  6728. {
  6729. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6730. return token_type::parse_error;
  6731. }
  6732. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6733. case 0x20:
  6734. case 0x21:
  6735. case 0x23:
  6736. case 0x24:
  6737. case 0x25:
  6738. case 0x26:
  6739. case 0x27:
  6740. case 0x28:
  6741. case 0x29:
  6742. case 0x2A:
  6743. case 0x2B:
  6744. case 0x2C:
  6745. case 0x2D:
  6746. case 0x2E:
  6747. case 0x2F:
  6748. case 0x30:
  6749. case 0x31:
  6750. case 0x32:
  6751. case 0x33:
  6752. case 0x34:
  6753. case 0x35:
  6754. case 0x36:
  6755. case 0x37:
  6756. case 0x38:
  6757. case 0x39:
  6758. case 0x3A:
  6759. case 0x3B:
  6760. case 0x3C:
  6761. case 0x3D:
  6762. case 0x3E:
  6763. case 0x3F:
  6764. case 0x40:
  6765. case 0x41:
  6766. case 0x42:
  6767. case 0x43:
  6768. case 0x44:
  6769. case 0x45:
  6770. case 0x46:
  6771. case 0x47:
  6772. case 0x48:
  6773. case 0x49:
  6774. case 0x4A:
  6775. case 0x4B:
  6776. case 0x4C:
  6777. case 0x4D:
  6778. case 0x4E:
  6779. case 0x4F:
  6780. case 0x50:
  6781. case 0x51:
  6782. case 0x52:
  6783. case 0x53:
  6784. case 0x54:
  6785. case 0x55:
  6786. case 0x56:
  6787. case 0x57:
  6788. case 0x58:
  6789. case 0x59:
  6790. case 0x5A:
  6791. case 0x5B:
  6792. case 0x5D:
  6793. case 0x5E:
  6794. case 0x5F:
  6795. case 0x60:
  6796. case 0x61:
  6797. case 0x62:
  6798. case 0x63:
  6799. case 0x64:
  6800. case 0x65:
  6801. case 0x66:
  6802. case 0x67:
  6803. case 0x68:
  6804. case 0x69:
  6805. case 0x6A:
  6806. case 0x6B:
  6807. case 0x6C:
  6808. case 0x6D:
  6809. case 0x6E:
  6810. case 0x6F:
  6811. case 0x70:
  6812. case 0x71:
  6813. case 0x72:
  6814. case 0x73:
  6815. case 0x74:
  6816. case 0x75:
  6817. case 0x76:
  6818. case 0x77:
  6819. case 0x78:
  6820. case 0x79:
  6821. case 0x7A:
  6822. case 0x7B:
  6823. case 0x7C:
  6824. case 0x7D:
  6825. case 0x7E:
  6826. case 0x7F:
  6827. {
  6828. add(current);
  6829. break;
  6830. }
  6831. // U+0080..U+07FF: bytes C2..DF 80..BF
  6832. case 0xC2:
  6833. case 0xC3:
  6834. case 0xC4:
  6835. case 0xC5:
  6836. case 0xC6:
  6837. case 0xC7:
  6838. case 0xC8:
  6839. case 0xC9:
  6840. case 0xCA:
  6841. case 0xCB:
  6842. case 0xCC:
  6843. case 0xCD:
  6844. case 0xCE:
  6845. case 0xCF:
  6846. case 0xD0:
  6847. case 0xD1:
  6848. case 0xD2:
  6849. case 0xD3:
  6850. case 0xD4:
  6851. case 0xD5:
  6852. case 0xD6:
  6853. case 0xD7:
  6854. case 0xD8:
  6855. case 0xD9:
  6856. case 0xDA:
  6857. case 0xDB:
  6858. case 0xDC:
  6859. case 0xDD:
  6860. case 0xDE:
  6861. case 0xDF:
  6862. {
  6863. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  6864. {
  6865. return token_type::parse_error;
  6866. }
  6867. break;
  6868. }
  6869. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6870. case 0xE0:
  6871. {
  6872. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6873. {
  6874. return token_type::parse_error;
  6875. }
  6876. break;
  6877. }
  6878. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6879. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6880. case 0xE1:
  6881. case 0xE2:
  6882. case 0xE3:
  6883. case 0xE4:
  6884. case 0xE5:
  6885. case 0xE6:
  6886. case 0xE7:
  6887. case 0xE8:
  6888. case 0xE9:
  6889. case 0xEA:
  6890. case 0xEB:
  6891. case 0xEC:
  6892. case 0xEE:
  6893. case 0xEF:
  6894. {
  6895. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6896. {
  6897. return token_type::parse_error;
  6898. }
  6899. break;
  6900. }
  6901. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6902. case 0xED:
  6903. {
  6904. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6905. {
  6906. return token_type::parse_error;
  6907. }
  6908. break;
  6909. }
  6910. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6911. case 0xF0:
  6912. {
  6913. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6914. {
  6915. return token_type::parse_error;
  6916. }
  6917. break;
  6918. }
  6919. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6920. case 0xF1:
  6921. case 0xF2:
  6922. case 0xF3:
  6923. {
  6924. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6925. {
  6926. return token_type::parse_error;
  6927. }
  6928. break;
  6929. }
  6930. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6931. case 0xF4:
  6932. {
  6933. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6934. {
  6935. return token_type::parse_error;
  6936. }
  6937. break;
  6938. }
  6939. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6940. default:
  6941. {
  6942. error_message = "invalid string: ill-formed UTF-8 byte";
  6943. return token_type::parse_error;
  6944. }
  6945. }
  6946. }
  6947. }
  6948. JSON_HEDLEY_NON_NULL(2)
  6949. static void strtof(float& f, const char* str, char** endptr) noexcept
  6950. {
  6951. f = std::strtof(str, endptr);
  6952. }
  6953. JSON_HEDLEY_NON_NULL(2)
  6954. static void strtof(double& f, const char* str, char** endptr) noexcept
  6955. {
  6956. f = std::strtod(str, endptr);
  6957. }
  6958. JSON_HEDLEY_NON_NULL(2)
  6959. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6960. {
  6961. f = std::strtold(str, endptr);
  6962. }
  6963. /*!
  6964. @brief scan a number literal
  6965. This function scans a string according to Sect. 6 of RFC 7159.
  6966. The function is realized with a deterministic finite state machine derived
  6967. from the grammar described in RFC 7159. Starting in state "init", the
  6968. input is read and used to determined the next state. Only state "done"
  6969. accepts the number. State "error" is a trap state to model errors. In the
  6970. table below, "anything" means any character but the ones listed before.
  6971. state | 0 | 1-9 | e E | + | - | . | anything
  6972. ---------|----------|----------|----------|---------|---------|----------|-----------
  6973. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6974. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6975. zero | done | done | exponent | done | done | decimal1 | done
  6976. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6977. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  6978. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6979. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6980. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6981. any2 | any2 | any2 | done | done | done | done | done
  6982. The state machine is realized with one label per state (prefixed with
  6983. "scan_number_") and `goto` statements between them. The state machine
  6984. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6985. the function is guaranteed to terminate.
  6986. During scanning, the read bytes are stored in token_buffer. This string is
  6987. then converted to a signed integer, an unsigned integer, or a
  6988. floating-point number.
  6989. @return token_type::value_unsigned, token_type::value_integer, or
  6990. token_type::value_float if number could be successfully scanned,
  6991. token_type::parse_error otherwise
  6992. @note The scanner is independent of the current locale. Internally, the
  6993. locale's decimal point is used instead of `.` to work with the
  6994. locale-dependent converters.
  6995. */
  6996. token_type scan_number() // lgtm [cpp/use-of-goto]
  6997. {
  6998. // reset token_buffer to store the number's bytes
  6999. reset();
  7000. // the type of the parsed number; initially set to unsigned; will be
  7001. // changed if minus sign, decimal point or exponent is read
  7002. token_type number_type = token_type::value_unsigned;
  7003. // state (init): we just found out we need to scan a number
  7004. switch (current)
  7005. {
  7006. case '-':
  7007. {
  7008. add(current);
  7009. goto scan_number_minus;
  7010. }
  7011. case '0':
  7012. {
  7013. add(current);
  7014. goto scan_number_zero;
  7015. }
  7016. case '1':
  7017. case '2':
  7018. case '3':
  7019. case '4':
  7020. case '5':
  7021. case '6':
  7022. case '7':
  7023. case '8':
  7024. case '9':
  7025. {
  7026. add(current);
  7027. goto scan_number_any1;
  7028. }
  7029. // all other characters are rejected outside scan_number()
  7030. default: // LCOV_EXCL_LINE
  7031. assert(false); // LCOV_EXCL_LINE
  7032. }
  7033. scan_number_minus:
  7034. // state: we just parsed a leading minus sign
  7035. number_type = token_type::value_integer;
  7036. switch (get())
  7037. {
  7038. case '0':
  7039. {
  7040. add(current);
  7041. goto scan_number_zero;
  7042. }
  7043. case '1':
  7044. case '2':
  7045. case '3':
  7046. case '4':
  7047. case '5':
  7048. case '6':
  7049. case '7':
  7050. case '8':
  7051. case '9':
  7052. {
  7053. add(current);
  7054. goto scan_number_any1;
  7055. }
  7056. default:
  7057. {
  7058. error_message = "invalid number; expected digit after '-'";
  7059. return token_type::parse_error;
  7060. }
  7061. }
  7062. scan_number_zero:
  7063. // state: we just parse a zero (maybe with a leading minus sign)
  7064. switch (get())
  7065. {
  7066. case '.':
  7067. {
  7068. add(decimal_point_char);
  7069. goto scan_number_decimal1;
  7070. }
  7071. case 'e':
  7072. case 'E':
  7073. {
  7074. add(current);
  7075. goto scan_number_exponent;
  7076. }
  7077. default:
  7078. goto scan_number_done;
  7079. }
  7080. scan_number_any1:
  7081. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  7082. switch (get())
  7083. {
  7084. case '0':
  7085. case '1':
  7086. case '2':
  7087. case '3':
  7088. case '4':
  7089. case '5':
  7090. case '6':
  7091. case '7':
  7092. case '8':
  7093. case '9':
  7094. {
  7095. add(current);
  7096. goto scan_number_any1;
  7097. }
  7098. case '.':
  7099. {
  7100. add(decimal_point_char);
  7101. goto scan_number_decimal1;
  7102. }
  7103. case 'e':
  7104. case 'E':
  7105. {
  7106. add(current);
  7107. goto scan_number_exponent;
  7108. }
  7109. default:
  7110. goto scan_number_done;
  7111. }
  7112. scan_number_decimal1:
  7113. // state: we just parsed a decimal point
  7114. number_type = token_type::value_float;
  7115. switch (get())
  7116. {
  7117. case '0':
  7118. case '1':
  7119. case '2':
  7120. case '3':
  7121. case '4':
  7122. case '5':
  7123. case '6':
  7124. case '7':
  7125. case '8':
  7126. case '9':
  7127. {
  7128. add(current);
  7129. goto scan_number_decimal2;
  7130. }
  7131. default:
  7132. {
  7133. error_message = "invalid number; expected digit after '.'";
  7134. return token_type::parse_error;
  7135. }
  7136. }
  7137. scan_number_decimal2:
  7138. // we just parsed at least one number after a decimal point
  7139. switch (get())
  7140. {
  7141. case '0':
  7142. case '1':
  7143. case '2':
  7144. case '3':
  7145. case '4':
  7146. case '5':
  7147. case '6':
  7148. case '7':
  7149. case '8':
  7150. case '9':
  7151. {
  7152. add(current);
  7153. goto scan_number_decimal2;
  7154. }
  7155. case 'e':
  7156. case 'E':
  7157. {
  7158. add(current);
  7159. goto scan_number_exponent;
  7160. }
  7161. default:
  7162. goto scan_number_done;
  7163. }
  7164. scan_number_exponent:
  7165. // we just parsed an exponent
  7166. number_type = token_type::value_float;
  7167. switch (get())
  7168. {
  7169. case '+':
  7170. case '-':
  7171. {
  7172. add(current);
  7173. goto scan_number_sign;
  7174. }
  7175. case '0':
  7176. case '1':
  7177. case '2':
  7178. case '3':
  7179. case '4':
  7180. case '5':
  7181. case '6':
  7182. case '7':
  7183. case '8':
  7184. case '9':
  7185. {
  7186. add(current);
  7187. goto scan_number_any2;
  7188. }
  7189. default:
  7190. {
  7191. error_message =
  7192. "invalid number; expected '+', '-', or digit after exponent";
  7193. return token_type::parse_error;
  7194. }
  7195. }
  7196. scan_number_sign:
  7197. // we just parsed an exponent sign
  7198. switch (get())
  7199. {
  7200. case '0':
  7201. case '1':
  7202. case '2':
  7203. case '3':
  7204. case '4':
  7205. case '5':
  7206. case '6':
  7207. case '7':
  7208. case '8':
  7209. case '9':
  7210. {
  7211. add(current);
  7212. goto scan_number_any2;
  7213. }
  7214. default:
  7215. {
  7216. error_message = "invalid number; expected digit after exponent sign";
  7217. return token_type::parse_error;
  7218. }
  7219. }
  7220. scan_number_any2:
  7221. // we just parsed a number after the exponent or exponent sign
  7222. switch (get())
  7223. {
  7224. case '0':
  7225. case '1':
  7226. case '2':
  7227. case '3':
  7228. case '4':
  7229. case '5':
  7230. case '6':
  7231. case '7':
  7232. case '8':
  7233. case '9':
  7234. {
  7235. add(current);
  7236. goto scan_number_any2;
  7237. }
  7238. default:
  7239. goto scan_number_done;
  7240. }
  7241. scan_number_done:
  7242. // unget the character after the number (we only read it to know that
  7243. // we are done scanning a number)
  7244. unget();
  7245. char* endptr = nullptr;
  7246. errno = 0;
  7247. // try to parse integers first and fall back to floats
  7248. if (number_type == token_type::value_unsigned)
  7249. {
  7250. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  7251. // we checked the number format before
  7252. assert(endptr == token_buffer.data() + token_buffer.size());
  7253. if (errno == 0)
  7254. {
  7255. value_unsigned = static_cast<number_unsigned_t>(x);
  7256. if (value_unsigned == x)
  7257. {
  7258. return token_type::value_unsigned;
  7259. }
  7260. }
  7261. }
  7262. else if (number_type == token_type::value_integer)
  7263. {
  7264. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  7265. // we checked the number format before
  7266. assert(endptr == token_buffer.data() + token_buffer.size());
  7267. if (errno == 0)
  7268. {
  7269. value_integer = static_cast<number_integer_t>(x);
  7270. if (value_integer == x)
  7271. {
  7272. return token_type::value_integer;
  7273. }
  7274. }
  7275. }
  7276. // this code is reached if we parse a floating-point number or if an
  7277. // integer conversion above failed
  7278. strtof(value_float, token_buffer.data(), &endptr);
  7279. // we checked the number format before
  7280. assert(endptr == token_buffer.data() + token_buffer.size());
  7281. return token_type::value_float;
  7282. }
  7283. /*!
  7284. @param[in] literal_text the literal text to expect
  7285. @param[in] length the length of the passed literal text
  7286. @param[in] return_type the token type to return on success
  7287. */
  7288. JSON_HEDLEY_NON_NULL(2)
  7289. token_type scan_literal(const char* literal_text, const std::size_t length,
  7290. token_type return_type)
  7291. {
  7292. assert(current == literal_text[0]);
  7293. for (std::size_t i = 1; i < length; ++i)
  7294. {
  7295. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  7296. {
  7297. error_message = "invalid literal";
  7298. return token_type::parse_error;
  7299. }
  7300. }
  7301. return return_type;
  7302. }
  7303. /////////////////////
  7304. // input management
  7305. /////////////////////
  7306. /// reset token_buffer; current character is beginning of token
  7307. void reset() noexcept
  7308. {
  7309. token_buffer.clear();
  7310. token_string.clear();
  7311. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7312. }
  7313. /*
  7314. @brief get next character from the input
  7315. This function provides the interface to the used input adapter. It does
  7316. not throw in case the input reached EOF, but returns a
  7317. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  7318. for use in error messages.
  7319. @return character read from the input
  7320. */
  7321. std::char_traits<char>::int_type get()
  7322. {
  7323. ++position.chars_read_total;
  7324. ++position.chars_read_current_line;
  7325. if (next_unget)
  7326. {
  7327. // just reset the next_unget variable and work with current
  7328. next_unget = false;
  7329. }
  7330. else
  7331. {
  7332. current = ia->get_character();
  7333. }
  7334. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7335. {
  7336. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7337. }
  7338. if (current == '\n')
  7339. {
  7340. ++position.lines_read;
  7341. position.chars_read_current_line = 0;
  7342. }
  7343. return current;
  7344. }
  7345. /*!
  7346. @brief unget current character (read it again on next get)
  7347. We implement unget by setting variable next_unget to true. The input is not
  7348. changed - we just simulate ungetting by modifying chars_read_total,
  7349. chars_read_current_line, and token_string. The next call to get() will
  7350. behave as if the unget character is read again.
  7351. */
  7352. void unget()
  7353. {
  7354. next_unget = true;
  7355. --position.chars_read_total;
  7356. // in case we "unget" a newline, we have to also decrement the lines_read
  7357. if (position.chars_read_current_line == 0)
  7358. {
  7359. if (position.lines_read > 0)
  7360. {
  7361. --position.lines_read;
  7362. }
  7363. }
  7364. else
  7365. {
  7366. --position.chars_read_current_line;
  7367. }
  7368. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7369. {
  7370. assert(not token_string.empty());
  7371. token_string.pop_back();
  7372. }
  7373. }
  7374. /// add a character to token_buffer
  7375. void add(int c)
  7376. {
  7377. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  7378. }
  7379. public:
  7380. /////////////////////
  7381. // value getters
  7382. /////////////////////
  7383. /// return integer value
  7384. constexpr number_integer_t get_number_integer() const noexcept
  7385. {
  7386. return value_integer;
  7387. }
  7388. /// return unsigned integer value
  7389. constexpr number_unsigned_t get_number_unsigned() const noexcept
  7390. {
  7391. return value_unsigned;
  7392. }
  7393. /// return floating-point value
  7394. constexpr number_float_t get_number_float() const noexcept
  7395. {
  7396. return value_float;
  7397. }
  7398. /// return current string value (implicitly resets the token; useful only once)
  7399. string_t& get_string()
  7400. {
  7401. return token_buffer;
  7402. }
  7403. /////////////////////
  7404. // diagnostics
  7405. /////////////////////
  7406. /// return position of last read token
  7407. constexpr position_t get_position() const noexcept
  7408. {
  7409. return position;
  7410. }
  7411. /// return the last read token (for errors only). Will never contain EOF
  7412. /// (an arbitrary value that is not a valid char value, often -1), because
  7413. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  7414. std::string get_token_string() const
  7415. {
  7416. // escape control characters
  7417. std::string result;
  7418. for (const auto c : token_string)
  7419. {
  7420. if ('\x00' <= c and c <= '\x1F')
  7421. {
  7422. // escape control characters
  7423. std::array<char, 9> cs{{}};
  7424. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  7425. result += cs.data();
  7426. }
  7427. else
  7428. {
  7429. // add character as is
  7430. result.push_back(c);
  7431. }
  7432. }
  7433. return result;
  7434. }
  7435. /// return syntax error message
  7436. JSON_HEDLEY_RETURNS_NON_NULL
  7437. constexpr const char* get_error_message() const noexcept
  7438. {
  7439. return error_message;
  7440. }
  7441. /////////////////////
  7442. // actual scanner
  7443. /////////////////////
  7444. /*!
  7445. @brief skip the UTF-8 byte order mark
  7446. @return true iff there is no BOM or the correct BOM has been skipped
  7447. */
  7448. bool skip_bom()
  7449. {
  7450. if (get() == 0xEF)
  7451. {
  7452. // check if we completely parse the BOM
  7453. return get() == 0xBB and get() == 0xBF;
  7454. }
  7455. // the first character is not the beginning of the BOM; unget it to
  7456. // process is later
  7457. unget();
  7458. return true;
  7459. }
  7460. token_type scan()
  7461. {
  7462. // initially, skip the BOM
  7463. if (position.chars_read_total == 0 and not skip_bom())
  7464. {
  7465. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7466. return token_type::parse_error;
  7467. }
  7468. // read next character and ignore whitespace
  7469. do
  7470. {
  7471. get();
  7472. }
  7473. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  7474. switch (current)
  7475. {
  7476. // structural characters
  7477. case '[':
  7478. return token_type::begin_array;
  7479. case ']':
  7480. return token_type::end_array;
  7481. case '{':
  7482. return token_type::begin_object;
  7483. case '}':
  7484. return token_type::end_object;
  7485. case ':':
  7486. return token_type::name_separator;
  7487. case ',':
  7488. return token_type::value_separator;
  7489. // literals
  7490. case 't':
  7491. return scan_literal("true", 4, token_type::literal_true);
  7492. case 'f':
  7493. return scan_literal("false", 5, token_type::literal_false);
  7494. case 'n':
  7495. return scan_literal("null", 4, token_type::literal_null);
  7496. // string
  7497. case '\"':
  7498. return scan_string();
  7499. // number
  7500. case '-':
  7501. case '0':
  7502. case '1':
  7503. case '2':
  7504. case '3':
  7505. case '4':
  7506. case '5':
  7507. case '6':
  7508. case '7':
  7509. case '8':
  7510. case '9':
  7511. return scan_number();
  7512. // end of input (the null byte is needed when parsing from
  7513. // string literals)
  7514. case '\0':
  7515. case std::char_traits<char>::eof():
  7516. return token_type::end_of_input;
  7517. // error
  7518. default:
  7519. error_message = "invalid literal";
  7520. return token_type::parse_error;
  7521. }
  7522. }
  7523. private:
  7524. /// input adapter
  7525. detail::input_adapter_t ia = nullptr;
  7526. /// the current character
  7527. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  7528. /// whether the next get() call should just return current
  7529. bool next_unget = false;
  7530. /// the start position of the current token
  7531. position_t position {};
  7532. /// raw input token string (for error messages)
  7533. std::vector<char> token_string {};
  7534. /// buffer for variable-length tokens (numbers, strings)
  7535. string_t token_buffer {};
  7536. /// a description of occurred lexer errors
  7537. const char* error_message = "";
  7538. // number values
  7539. number_integer_t value_integer = 0;
  7540. number_unsigned_t value_unsigned = 0;
  7541. number_float_t value_float = 0;
  7542. /// the decimal point
  7543. const char decimal_point_char = '.';
  7544. };
  7545. } // namespace detail
  7546. } // namespace nlohmann
  7547. // #include <nlohmann/detail/input/parser.hpp>
  7548. #include <cassert> // assert
  7549. #include <cmath> // isfinite
  7550. #include <cstdint> // uint8_t
  7551. #include <functional> // function
  7552. #include <string> // string
  7553. #include <utility> // move
  7554. #include <vector> // vector
  7555. // #include <nlohmann/detail/exceptions.hpp>
  7556. // #include <nlohmann/detail/input/input_adapters.hpp>
  7557. // #include <nlohmann/detail/input/json_sax.hpp>
  7558. // #include <nlohmann/detail/input/lexer.hpp>
  7559. // #include <nlohmann/detail/macro_scope.hpp>
  7560. // #include <nlohmann/detail/meta/is_sax.hpp>
  7561. // #include <nlohmann/detail/value_t.hpp>
  7562. namespace nlohmann
  7563. {
  7564. namespace detail
  7565. {
  7566. ////////////
  7567. // parser //
  7568. ////////////
  7569. /*!
  7570. @brief syntax analysis
  7571. This class implements a recursive decent parser.
  7572. */
  7573. template<typename BasicJsonType>
  7574. class parser
  7575. {
  7576. using number_integer_t = typename BasicJsonType::number_integer_t;
  7577. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7578. using number_float_t = typename BasicJsonType::number_float_t;
  7579. using string_t = typename BasicJsonType::string_t;
  7580. using lexer_t = lexer<BasicJsonType>;
  7581. using token_type = typename lexer_t::token_type;
  7582. public:
  7583. enum class parse_event_t : uint8_t
  7584. {
  7585. /// the parser read `{` and started to process a JSON object
  7586. object_start,
  7587. /// the parser read `}` and finished processing a JSON object
  7588. object_end,
  7589. /// the parser read `[` and started to process a JSON array
  7590. array_start,
  7591. /// the parser read `]` and finished processing a JSON array
  7592. array_end,
  7593. /// the parser read a key of a value in an object
  7594. key,
  7595. /// the parser finished reading a JSON value
  7596. value
  7597. };
  7598. using parser_callback_t =
  7599. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  7600. /// a parser reading from an input adapter
  7601. explicit parser(detail::input_adapter_t&& adapter,
  7602. const parser_callback_t cb = nullptr,
  7603. const bool allow_exceptions_ = true)
  7604. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  7605. {
  7606. // read first token
  7607. get_token();
  7608. }
  7609. /*!
  7610. @brief public parser interface
  7611. @param[in] strict whether to expect the last token to be EOF
  7612. @param[in,out] result parsed JSON value
  7613. @throw parse_error.101 in case of an unexpected token
  7614. @throw parse_error.102 if to_unicode fails or surrogate error
  7615. @throw parse_error.103 if to_unicode fails
  7616. */
  7617. void parse(const bool strict, BasicJsonType& result)
  7618. {
  7619. if (callback)
  7620. {
  7621. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  7622. sax_parse_internal(&sdp);
  7623. result.assert_invariant();
  7624. // in strict mode, input must be completely read
  7625. if (strict and (get_token() != token_type::end_of_input))
  7626. {
  7627. sdp.parse_error(m_lexer.get_position(),
  7628. m_lexer.get_token_string(),
  7629. parse_error::create(101, m_lexer.get_position(),
  7630. exception_message(token_type::end_of_input, "value")));
  7631. }
  7632. // in case of an error, return discarded value
  7633. if (sdp.is_errored())
  7634. {
  7635. result = value_t::discarded;
  7636. return;
  7637. }
  7638. // set top-level value to null if it was discarded by the callback
  7639. // function
  7640. if (result.is_discarded())
  7641. {
  7642. result = nullptr;
  7643. }
  7644. }
  7645. else
  7646. {
  7647. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  7648. sax_parse_internal(&sdp);
  7649. result.assert_invariant();
  7650. // in strict mode, input must be completely read
  7651. if (strict and (get_token() != token_type::end_of_input))
  7652. {
  7653. sdp.parse_error(m_lexer.get_position(),
  7654. m_lexer.get_token_string(),
  7655. parse_error::create(101, m_lexer.get_position(),
  7656. exception_message(token_type::end_of_input, "value")));
  7657. }
  7658. // in case of an error, return discarded value
  7659. if (sdp.is_errored())
  7660. {
  7661. result = value_t::discarded;
  7662. return;
  7663. }
  7664. }
  7665. }
  7666. /*!
  7667. @brief public accept interface
  7668. @param[in] strict whether to expect the last token to be EOF
  7669. @return whether the input is a proper JSON text
  7670. */
  7671. bool accept(const bool strict = true)
  7672. {
  7673. json_sax_acceptor<BasicJsonType> sax_acceptor;
  7674. return sax_parse(&sax_acceptor, strict);
  7675. }
  7676. template <typename SAX>
  7677. JSON_HEDLEY_NON_NULL(2)
  7678. bool sax_parse(SAX* sax, const bool strict = true)
  7679. {
  7680. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7681. const bool result = sax_parse_internal(sax);
  7682. // strict mode: next byte must be EOF
  7683. if (result and strict and (get_token() != token_type::end_of_input))
  7684. {
  7685. return sax->parse_error(m_lexer.get_position(),
  7686. m_lexer.get_token_string(),
  7687. parse_error::create(101, m_lexer.get_position(),
  7688. exception_message(token_type::end_of_input, "value")));
  7689. }
  7690. return result;
  7691. }
  7692. private:
  7693. template <typename SAX>
  7694. JSON_HEDLEY_NON_NULL(2)
  7695. bool sax_parse_internal(SAX* sax)
  7696. {
  7697. // stack to remember the hierarchy of structured values we are parsing
  7698. // true = array; false = object
  7699. std::vector<bool> states;
  7700. // value to avoid a goto (see comment where set to true)
  7701. bool skip_to_state_evaluation = false;
  7702. while (true)
  7703. {
  7704. if (not skip_to_state_evaluation)
  7705. {
  7706. // invariant: get_token() was called before each iteration
  7707. switch (last_token)
  7708. {
  7709. case token_type::begin_object:
  7710. {
  7711. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  7712. {
  7713. return false;
  7714. }
  7715. // closing } -> we are done
  7716. if (get_token() == token_type::end_object)
  7717. {
  7718. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7719. {
  7720. return false;
  7721. }
  7722. break;
  7723. }
  7724. // parse key
  7725. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  7726. {
  7727. return sax->parse_error(m_lexer.get_position(),
  7728. m_lexer.get_token_string(),
  7729. parse_error::create(101, m_lexer.get_position(),
  7730. exception_message(token_type::value_string, "object key")));
  7731. }
  7732. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7733. {
  7734. return false;
  7735. }
  7736. // parse separator (:)
  7737. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7738. {
  7739. return sax->parse_error(m_lexer.get_position(),
  7740. m_lexer.get_token_string(),
  7741. parse_error::create(101, m_lexer.get_position(),
  7742. exception_message(token_type::name_separator, "object separator")));
  7743. }
  7744. // remember we are now inside an object
  7745. states.push_back(false);
  7746. // parse values
  7747. get_token();
  7748. continue;
  7749. }
  7750. case token_type::begin_array:
  7751. {
  7752. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  7753. {
  7754. return false;
  7755. }
  7756. // closing ] -> we are done
  7757. if (get_token() == token_type::end_array)
  7758. {
  7759. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7760. {
  7761. return false;
  7762. }
  7763. break;
  7764. }
  7765. // remember we are now inside an array
  7766. states.push_back(true);
  7767. // parse values (no need to call get_token)
  7768. continue;
  7769. }
  7770. case token_type::value_float:
  7771. {
  7772. const auto res = m_lexer.get_number_float();
  7773. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  7774. {
  7775. return sax->parse_error(m_lexer.get_position(),
  7776. m_lexer.get_token_string(),
  7777. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  7778. }
  7779. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  7780. {
  7781. return false;
  7782. }
  7783. break;
  7784. }
  7785. case token_type::literal_false:
  7786. {
  7787. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  7788. {
  7789. return false;
  7790. }
  7791. break;
  7792. }
  7793. case token_type::literal_null:
  7794. {
  7795. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  7796. {
  7797. return false;
  7798. }
  7799. break;
  7800. }
  7801. case token_type::literal_true:
  7802. {
  7803. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  7804. {
  7805. return false;
  7806. }
  7807. break;
  7808. }
  7809. case token_type::value_integer:
  7810. {
  7811. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  7812. {
  7813. return false;
  7814. }
  7815. break;
  7816. }
  7817. case token_type::value_string:
  7818. {
  7819. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  7820. {
  7821. return false;
  7822. }
  7823. break;
  7824. }
  7825. case token_type::value_unsigned:
  7826. {
  7827. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  7828. {
  7829. return false;
  7830. }
  7831. break;
  7832. }
  7833. case token_type::parse_error:
  7834. {
  7835. // using "uninitialized" to avoid "expected" message
  7836. return sax->parse_error(m_lexer.get_position(),
  7837. m_lexer.get_token_string(),
  7838. parse_error::create(101, m_lexer.get_position(),
  7839. exception_message(token_type::uninitialized, "value")));
  7840. }
  7841. default: // the last token was unexpected
  7842. {
  7843. return sax->parse_error(m_lexer.get_position(),
  7844. m_lexer.get_token_string(),
  7845. parse_error::create(101, m_lexer.get_position(),
  7846. exception_message(token_type::literal_or_value, "value")));
  7847. }
  7848. }
  7849. }
  7850. else
  7851. {
  7852. skip_to_state_evaluation = false;
  7853. }
  7854. // we reached this line after we successfully parsed a value
  7855. if (states.empty())
  7856. {
  7857. // empty stack: we reached the end of the hierarchy: done
  7858. return true;
  7859. }
  7860. if (states.back()) // array
  7861. {
  7862. // comma -> next value
  7863. if (get_token() == token_type::value_separator)
  7864. {
  7865. // parse a new value
  7866. get_token();
  7867. continue;
  7868. }
  7869. // closing ]
  7870. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  7871. {
  7872. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7873. {
  7874. return false;
  7875. }
  7876. // We are done with this array. Before we can parse a
  7877. // new value, we need to evaluate the new state first.
  7878. // By setting skip_to_state_evaluation to false, we
  7879. // are effectively jumping to the beginning of this if.
  7880. assert(not states.empty());
  7881. states.pop_back();
  7882. skip_to_state_evaluation = true;
  7883. continue;
  7884. }
  7885. return sax->parse_error(m_lexer.get_position(),
  7886. m_lexer.get_token_string(),
  7887. parse_error::create(101, m_lexer.get_position(),
  7888. exception_message(token_type::end_array, "array")));
  7889. }
  7890. else // object
  7891. {
  7892. // comma -> next value
  7893. if (get_token() == token_type::value_separator)
  7894. {
  7895. // parse key
  7896. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  7897. {
  7898. return sax->parse_error(m_lexer.get_position(),
  7899. m_lexer.get_token_string(),
  7900. parse_error::create(101, m_lexer.get_position(),
  7901. exception_message(token_type::value_string, "object key")));
  7902. }
  7903. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7904. {
  7905. return false;
  7906. }
  7907. // parse separator (:)
  7908. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7909. {
  7910. return sax->parse_error(m_lexer.get_position(),
  7911. m_lexer.get_token_string(),
  7912. parse_error::create(101, m_lexer.get_position(),
  7913. exception_message(token_type::name_separator, "object separator")));
  7914. }
  7915. // parse values
  7916. get_token();
  7917. continue;
  7918. }
  7919. // closing }
  7920. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  7921. {
  7922. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7923. {
  7924. return false;
  7925. }
  7926. // We are done with this object. Before we can parse a
  7927. // new value, we need to evaluate the new state first.
  7928. // By setting skip_to_state_evaluation to false, we
  7929. // are effectively jumping to the beginning of this if.
  7930. assert(not states.empty());
  7931. states.pop_back();
  7932. skip_to_state_evaluation = true;
  7933. continue;
  7934. }
  7935. return sax->parse_error(m_lexer.get_position(),
  7936. m_lexer.get_token_string(),
  7937. parse_error::create(101, m_lexer.get_position(),
  7938. exception_message(token_type::end_object, "object")));
  7939. }
  7940. }
  7941. }
  7942. /// get next token from lexer
  7943. token_type get_token()
  7944. {
  7945. return last_token = m_lexer.scan();
  7946. }
  7947. std::string exception_message(const token_type expected, const std::string& context)
  7948. {
  7949. std::string error_msg = "syntax error ";
  7950. if (not context.empty())
  7951. {
  7952. error_msg += "while parsing " + context + " ";
  7953. }
  7954. error_msg += "- ";
  7955. if (last_token == token_type::parse_error)
  7956. {
  7957. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  7958. m_lexer.get_token_string() + "'";
  7959. }
  7960. else
  7961. {
  7962. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  7963. }
  7964. if (expected != token_type::uninitialized)
  7965. {
  7966. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  7967. }
  7968. return error_msg;
  7969. }
  7970. private:
  7971. /// callback function
  7972. const parser_callback_t callback = nullptr;
  7973. /// the type of the last read token
  7974. token_type last_token = token_type::uninitialized;
  7975. /// the lexer
  7976. lexer_t m_lexer;
  7977. /// whether to throw exceptions in case of errors
  7978. const bool allow_exceptions = true;
  7979. };
  7980. } // namespace detail
  7981. } // namespace nlohmann
  7982. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  7983. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  7984. #include <cstddef> // ptrdiff_t
  7985. #include <limits> // numeric_limits
  7986. namespace nlohmann
  7987. {
  7988. namespace detail
  7989. {
  7990. /*
  7991. @brief an iterator for primitive JSON types
  7992. This class models an iterator for primitive JSON types (boolean, number,
  7993. string). It's only purpose is to allow the iterator/const_iterator classes
  7994. to "iterate" over primitive values. Internally, the iterator is modeled by
  7995. a `difference_type` variable. Value begin_value (`0`) models the begin,
  7996. end_value (`1`) models past the end.
  7997. */
  7998. class primitive_iterator_t
  7999. {
  8000. private:
  8001. using difference_type = std::ptrdiff_t;
  8002. static constexpr difference_type begin_value = 0;
  8003. static constexpr difference_type end_value = begin_value + 1;
  8004. /// iterator as signed integer type
  8005. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  8006. public:
  8007. constexpr difference_type get_value() const noexcept
  8008. {
  8009. return m_it;
  8010. }
  8011. /// set iterator to a defined beginning
  8012. void set_begin() noexcept
  8013. {
  8014. m_it = begin_value;
  8015. }
  8016. /// set iterator to a defined past the end
  8017. void set_end() noexcept
  8018. {
  8019. m_it = end_value;
  8020. }
  8021. /// return whether the iterator can be dereferenced
  8022. constexpr bool is_begin() const noexcept
  8023. {
  8024. return m_it == begin_value;
  8025. }
  8026. /// return whether the iterator is at end
  8027. constexpr bool is_end() const noexcept
  8028. {
  8029. return m_it == end_value;
  8030. }
  8031. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8032. {
  8033. return lhs.m_it == rhs.m_it;
  8034. }
  8035. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8036. {
  8037. return lhs.m_it < rhs.m_it;
  8038. }
  8039. primitive_iterator_t operator+(difference_type n) noexcept
  8040. {
  8041. auto result = *this;
  8042. result += n;
  8043. return result;
  8044. }
  8045. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8046. {
  8047. return lhs.m_it - rhs.m_it;
  8048. }
  8049. primitive_iterator_t& operator++() noexcept
  8050. {
  8051. ++m_it;
  8052. return *this;
  8053. }
  8054. primitive_iterator_t const operator++(int) noexcept
  8055. {
  8056. auto result = *this;
  8057. ++m_it;
  8058. return result;
  8059. }
  8060. primitive_iterator_t& operator--() noexcept
  8061. {
  8062. --m_it;
  8063. return *this;
  8064. }
  8065. primitive_iterator_t const operator--(int) noexcept
  8066. {
  8067. auto result = *this;
  8068. --m_it;
  8069. return result;
  8070. }
  8071. primitive_iterator_t& operator+=(difference_type n) noexcept
  8072. {
  8073. m_it += n;
  8074. return *this;
  8075. }
  8076. primitive_iterator_t& operator-=(difference_type n) noexcept
  8077. {
  8078. m_it -= n;
  8079. return *this;
  8080. }
  8081. };
  8082. } // namespace detail
  8083. } // namespace nlohmann
  8084. namespace nlohmann
  8085. {
  8086. namespace detail
  8087. {
  8088. /*!
  8089. @brief an iterator value
  8090. @note This structure could easily be a union, but MSVC currently does not allow
  8091. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  8092. */
  8093. template<typename BasicJsonType> struct internal_iterator
  8094. {
  8095. /// iterator for JSON objects
  8096. typename BasicJsonType::object_t::iterator object_iterator {};
  8097. /// iterator for JSON arrays
  8098. typename BasicJsonType::array_t::iterator array_iterator {};
  8099. /// generic iterator for all other types
  8100. primitive_iterator_t primitive_iterator {};
  8101. };
  8102. } // namespace detail
  8103. } // namespace nlohmann
  8104. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8105. #include <ciso646> // not
  8106. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8107. #include <type_traits> // conditional, is_const, remove_const
  8108. // #include <nlohmann/detail/exceptions.hpp>
  8109. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8110. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8111. // #include <nlohmann/detail/macro_scope.hpp>
  8112. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8113. // #include <nlohmann/detail/meta/type_traits.hpp>
  8114. // #include <nlohmann/detail/value_t.hpp>
  8115. namespace nlohmann
  8116. {
  8117. namespace detail
  8118. {
  8119. // forward declare, to be able to friend it later on
  8120. template<typename IteratorType> class iteration_proxy;
  8121. template<typename IteratorType> class iteration_proxy_value;
  8122. /*!
  8123. @brief a template for a bidirectional iterator for the @ref basic_json class
  8124. This class implements a both iterators (iterator and const_iterator) for the
  8125. @ref basic_json class.
  8126. @note An iterator is called *initialized* when a pointer to a JSON value has
  8127. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8128. default-constructed, it is *uninitialized* and most methods are undefined.
  8129. **The library uses assertions to detect calls on uninitialized iterators.**
  8130. @requirement The class satisfies the following concept requirements:
  8131. -
  8132. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8133. The iterator that can be moved can be moved in both directions (i.e.
  8134. incremented and decremented).
  8135. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8136. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8137. */
  8138. template<typename BasicJsonType>
  8139. class iter_impl
  8140. {
  8141. /// allow basic_json to access private members
  8142. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8143. friend BasicJsonType;
  8144. friend iteration_proxy<iter_impl>;
  8145. friend iteration_proxy_value<iter_impl>;
  8146. using object_t = typename BasicJsonType::object_t;
  8147. using array_t = typename BasicJsonType::array_t;
  8148. // make sure BasicJsonType is basic_json or const basic_json
  8149. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  8150. "iter_impl only accepts (const) basic_json");
  8151. public:
  8152. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  8153. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  8154. /// A user-defined iterator should provide publicly accessible typedefs named
  8155. /// iterator_category, value_type, difference_type, pointer, and reference.
  8156. /// Note that value_type is required to be non-const, even for constant iterators.
  8157. using iterator_category = std::bidirectional_iterator_tag;
  8158. /// the type of the values when the iterator is dereferenced
  8159. using value_type = typename BasicJsonType::value_type;
  8160. /// a type to represent differences between iterators
  8161. using difference_type = typename BasicJsonType::difference_type;
  8162. /// defines a pointer to the type iterated over (value_type)
  8163. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  8164. typename BasicJsonType::const_pointer,
  8165. typename BasicJsonType::pointer>::type;
  8166. /// defines a reference to the type iterated over (value_type)
  8167. using reference =
  8168. typename std::conditional<std::is_const<BasicJsonType>::value,
  8169. typename BasicJsonType::const_reference,
  8170. typename BasicJsonType::reference>::type;
  8171. /// default constructor
  8172. iter_impl() = default;
  8173. /*!
  8174. @brief constructor for a given JSON instance
  8175. @param[in] object pointer to a JSON object for this iterator
  8176. @pre object != nullptr
  8177. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8178. */
  8179. explicit iter_impl(pointer object) noexcept : m_object(object)
  8180. {
  8181. assert(m_object != nullptr);
  8182. switch (m_object->m_type)
  8183. {
  8184. case value_t::object:
  8185. {
  8186. m_it.object_iterator = typename object_t::iterator();
  8187. break;
  8188. }
  8189. case value_t::array:
  8190. {
  8191. m_it.array_iterator = typename array_t::iterator();
  8192. break;
  8193. }
  8194. default:
  8195. {
  8196. m_it.primitive_iterator = primitive_iterator_t();
  8197. break;
  8198. }
  8199. }
  8200. }
  8201. /*!
  8202. @note The conventional copy constructor and copy assignment are implicitly
  8203. defined. Combined with the following converting constructor and
  8204. assignment, they support: (1) copy from iterator to iterator, (2)
  8205. copy from const iterator to const iterator, and (3) conversion from
  8206. iterator to const iterator. However conversion from const iterator
  8207. to iterator is not defined.
  8208. */
  8209. /*!
  8210. @brief const copy constructor
  8211. @param[in] other const iterator to copy from
  8212. @note This copy constructor had to be defined explicitly to circumvent a bug
  8213. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  8214. information refer to: https://github.com/nlohmann/json/issues/1608
  8215. */
  8216. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  8217. : m_object(other.m_object), m_it(other.m_it)
  8218. {}
  8219. /*!
  8220. @brief converting assignment
  8221. @param[in] other const iterator to copy from
  8222. @return const/non-const iterator
  8223. @note It is not checked whether @a other is initialized.
  8224. */
  8225. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  8226. {
  8227. m_object = other.m_object;
  8228. m_it = other.m_it;
  8229. return *this;
  8230. }
  8231. /*!
  8232. @brief converting constructor
  8233. @param[in] other non-const iterator to copy from
  8234. @note It is not checked whether @a other is initialized.
  8235. */
  8236. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8237. : m_object(other.m_object), m_it(other.m_it)
  8238. {}
  8239. /*!
  8240. @brief converting assignment
  8241. @param[in] other non-const iterator to copy from
  8242. @return const/non-const iterator
  8243. @note It is not checked whether @a other is initialized.
  8244. */
  8245. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8246. {
  8247. m_object = other.m_object;
  8248. m_it = other.m_it;
  8249. return *this;
  8250. }
  8251. private:
  8252. /*!
  8253. @brief set the iterator to the first value
  8254. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8255. */
  8256. void set_begin() noexcept
  8257. {
  8258. assert(m_object != nullptr);
  8259. switch (m_object->m_type)
  8260. {
  8261. case value_t::object:
  8262. {
  8263. m_it.object_iterator = m_object->m_value.object->begin();
  8264. break;
  8265. }
  8266. case value_t::array:
  8267. {
  8268. m_it.array_iterator = m_object->m_value.array->begin();
  8269. break;
  8270. }
  8271. case value_t::null:
  8272. {
  8273. // set to end so begin()==end() is true: null is empty
  8274. m_it.primitive_iterator.set_end();
  8275. break;
  8276. }
  8277. default:
  8278. {
  8279. m_it.primitive_iterator.set_begin();
  8280. break;
  8281. }
  8282. }
  8283. }
  8284. /*!
  8285. @brief set the iterator past the last value
  8286. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8287. */
  8288. void set_end() noexcept
  8289. {
  8290. assert(m_object != nullptr);
  8291. switch (m_object->m_type)
  8292. {
  8293. case value_t::object:
  8294. {
  8295. m_it.object_iterator = m_object->m_value.object->end();
  8296. break;
  8297. }
  8298. case value_t::array:
  8299. {
  8300. m_it.array_iterator = m_object->m_value.array->end();
  8301. break;
  8302. }
  8303. default:
  8304. {
  8305. m_it.primitive_iterator.set_end();
  8306. break;
  8307. }
  8308. }
  8309. }
  8310. public:
  8311. /*!
  8312. @brief return a reference to the value pointed to by the iterator
  8313. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8314. */
  8315. reference operator*() const
  8316. {
  8317. assert(m_object != nullptr);
  8318. switch (m_object->m_type)
  8319. {
  8320. case value_t::object:
  8321. {
  8322. assert(m_it.object_iterator != m_object->m_value.object->end());
  8323. return m_it.object_iterator->second;
  8324. }
  8325. case value_t::array:
  8326. {
  8327. assert(m_it.array_iterator != m_object->m_value.array->end());
  8328. return *m_it.array_iterator;
  8329. }
  8330. case value_t::null:
  8331. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8332. default:
  8333. {
  8334. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8335. {
  8336. return *m_object;
  8337. }
  8338. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8339. }
  8340. }
  8341. }
  8342. /*!
  8343. @brief dereference the iterator
  8344. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8345. */
  8346. pointer operator->() const
  8347. {
  8348. assert(m_object != nullptr);
  8349. switch (m_object->m_type)
  8350. {
  8351. case value_t::object:
  8352. {
  8353. assert(m_it.object_iterator != m_object->m_value.object->end());
  8354. return &(m_it.object_iterator->second);
  8355. }
  8356. case value_t::array:
  8357. {
  8358. assert(m_it.array_iterator != m_object->m_value.array->end());
  8359. return &*m_it.array_iterator;
  8360. }
  8361. default:
  8362. {
  8363. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8364. {
  8365. return m_object;
  8366. }
  8367. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8368. }
  8369. }
  8370. }
  8371. /*!
  8372. @brief post-increment (it++)
  8373. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8374. */
  8375. iter_impl const operator++(int)
  8376. {
  8377. auto result = *this;
  8378. ++(*this);
  8379. return result;
  8380. }
  8381. /*!
  8382. @brief pre-increment (++it)
  8383. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8384. */
  8385. iter_impl& operator++()
  8386. {
  8387. assert(m_object != nullptr);
  8388. switch (m_object->m_type)
  8389. {
  8390. case value_t::object:
  8391. {
  8392. std::advance(m_it.object_iterator, 1);
  8393. break;
  8394. }
  8395. case value_t::array:
  8396. {
  8397. std::advance(m_it.array_iterator, 1);
  8398. break;
  8399. }
  8400. default:
  8401. {
  8402. ++m_it.primitive_iterator;
  8403. break;
  8404. }
  8405. }
  8406. return *this;
  8407. }
  8408. /*!
  8409. @brief post-decrement (it--)
  8410. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8411. */
  8412. iter_impl const operator--(int)
  8413. {
  8414. auto result = *this;
  8415. --(*this);
  8416. return result;
  8417. }
  8418. /*!
  8419. @brief pre-decrement (--it)
  8420. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8421. */
  8422. iter_impl& operator--()
  8423. {
  8424. assert(m_object != nullptr);
  8425. switch (m_object->m_type)
  8426. {
  8427. case value_t::object:
  8428. {
  8429. std::advance(m_it.object_iterator, -1);
  8430. break;
  8431. }
  8432. case value_t::array:
  8433. {
  8434. std::advance(m_it.array_iterator, -1);
  8435. break;
  8436. }
  8437. default:
  8438. {
  8439. --m_it.primitive_iterator;
  8440. break;
  8441. }
  8442. }
  8443. return *this;
  8444. }
  8445. /*!
  8446. @brief comparison: equal
  8447. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8448. */
  8449. bool operator==(const iter_impl& other) const
  8450. {
  8451. // if objects are not the same, the comparison is undefined
  8452. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8453. {
  8454. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8455. }
  8456. assert(m_object != nullptr);
  8457. switch (m_object->m_type)
  8458. {
  8459. case value_t::object:
  8460. return (m_it.object_iterator == other.m_it.object_iterator);
  8461. case value_t::array:
  8462. return (m_it.array_iterator == other.m_it.array_iterator);
  8463. default:
  8464. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  8465. }
  8466. }
  8467. /*!
  8468. @brief comparison: not equal
  8469. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8470. */
  8471. bool operator!=(const iter_impl& other) const
  8472. {
  8473. return not operator==(other);
  8474. }
  8475. /*!
  8476. @brief comparison: smaller
  8477. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8478. */
  8479. bool operator<(const iter_impl& other) const
  8480. {
  8481. // if objects are not the same, the comparison is undefined
  8482. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8483. {
  8484. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8485. }
  8486. assert(m_object != nullptr);
  8487. switch (m_object->m_type)
  8488. {
  8489. case value_t::object:
  8490. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  8491. case value_t::array:
  8492. return (m_it.array_iterator < other.m_it.array_iterator);
  8493. default:
  8494. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  8495. }
  8496. }
  8497. /*!
  8498. @brief comparison: less than or equal
  8499. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8500. */
  8501. bool operator<=(const iter_impl& other) const
  8502. {
  8503. return not other.operator < (*this);
  8504. }
  8505. /*!
  8506. @brief comparison: greater than
  8507. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8508. */
  8509. bool operator>(const iter_impl& other) const
  8510. {
  8511. return not operator<=(other);
  8512. }
  8513. /*!
  8514. @brief comparison: greater than or equal
  8515. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8516. */
  8517. bool operator>=(const iter_impl& other) const
  8518. {
  8519. return not operator<(other);
  8520. }
  8521. /*!
  8522. @brief add to iterator
  8523. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8524. */
  8525. iter_impl& operator+=(difference_type i)
  8526. {
  8527. assert(m_object != nullptr);
  8528. switch (m_object->m_type)
  8529. {
  8530. case value_t::object:
  8531. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8532. case value_t::array:
  8533. {
  8534. std::advance(m_it.array_iterator, i);
  8535. break;
  8536. }
  8537. default:
  8538. {
  8539. m_it.primitive_iterator += i;
  8540. break;
  8541. }
  8542. }
  8543. return *this;
  8544. }
  8545. /*!
  8546. @brief subtract from iterator
  8547. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8548. */
  8549. iter_impl& operator-=(difference_type i)
  8550. {
  8551. return operator+=(-i);
  8552. }
  8553. /*!
  8554. @brief add to iterator
  8555. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8556. */
  8557. iter_impl operator+(difference_type i) const
  8558. {
  8559. auto result = *this;
  8560. result += i;
  8561. return result;
  8562. }
  8563. /*!
  8564. @brief addition of distance and iterator
  8565. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8566. */
  8567. friend iter_impl operator+(difference_type i, const iter_impl& it)
  8568. {
  8569. auto result = it;
  8570. result += i;
  8571. return result;
  8572. }
  8573. /*!
  8574. @brief subtract from iterator
  8575. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8576. */
  8577. iter_impl operator-(difference_type i) const
  8578. {
  8579. auto result = *this;
  8580. result -= i;
  8581. return result;
  8582. }
  8583. /*!
  8584. @brief return difference
  8585. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8586. */
  8587. difference_type operator-(const iter_impl& other) const
  8588. {
  8589. assert(m_object != nullptr);
  8590. switch (m_object->m_type)
  8591. {
  8592. case value_t::object:
  8593. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8594. case value_t::array:
  8595. return m_it.array_iterator - other.m_it.array_iterator;
  8596. default:
  8597. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  8598. }
  8599. }
  8600. /*!
  8601. @brief access to successor
  8602. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8603. */
  8604. reference operator[](difference_type n) const
  8605. {
  8606. assert(m_object != nullptr);
  8607. switch (m_object->m_type)
  8608. {
  8609. case value_t::object:
  8610. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  8611. case value_t::array:
  8612. return *std::next(m_it.array_iterator, n);
  8613. case value_t::null:
  8614. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8615. default:
  8616. {
  8617. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  8618. {
  8619. return *m_object;
  8620. }
  8621. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8622. }
  8623. }
  8624. }
  8625. /*!
  8626. @brief return the key of an object iterator
  8627. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8628. */
  8629. const typename object_t::key_type& key() const
  8630. {
  8631. assert(m_object != nullptr);
  8632. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  8633. {
  8634. return m_it.object_iterator->first;
  8635. }
  8636. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  8637. }
  8638. /*!
  8639. @brief return the value of an iterator
  8640. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8641. */
  8642. reference value() const
  8643. {
  8644. return operator*();
  8645. }
  8646. private:
  8647. /// associated JSON instance
  8648. pointer m_object = nullptr;
  8649. /// the actual iterator of the associated instance
  8650. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  8651. };
  8652. } // namespace detail
  8653. } // namespace nlohmann
  8654. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  8655. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  8656. #include <cstddef> // ptrdiff_t
  8657. #include <iterator> // reverse_iterator
  8658. #include <utility> // declval
  8659. namespace nlohmann
  8660. {
  8661. namespace detail
  8662. {
  8663. //////////////////////
  8664. // reverse_iterator //
  8665. //////////////////////
  8666. /*!
  8667. @brief a template for a reverse iterator class
  8668. @tparam Base the base iterator type to reverse. Valid types are @ref
  8669. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  8670. create @ref const_reverse_iterator).
  8671. @requirement The class satisfies the following concept requirements:
  8672. -
  8673. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8674. The iterator that can be moved can be moved in both directions (i.e.
  8675. incremented and decremented).
  8676. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  8677. It is possible to write to the pointed-to element (only if @a Base is
  8678. @ref iterator).
  8679. @since version 1.0.0
  8680. */
  8681. template<typename Base>
  8682. class json_reverse_iterator : public std::reverse_iterator<Base>
  8683. {
  8684. public:
  8685. using difference_type = std::ptrdiff_t;
  8686. /// shortcut to the reverse iterator adapter
  8687. using base_iterator = std::reverse_iterator<Base>;
  8688. /// the reference type for the pointed-to element
  8689. using reference = typename Base::reference;
  8690. /// create reverse iterator from iterator
  8691. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  8692. : base_iterator(it) {}
  8693. /// create reverse iterator from base class
  8694. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  8695. /// post-increment (it++)
  8696. json_reverse_iterator const operator++(int)
  8697. {
  8698. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  8699. }
  8700. /// pre-increment (++it)
  8701. json_reverse_iterator& operator++()
  8702. {
  8703. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  8704. }
  8705. /// post-decrement (it--)
  8706. json_reverse_iterator const operator--(int)
  8707. {
  8708. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  8709. }
  8710. /// pre-decrement (--it)
  8711. json_reverse_iterator& operator--()
  8712. {
  8713. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  8714. }
  8715. /// add to iterator
  8716. json_reverse_iterator& operator+=(difference_type i)
  8717. {
  8718. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  8719. }
  8720. /// add to iterator
  8721. json_reverse_iterator operator+(difference_type i) const
  8722. {
  8723. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  8724. }
  8725. /// subtract from iterator
  8726. json_reverse_iterator operator-(difference_type i) const
  8727. {
  8728. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  8729. }
  8730. /// return difference
  8731. difference_type operator-(const json_reverse_iterator& other) const
  8732. {
  8733. return base_iterator(*this) - base_iterator(other);
  8734. }
  8735. /// access to successor
  8736. reference operator[](difference_type n) const
  8737. {
  8738. return *(this->operator+(n));
  8739. }
  8740. /// return the key of an object iterator
  8741. auto key() const -> decltype(std::declval<Base>().key())
  8742. {
  8743. auto it = --this->base();
  8744. return it.key();
  8745. }
  8746. /// return the value of an iterator
  8747. reference value() const
  8748. {
  8749. auto it = --this->base();
  8750. return it.operator * ();
  8751. }
  8752. };
  8753. } // namespace detail
  8754. } // namespace nlohmann
  8755. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8756. // #include <nlohmann/detail/json_pointer.hpp>
  8757. #include <algorithm> // all_of
  8758. #include <cassert> // assert
  8759. #include <cctype> // isdigit
  8760. #include <numeric> // accumulate
  8761. #include <string> // string
  8762. #include <utility> // move
  8763. #include <vector> // vector
  8764. // #include <nlohmann/detail/exceptions.hpp>
  8765. // #include <nlohmann/detail/macro_scope.hpp>
  8766. // #include <nlohmann/detail/value_t.hpp>
  8767. namespace nlohmann
  8768. {
  8769. template<typename BasicJsonType>
  8770. class json_pointer
  8771. {
  8772. // allow basic_json to access private members
  8773. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  8774. friend class basic_json;
  8775. public:
  8776. /*!
  8777. @brief create JSON pointer
  8778. Create a JSON pointer according to the syntax described in
  8779. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  8780. @param[in] s string representing the JSON pointer; if omitted, the empty
  8781. string is assumed which references the whole JSON value
  8782. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  8783. not begin with a slash (`/`); see example below
  8784. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  8785. not followed by `0` (representing `~`) or `1` (representing `/`); see
  8786. example below
  8787. @liveexample{The example shows the construction several valid JSON pointers
  8788. as well as the exceptional behavior.,json_pointer}
  8789. @since version 2.0.0
  8790. */
  8791. explicit json_pointer(const std::string& s = "")
  8792. : reference_tokens(split(s))
  8793. {}
  8794. /*!
  8795. @brief return a string representation of the JSON pointer
  8796. @invariant For each JSON pointer `ptr`, it holds:
  8797. @code {.cpp}
  8798. ptr == json_pointer(ptr.to_string());
  8799. @endcode
  8800. @return a string representation of the JSON pointer
  8801. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  8802. @since version 2.0.0
  8803. */
  8804. std::string to_string() const
  8805. {
  8806. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  8807. std::string{},
  8808. [](const std::string & a, const std::string & b)
  8809. {
  8810. return a + "/" + escape(b);
  8811. });
  8812. }
  8813. /// @copydoc to_string()
  8814. operator std::string() const
  8815. {
  8816. return to_string();
  8817. }
  8818. /*!
  8819. @brief append another JSON pointer at the end of this JSON pointer
  8820. @param[in] ptr JSON pointer to append
  8821. @return JSON pointer with @a ptr appended
  8822. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8823. @complexity Linear in the length of @a ptr.
  8824. @sa @ref operator/=(std::string) to append a reference token
  8825. @sa @ref operator/=(std::size_t) to append an array index
  8826. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  8827. @since version 3.6.0
  8828. */
  8829. json_pointer& operator/=(const json_pointer& ptr)
  8830. {
  8831. reference_tokens.insert(reference_tokens.end(),
  8832. ptr.reference_tokens.begin(),
  8833. ptr.reference_tokens.end());
  8834. return *this;
  8835. }
  8836. /*!
  8837. @brief append an unescaped reference token at the end of this JSON pointer
  8838. @param[in] token reference token to append
  8839. @return JSON pointer with @a token appended without escaping @a token
  8840. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8841. @complexity Amortized constant.
  8842. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8843. @sa @ref operator/=(std::size_t) to append an array index
  8844. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  8845. @since version 3.6.0
  8846. */
  8847. json_pointer& operator/=(std::string token)
  8848. {
  8849. push_back(std::move(token));
  8850. return *this;
  8851. }
  8852. /*!
  8853. @brief append an array index at the end of this JSON pointer
  8854. @param[in] array_index array index to append
  8855. @return JSON pointer with @a array_index appended
  8856. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8857. @complexity Amortized constant.
  8858. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8859. @sa @ref operator/=(std::string) to append a reference token
  8860. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  8861. @since version 3.6.0
  8862. */
  8863. json_pointer& operator/=(std::size_t array_index)
  8864. {
  8865. return *this /= std::to_string(array_index);
  8866. }
  8867. /*!
  8868. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  8869. @param[in] lhs JSON pointer
  8870. @param[in] rhs JSON pointer
  8871. @return a new JSON pointer with @a rhs appended to @a lhs
  8872. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8873. @complexity Linear in the length of @a lhs and @a rhs.
  8874. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8875. @since version 3.6.0
  8876. */
  8877. friend json_pointer operator/(const json_pointer& lhs,
  8878. const json_pointer& rhs)
  8879. {
  8880. return json_pointer(lhs) /= rhs;
  8881. }
  8882. /*!
  8883. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  8884. @param[in] ptr JSON pointer
  8885. @param[in] token reference token
  8886. @return a new JSON pointer with unescaped @a token appended to @a ptr
  8887. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8888. @complexity Linear in the length of @a ptr.
  8889. @sa @ref operator/=(std::string) to append a reference token
  8890. @since version 3.6.0
  8891. */
  8892. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  8893. {
  8894. return json_pointer(ptr) /= std::move(token);
  8895. }
  8896. /*!
  8897. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  8898. @param[in] ptr JSON pointer
  8899. @param[in] array_index array index
  8900. @return a new JSON pointer with @a array_index appended to @a ptr
  8901. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8902. @complexity Linear in the length of @a ptr.
  8903. @sa @ref operator/=(std::size_t) to append an array index
  8904. @since version 3.6.0
  8905. */
  8906. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
  8907. {
  8908. return json_pointer(ptr) /= array_index;
  8909. }
  8910. /*!
  8911. @brief returns the parent of this JSON pointer
  8912. @return parent of this JSON pointer; in case this JSON pointer is the root,
  8913. the root itself is returned
  8914. @complexity Linear in the length of the JSON pointer.
  8915. @liveexample{The example shows the result of `parent_pointer` for different
  8916. JSON Pointers.,json_pointer__parent_pointer}
  8917. @since version 3.6.0
  8918. */
  8919. json_pointer parent_pointer() const
  8920. {
  8921. if (empty())
  8922. {
  8923. return *this;
  8924. }
  8925. json_pointer res = *this;
  8926. res.pop_back();
  8927. return res;
  8928. }
  8929. /*!
  8930. @brief remove last reference token
  8931. @pre not `empty()`
  8932. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  8933. @complexity Constant.
  8934. @throw out_of_range.405 if JSON pointer has no parent
  8935. @since version 3.6.0
  8936. */
  8937. void pop_back()
  8938. {
  8939. if (JSON_HEDLEY_UNLIKELY(empty()))
  8940. {
  8941. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8942. }
  8943. reference_tokens.pop_back();
  8944. }
  8945. /*!
  8946. @brief return last reference token
  8947. @pre not `empty()`
  8948. @return last reference token
  8949. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  8950. @complexity Constant.
  8951. @throw out_of_range.405 if JSON pointer has no parent
  8952. @since version 3.6.0
  8953. */
  8954. const std::string& back() const
  8955. {
  8956. if (JSON_HEDLEY_UNLIKELY(empty()))
  8957. {
  8958. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8959. }
  8960. return reference_tokens.back();
  8961. }
  8962. /*!
  8963. @brief append an unescaped token at the end of the reference pointer
  8964. @param[in] token token to add
  8965. @complexity Amortized constant.
  8966. @liveexample{The example shows the result of `push_back` for different
  8967. JSON Pointers.,json_pointer__push_back}
  8968. @since version 3.6.0
  8969. */
  8970. void push_back(const std::string& token)
  8971. {
  8972. reference_tokens.push_back(token);
  8973. }
  8974. /// @copydoc push_back(const std::string&)
  8975. void push_back(std::string&& token)
  8976. {
  8977. reference_tokens.push_back(std::move(token));
  8978. }
  8979. /*!
  8980. @brief return whether pointer points to the root document
  8981. @return true iff the JSON pointer points to the root document
  8982. @complexity Constant.
  8983. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  8984. @liveexample{The example shows the result of `empty` for different JSON
  8985. Pointers.,json_pointer__empty}
  8986. @since version 3.6.0
  8987. */
  8988. bool empty() const noexcept
  8989. {
  8990. return reference_tokens.empty();
  8991. }
  8992. private:
  8993. /*!
  8994. @param[in] s reference token to be converted into an array index
  8995. @return integer representation of @a s
  8996. @throw out_of_range.404 if string @a s could not be converted to an integer
  8997. */
  8998. static int array_index(const std::string& s)
  8999. {
  9000. std::size_t processed_chars = 0;
  9001. const int res = std::stoi(s, &processed_chars);
  9002. // check if the string was completely read
  9003. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  9004. {
  9005. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9006. }
  9007. return res;
  9008. }
  9009. json_pointer top() const
  9010. {
  9011. if (JSON_HEDLEY_UNLIKELY(empty()))
  9012. {
  9013. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9014. }
  9015. json_pointer result = *this;
  9016. result.reference_tokens = {reference_tokens[0]};
  9017. return result;
  9018. }
  9019. /*!
  9020. @brief create and return a reference to the pointed to value
  9021. @complexity Linear in the number of reference tokens.
  9022. @throw parse_error.109 if array index is not a number
  9023. @throw type_error.313 if value cannot be unflattened
  9024. */
  9025. BasicJsonType& get_and_create(BasicJsonType& j) const
  9026. {
  9027. using size_type = typename BasicJsonType::size_type;
  9028. auto result = &j;
  9029. // in case no reference tokens exist, return a reference to the JSON value
  9030. // j which will be overwritten by a primitive value
  9031. for (const auto& reference_token : reference_tokens)
  9032. {
  9033. switch (result->type())
  9034. {
  9035. case detail::value_t::null:
  9036. {
  9037. if (reference_token == "0")
  9038. {
  9039. // start a new array if reference token is 0
  9040. result = &result->operator[](0);
  9041. }
  9042. else
  9043. {
  9044. // start a new object otherwise
  9045. result = &result->operator[](reference_token);
  9046. }
  9047. break;
  9048. }
  9049. case detail::value_t::object:
  9050. {
  9051. // create an entry in the object
  9052. result = &result->operator[](reference_token);
  9053. break;
  9054. }
  9055. case detail::value_t::array:
  9056. {
  9057. // create an entry in the array
  9058. JSON_TRY
  9059. {
  9060. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  9061. }
  9062. JSON_CATCH(std::invalid_argument&)
  9063. {
  9064. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9065. }
  9066. break;
  9067. }
  9068. /*
  9069. The following code is only reached if there exists a reference
  9070. token _and_ the current value is primitive. In this case, we have
  9071. an error situation, because primitive values may only occur as
  9072. single value; that is, with an empty list of reference tokens.
  9073. */
  9074. default:
  9075. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  9076. }
  9077. }
  9078. return *result;
  9079. }
  9080. /*!
  9081. @brief return a reference to the pointed to value
  9082. @note This version does not throw if a value is not present, but tries to
  9083. create nested values instead. For instance, calling this function
  9084. with pointer `"/this/that"` on a null value is equivalent to calling
  9085. `operator[]("this").operator[]("that")` on that value, effectively
  9086. changing the null value to an object.
  9087. @param[in] ptr a JSON value
  9088. @return reference to the JSON value pointed to by the JSON pointer
  9089. @complexity Linear in the length of the JSON pointer.
  9090. @throw parse_error.106 if an array index begins with '0'
  9091. @throw parse_error.109 if an array index was not a number
  9092. @throw out_of_range.404 if the JSON pointer can not be resolved
  9093. */
  9094. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  9095. {
  9096. using size_type = typename BasicJsonType::size_type;
  9097. for (const auto& reference_token : reference_tokens)
  9098. {
  9099. // convert null values to arrays or objects before continuing
  9100. if (ptr->is_null())
  9101. {
  9102. // check if reference token is a number
  9103. const bool nums =
  9104. std::all_of(reference_token.begin(), reference_token.end(),
  9105. [](const unsigned char x)
  9106. {
  9107. return std::isdigit(x);
  9108. });
  9109. // change value to array for numbers or "-" or to object otherwise
  9110. *ptr = (nums or reference_token == "-")
  9111. ? detail::value_t::array
  9112. : detail::value_t::object;
  9113. }
  9114. switch (ptr->type())
  9115. {
  9116. case detail::value_t::object:
  9117. {
  9118. // use unchecked object access
  9119. ptr = &ptr->operator[](reference_token);
  9120. break;
  9121. }
  9122. case detail::value_t::array:
  9123. {
  9124. // error condition (cf. RFC 6901, Sect. 4)
  9125. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9126. {
  9127. JSON_THROW(detail::parse_error::create(106, 0,
  9128. "array index '" + reference_token +
  9129. "' must not begin with '0'"));
  9130. }
  9131. if (reference_token == "-")
  9132. {
  9133. // explicitly treat "-" as index beyond the end
  9134. ptr = &ptr->operator[](ptr->m_value.array->size());
  9135. }
  9136. else
  9137. {
  9138. // convert array index to number; unchecked access
  9139. JSON_TRY
  9140. {
  9141. ptr = &ptr->operator[](
  9142. static_cast<size_type>(array_index(reference_token)));
  9143. }
  9144. JSON_CATCH(std::invalid_argument&)
  9145. {
  9146. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9147. }
  9148. }
  9149. break;
  9150. }
  9151. default:
  9152. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9153. }
  9154. }
  9155. return *ptr;
  9156. }
  9157. /*!
  9158. @throw parse_error.106 if an array index begins with '0'
  9159. @throw parse_error.109 if an array index was not a number
  9160. @throw out_of_range.402 if the array index '-' is used
  9161. @throw out_of_range.404 if the JSON pointer can not be resolved
  9162. */
  9163. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9164. {
  9165. using size_type = typename BasicJsonType::size_type;
  9166. for (const auto& reference_token : reference_tokens)
  9167. {
  9168. switch (ptr->type())
  9169. {
  9170. case detail::value_t::object:
  9171. {
  9172. // note: at performs range check
  9173. ptr = &ptr->at(reference_token);
  9174. break;
  9175. }
  9176. case detail::value_t::array:
  9177. {
  9178. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9179. {
  9180. // "-" always fails the range check
  9181. JSON_THROW(detail::out_of_range::create(402,
  9182. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9183. ") is out of range"));
  9184. }
  9185. // error condition (cf. RFC 6901, Sect. 4)
  9186. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9187. {
  9188. JSON_THROW(detail::parse_error::create(106, 0,
  9189. "array index '" + reference_token +
  9190. "' must not begin with '0'"));
  9191. }
  9192. // note: at performs range check
  9193. JSON_TRY
  9194. {
  9195. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9196. }
  9197. JSON_CATCH(std::invalid_argument&)
  9198. {
  9199. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9200. }
  9201. break;
  9202. }
  9203. default:
  9204. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9205. }
  9206. }
  9207. return *ptr;
  9208. }
  9209. /*!
  9210. @brief return a const reference to the pointed to value
  9211. @param[in] ptr a JSON value
  9212. @return const reference to the JSON value pointed to by the JSON
  9213. pointer
  9214. @throw parse_error.106 if an array index begins with '0'
  9215. @throw parse_error.109 if an array index was not a number
  9216. @throw out_of_range.402 if the array index '-' is used
  9217. @throw out_of_range.404 if the JSON pointer can not be resolved
  9218. */
  9219. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9220. {
  9221. using size_type = typename BasicJsonType::size_type;
  9222. for (const auto& reference_token : reference_tokens)
  9223. {
  9224. switch (ptr->type())
  9225. {
  9226. case detail::value_t::object:
  9227. {
  9228. // use unchecked object access
  9229. ptr = &ptr->operator[](reference_token);
  9230. break;
  9231. }
  9232. case detail::value_t::array:
  9233. {
  9234. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9235. {
  9236. // "-" cannot be used for const access
  9237. JSON_THROW(detail::out_of_range::create(402,
  9238. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9239. ") is out of range"));
  9240. }
  9241. // error condition (cf. RFC 6901, Sect. 4)
  9242. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9243. {
  9244. JSON_THROW(detail::parse_error::create(106, 0,
  9245. "array index '" + reference_token +
  9246. "' must not begin with '0'"));
  9247. }
  9248. // use unchecked array access
  9249. JSON_TRY
  9250. {
  9251. ptr = &ptr->operator[](
  9252. static_cast<size_type>(array_index(reference_token)));
  9253. }
  9254. JSON_CATCH(std::invalid_argument&)
  9255. {
  9256. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9257. }
  9258. break;
  9259. }
  9260. default:
  9261. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9262. }
  9263. }
  9264. return *ptr;
  9265. }
  9266. /*!
  9267. @throw parse_error.106 if an array index begins with '0'
  9268. @throw parse_error.109 if an array index was not a number
  9269. @throw out_of_range.402 if the array index '-' is used
  9270. @throw out_of_range.404 if the JSON pointer can not be resolved
  9271. */
  9272. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9273. {
  9274. using size_type = typename BasicJsonType::size_type;
  9275. for (const auto& reference_token : reference_tokens)
  9276. {
  9277. switch (ptr->type())
  9278. {
  9279. case detail::value_t::object:
  9280. {
  9281. // note: at performs range check
  9282. ptr = &ptr->at(reference_token);
  9283. break;
  9284. }
  9285. case detail::value_t::array:
  9286. {
  9287. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9288. {
  9289. // "-" always fails the range check
  9290. JSON_THROW(detail::out_of_range::create(402,
  9291. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9292. ") is out of range"));
  9293. }
  9294. // error condition (cf. RFC 6901, Sect. 4)
  9295. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9296. {
  9297. JSON_THROW(detail::parse_error::create(106, 0,
  9298. "array index '" + reference_token +
  9299. "' must not begin with '0'"));
  9300. }
  9301. // note: at performs range check
  9302. JSON_TRY
  9303. {
  9304. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9305. }
  9306. JSON_CATCH(std::invalid_argument&)
  9307. {
  9308. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9309. }
  9310. break;
  9311. }
  9312. default:
  9313. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9314. }
  9315. }
  9316. return *ptr;
  9317. }
  9318. /*!
  9319. @throw parse_error.106 if an array index begins with '0'
  9320. @throw parse_error.109 if an array index was not a number
  9321. */
  9322. bool contains(const BasicJsonType* ptr) const
  9323. {
  9324. using size_type = typename BasicJsonType::size_type;
  9325. for (const auto& reference_token : reference_tokens)
  9326. {
  9327. switch (ptr->type())
  9328. {
  9329. case detail::value_t::object:
  9330. {
  9331. if (not ptr->contains(reference_token))
  9332. {
  9333. // we did not find the key in the object
  9334. return false;
  9335. }
  9336. ptr = &ptr->operator[](reference_token);
  9337. break;
  9338. }
  9339. case detail::value_t::array:
  9340. {
  9341. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9342. {
  9343. // "-" always fails the range check
  9344. return false;
  9345. }
  9346. // error condition (cf. RFC 6901, Sect. 4)
  9347. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9348. {
  9349. JSON_THROW(detail::parse_error::create(106, 0,
  9350. "array index '" + reference_token +
  9351. "' must not begin with '0'"));
  9352. }
  9353. JSON_TRY
  9354. {
  9355. const auto idx = static_cast<size_type>(array_index(reference_token));
  9356. if (idx >= ptr->size())
  9357. {
  9358. // index out of range
  9359. return false;
  9360. }
  9361. ptr = &ptr->operator[](idx);
  9362. break;
  9363. }
  9364. JSON_CATCH(std::invalid_argument&)
  9365. {
  9366. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9367. }
  9368. break;
  9369. }
  9370. default:
  9371. {
  9372. // we do not expect primitive values if there is still a
  9373. // reference token to process
  9374. return false;
  9375. }
  9376. }
  9377. }
  9378. // no reference token left means we found a primitive value
  9379. return true;
  9380. }
  9381. /*!
  9382. @brief split the string input to reference tokens
  9383. @note This function is only called by the json_pointer constructor.
  9384. All exceptions below are documented there.
  9385. @throw parse_error.107 if the pointer is not empty or begins with '/'
  9386. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  9387. */
  9388. static std::vector<std::string> split(const std::string& reference_string)
  9389. {
  9390. std::vector<std::string> result;
  9391. // special case: empty reference string -> no reference tokens
  9392. if (reference_string.empty())
  9393. {
  9394. return result;
  9395. }
  9396. // check if nonempty reference string begins with slash
  9397. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  9398. {
  9399. JSON_THROW(detail::parse_error::create(107, 1,
  9400. "JSON pointer must be empty or begin with '/' - was: '" +
  9401. reference_string + "'"));
  9402. }
  9403. // extract the reference tokens:
  9404. // - slash: position of the last read slash (or end of string)
  9405. // - start: position after the previous slash
  9406. for (
  9407. // search for the first slash after the first character
  9408. std::size_t slash = reference_string.find_first_of('/', 1),
  9409. // set the beginning of the first reference token
  9410. start = 1;
  9411. // we can stop if start == 0 (if slash == std::string::npos)
  9412. start != 0;
  9413. // set the beginning of the next reference token
  9414. // (will eventually be 0 if slash == std::string::npos)
  9415. start = (slash == std::string::npos) ? 0 : slash + 1,
  9416. // find next slash
  9417. slash = reference_string.find_first_of('/', start))
  9418. {
  9419. // use the text between the beginning of the reference token
  9420. // (start) and the last slash (slash).
  9421. auto reference_token = reference_string.substr(start, slash - start);
  9422. // check reference tokens are properly escaped
  9423. for (std::size_t pos = reference_token.find_first_of('~');
  9424. pos != std::string::npos;
  9425. pos = reference_token.find_first_of('~', pos + 1))
  9426. {
  9427. assert(reference_token[pos] == '~');
  9428. // ~ must be followed by 0 or 1
  9429. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  9430. (reference_token[pos + 1] != '0' and
  9431. reference_token[pos + 1] != '1')))
  9432. {
  9433. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  9434. }
  9435. }
  9436. // finally, store the reference token
  9437. unescape(reference_token);
  9438. result.push_back(reference_token);
  9439. }
  9440. return result;
  9441. }
  9442. /*!
  9443. @brief replace all occurrences of a substring by another string
  9444. @param[in,out] s the string to manipulate; changed so that all
  9445. occurrences of @a f are replaced with @a t
  9446. @param[in] f the substring to replace with @a t
  9447. @param[in] t the string to replace @a f
  9448. @pre The search string @a f must not be empty. **This precondition is
  9449. enforced with an assertion.**
  9450. @since version 2.0.0
  9451. */
  9452. static void replace_substring(std::string& s, const std::string& f,
  9453. const std::string& t)
  9454. {
  9455. assert(not f.empty());
  9456. for (auto pos = s.find(f); // find first occurrence of f
  9457. pos != std::string::npos; // make sure f was found
  9458. s.replace(pos, f.size(), t), // replace with t, and
  9459. pos = s.find(f, pos + t.size())) // find next occurrence of f
  9460. {}
  9461. }
  9462. /// escape "~" to "~0" and "/" to "~1"
  9463. static std::string escape(std::string s)
  9464. {
  9465. replace_substring(s, "~", "~0");
  9466. replace_substring(s, "/", "~1");
  9467. return s;
  9468. }
  9469. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  9470. static void unescape(std::string& s)
  9471. {
  9472. replace_substring(s, "~1", "/");
  9473. replace_substring(s, "~0", "~");
  9474. }
  9475. /*!
  9476. @param[in] reference_string the reference string to the current value
  9477. @param[in] value the value to consider
  9478. @param[in,out] result the result object to insert values to
  9479. @note Empty objects or arrays are flattened to `null`.
  9480. */
  9481. static void flatten(const std::string& reference_string,
  9482. const BasicJsonType& value,
  9483. BasicJsonType& result)
  9484. {
  9485. switch (value.type())
  9486. {
  9487. case detail::value_t::array:
  9488. {
  9489. if (value.m_value.array->empty())
  9490. {
  9491. // flatten empty array as null
  9492. result[reference_string] = nullptr;
  9493. }
  9494. else
  9495. {
  9496. // iterate array and use index as reference string
  9497. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  9498. {
  9499. flatten(reference_string + "/" + std::to_string(i),
  9500. value.m_value.array->operator[](i), result);
  9501. }
  9502. }
  9503. break;
  9504. }
  9505. case detail::value_t::object:
  9506. {
  9507. if (value.m_value.object->empty())
  9508. {
  9509. // flatten empty object as null
  9510. result[reference_string] = nullptr;
  9511. }
  9512. else
  9513. {
  9514. // iterate object and use keys as reference string
  9515. for (const auto& element : *value.m_value.object)
  9516. {
  9517. flatten(reference_string + "/" + escape(element.first), element.second, result);
  9518. }
  9519. }
  9520. break;
  9521. }
  9522. default:
  9523. {
  9524. // add primitive value with its reference string
  9525. result[reference_string] = value;
  9526. break;
  9527. }
  9528. }
  9529. }
  9530. /*!
  9531. @param[in] value flattened JSON
  9532. @return unflattened JSON
  9533. @throw parse_error.109 if array index is not a number
  9534. @throw type_error.314 if value is not an object
  9535. @throw type_error.315 if object values are not primitive
  9536. @throw type_error.313 if value cannot be unflattened
  9537. */
  9538. static BasicJsonType
  9539. unflatten(const BasicJsonType& value)
  9540. {
  9541. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  9542. {
  9543. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  9544. }
  9545. BasicJsonType result;
  9546. // iterate the JSON object values
  9547. for (const auto& element : *value.m_value.object)
  9548. {
  9549. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  9550. {
  9551. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  9552. }
  9553. // assign value to reference pointed to by JSON pointer; Note that if
  9554. // the JSON pointer is "" (i.e., points to the whole value), function
  9555. // get_and_create returns a reference to result itself. An assignment
  9556. // will then create a primitive value.
  9557. json_pointer(element.first).get_and_create(result) = element.second;
  9558. }
  9559. return result;
  9560. }
  9561. /*!
  9562. @brief compares two JSON pointers for equality
  9563. @param[in] lhs JSON pointer to compare
  9564. @param[in] rhs JSON pointer to compare
  9565. @return whether @a lhs is equal to @a rhs
  9566. @complexity Linear in the length of the JSON pointer
  9567. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9568. */
  9569. friend bool operator==(json_pointer const& lhs,
  9570. json_pointer const& rhs) noexcept
  9571. {
  9572. return lhs.reference_tokens == rhs.reference_tokens;
  9573. }
  9574. /*!
  9575. @brief compares two JSON pointers for inequality
  9576. @param[in] lhs JSON pointer to compare
  9577. @param[in] rhs JSON pointer to compare
  9578. @return whether @a lhs is not equal @a rhs
  9579. @complexity Linear in the length of the JSON pointer
  9580. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9581. */
  9582. friend bool operator!=(json_pointer const& lhs,
  9583. json_pointer const& rhs) noexcept
  9584. {
  9585. return not (lhs == rhs);
  9586. }
  9587. /// the reference tokens
  9588. std::vector<std::string> reference_tokens;
  9589. };
  9590. } // namespace nlohmann
  9591. // #include <nlohmann/detail/json_ref.hpp>
  9592. #include <initializer_list>
  9593. #include <utility>
  9594. // #include <nlohmann/detail/meta/type_traits.hpp>
  9595. namespace nlohmann
  9596. {
  9597. namespace detail
  9598. {
  9599. template<typename BasicJsonType>
  9600. class json_ref
  9601. {
  9602. public:
  9603. using value_type = BasicJsonType;
  9604. json_ref(value_type&& value)
  9605. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  9606. {}
  9607. json_ref(const value_type& value)
  9608. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  9609. {}
  9610. json_ref(std::initializer_list<json_ref> init)
  9611. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  9612. {}
  9613. template <
  9614. class... Args,
  9615. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  9616. json_ref(Args && ... args)
  9617. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  9618. is_rvalue(true) {}
  9619. // class should be movable only
  9620. json_ref(json_ref&&) = default;
  9621. json_ref(const json_ref&) = delete;
  9622. json_ref& operator=(const json_ref&) = delete;
  9623. json_ref& operator=(json_ref&&) = delete;
  9624. ~json_ref() = default;
  9625. value_type moved_or_copied() const
  9626. {
  9627. if (is_rvalue)
  9628. {
  9629. return std::move(*value_ref);
  9630. }
  9631. return *value_ref;
  9632. }
  9633. value_type const& operator*() const
  9634. {
  9635. return *static_cast<value_type const*>(value_ref);
  9636. }
  9637. value_type const* operator->() const
  9638. {
  9639. return static_cast<value_type const*>(value_ref);
  9640. }
  9641. private:
  9642. mutable value_type owned_value = nullptr;
  9643. value_type* value_ref = nullptr;
  9644. const bool is_rvalue;
  9645. };
  9646. } // namespace detail
  9647. } // namespace nlohmann
  9648. // #include <nlohmann/detail/macro_scope.hpp>
  9649. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9650. // #include <nlohmann/detail/meta/type_traits.hpp>
  9651. // #include <nlohmann/detail/output/binary_writer.hpp>
  9652. #include <algorithm> // reverse
  9653. #include <array> // array
  9654. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  9655. #include <cstring> // memcpy
  9656. #include <limits> // numeric_limits
  9657. #include <string> // string
  9658. // #include <nlohmann/detail/input/binary_reader.hpp>
  9659. // #include <nlohmann/detail/macro_scope.hpp>
  9660. // #include <nlohmann/detail/output/output_adapters.hpp>
  9661. #include <algorithm> // copy
  9662. #include <cstddef> // size_t
  9663. #include <ios> // streamsize
  9664. #include <iterator> // back_inserter
  9665. #include <memory> // shared_ptr, make_shared
  9666. #include <ostream> // basic_ostream
  9667. #include <string> // basic_string
  9668. #include <vector> // vector
  9669. // #include <nlohmann/detail/macro_scope.hpp>
  9670. namespace nlohmann
  9671. {
  9672. namespace detail
  9673. {
  9674. /// abstract output adapter interface
  9675. template<typename CharType> struct output_adapter_protocol
  9676. {
  9677. virtual void write_character(CharType c) = 0;
  9678. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  9679. virtual ~output_adapter_protocol() = default;
  9680. };
  9681. /// a type to simplify interfaces
  9682. template<typename CharType>
  9683. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  9684. /// output adapter for byte vectors
  9685. template<typename CharType>
  9686. class output_vector_adapter : public output_adapter_protocol<CharType>
  9687. {
  9688. public:
  9689. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  9690. : v(vec)
  9691. {}
  9692. void write_character(CharType c) override
  9693. {
  9694. v.push_back(c);
  9695. }
  9696. JSON_HEDLEY_NON_NULL(2)
  9697. void write_characters(const CharType* s, std::size_t length) override
  9698. {
  9699. std::copy(s, s + length, std::back_inserter(v));
  9700. }
  9701. private:
  9702. std::vector<CharType>& v;
  9703. };
  9704. /// output adapter for output streams
  9705. template<typename CharType>
  9706. class output_stream_adapter : public output_adapter_protocol<CharType>
  9707. {
  9708. public:
  9709. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  9710. : stream(s)
  9711. {}
  9712. void write_character(CharType c) override
  9713. {
  9714. stream.put(c);
  9715. }
  9716. JSON_HEDLEY_NON_NULL(2)
  9717. void write_characters(const CharType* s, std::size_t length) override
  9718. {
  9719. stream.write(s, static_cast<std::streamsize>(length));
  9720. }
  9721. private:
  9722. std::basic_ostream<CharType>& stream;
  9723. };
  9724. /// output adapter for basic_string
  9725. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9726. class output_string_adapter : public output_adapter_protocol<CharType>
  9727. {
  9728. public:
  9729. explicit output_string_adapter(StringType& s) noexcept
  9730. : str(s)
  9731. {}
  9732. void write_character(CharType c) override
  9733. {
  9734. str.push_back(c);
  9735. }
  9736. JSON_HEDLEY_NON_NULL(2)
  9737. void write_characters(const CharType* s, std::size_t length) override
  9738. {
  9739. str.append(s, length);
  9740. }
  9741. private:
  9742. StringType& str;
  9743. };
  9744. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9745. class output_adapter
  9746. {
  9747. public:
  9748. output_adapter(std::vector<CharType>& vec)
  9749. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  9750. output_adapter(std::basic_ostream<CharType>& s)
  9751. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  9752. output_adapter(StringType& s)
  9753. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  9754. operator output_adapter_t<CharType>()
  9755. {
  9756. return oa;
  9757. }
  9758. private:
  9759. output_adapter_t<CharType> oa = nullptr;
  9760. };
  9761. } // namespace detail
  9762. } // namespace nlohmann
  9763. namespace nlohmann
  9764. {
  9765. namespace detail
  9766. {
  9767. ///////////////////
  9768. // binary writer //
  9769. ///////////////////
  9770. /*!
  9771. @brief serialization to CBOR and MessagePack values
  9772. */
  9773. template<typename BasicJsonType, typename CharType>
  9774. class binary_writer
  9775. {
  9776. using string_t = typename BasicJsonType::string_t;
  9777. public:
  9778. /*!
  9779. @brief create a binary writer
  9780. @param[in] adapter output adapter to write to
  9781. */
  9782. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  9783. {
  9784. assert(oa);
  9785. }
  9786. /*!
  9787. @param[in] j JSON value to serialize
  9788. @pre j.type() == value_t::object
  9789. */
  9790. void write_bson(const BasicJsonType& j)
  9791. {
  9792. switch (j.type())
  9793. {
  9794. case value_t::object:
  9795. {
  9796. write_bson_object(*j.m_value.object);
  9797. break;
  9798. }
  9799. default:
  9800. {
  9801. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  9802. }
  9803. }
  9804. }
  9805. /*!
  9806. @param[in] j JSON value to serialize
  9807. */
  9808. void write_cbor(const BasicJsonType& j)
  9809. {
  9810. switch (j.type())
  9811. {
  9812. case value_t::null:
  9813. {
  9814. oa->write_character(to_char_type(0xF6));
  9815. break;
  9816. }
  9817. case value_t::boolean:
  9818. {
  9819. oa->write_character(j.m_value.boolean
  9820. ? to_char_type(0xF5)
  9821. : to_char_type(0xF4));
  9822. break;
  9823. }
  9824. case value_t::number_integer:
  9825. {
  9826. if (j.m_value.number_integer >= 0)
  9827. {
  9828. // CBOR does not differentiate between positive signed
  9829. // integers and unsigned integers. Therefore, we used the
  9830. // code from the value_t::number_unsigned case here.
  9831. if (j.m_value.number_integer <= 0x17)
  9832. {
  9833. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9834. }
  9835. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  9836. {
  9837. oa->write_character(to_char_type(0x18));
  9838. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9839. }
  9840. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  9841. {
  9842. oa->write_character(to_char_type(0x19));
  9843. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  9844. }
  9845. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  9846. {
  9847. oa->write_character(to_char_type(0x1A));
  9848. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  9849. }
  9850. else
  9851. {
  9852. oa->write_character(to_char_type(0x1B));
  9853. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  9854. }
  9855. }
  9856. else
  9857. {
  9858. // The conversions below encode the sign in the first
  9859. // byte, and the value is converted to a positive number.
  9860. const auto positive_number = -1 - j.m_value.number_integer;
  9861. if (j.m_value.number_integer >= -24)
  9862. {
  9863. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  9864. }
  9865. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  9866. {
  9867. oa->write_character(to_char_type(0x38));
  9868. write_number(static_cast<std::uint8_t>(positive_number));
  9869. }
  9870. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  9871. {
  9872. oa->write_character(to_char_type(0x39));
  9873. write_number(static_cast<std::uint16_t>(positive_number));
  9874. }
  9875. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  9876. {
  9877. oa->write_character(to_char_type(0x3A));
  9878. write_number(static_cast<std::uint32_t>(positive_number));
  9879. }
  9880. else
  9881. {
  9882. oa->write_character(to_char_type(0x3B));
  9883. write_number(static_cast<std::uint64_t>(positive_number));
  9884. }
  9885. }
  9886. break;
  9887. }
  9888. case value_t::number_unsigned:
  9889. {
  9890. if (j.m_value.number_unsigned <= 0x17)
  9891. {
  9892. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9893. }
  9894. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9895. {
  9896. oa->write_character(to_char_type(0x18));
  9897. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9898. }
  9899. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  9900. {
  9901. oa->write_character(to_char_type(0x19));
  9902. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  9903. }
  9904. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  9905. {
  9906. oa->write_character(to_char_type(0x1A));
  9907. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  9908. }
  9909. else
  9910. {
  9911. oa->write_character(to_char_type(0x1B));
  9912. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  9913. }
  9914. break;
  9915. }
  9916. case value_t::number_float:
  9917. {
  9918. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  9919. write_number(j.m_value.number_float);
  9920. break;
  9921. }
  9922. case value_t::string:
  9923. {
  9924. // step 1: write control byte and the string length
  9925. const auto N = j.m_value.string->size();
  9926. if (N <= 0x17)
  9927. {
  9928. write_number(static_cast<std::uint8_t>(0x60 + N));
  9929. }
  9930. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9931. {
  9932. oa->write_character(to_char_type(0x78));
  9933. write_number(static_cast<std::uint8_t>(N));
  9934. }
  9935. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9936. {
  9937. oa->write_character(to_char_type(0x79));
  9938. write_number(static_cast<std::uint16_t>(N));
  9939. }
  9940. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9941. {
  9942. oa->write_character(to_char_type(0x7A));
  9943. write_number(static_cast<std::uint32_t>(N));
  9944. }
  9945. // LCOV_EXCL_START
  9946. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9947. {
  9948. oa->write_character(to_char_type(0x7B));
  9949. write_number(static_cast<std::uint64_t>(N));
  9950. }
  9951. // LCOV_EXCL_STOP
  9952. // step 2: write the string
  9953. oa->write_characters(
  9954. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  9955. j.m_value.string->size());
  9956. break;
  9957. }
  9958. case value_t::array:
  9959. {
  9960. // step 1: write control byte and the array size
  9961. const auto N = j.m_value.array->size();
  9962. if (N <= 0x17)
  9963. {
  9964. write_number(static_cast<std::uint8_t>(0x80 + N));
  9965. }
  9966. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9967. {
  9968. oa->write_character(to_char_type(0x98));
  9969. write_number(static_cast<std::uint8_t>(N));
  9970. }
  9971. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9972. {
  9973. oa->write_character(to_char_type(0x99));
  9974. write_number(static_cast<std::uint16_t>(N));
  9975. }
  9976. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9977. {
  9978. oa->write_character(to_char_type(0x9A));
  9979. write_number(static_cast<std::uint32_t>(N));
  9980. }
  9981. // LCOV_EXCL_START
  9982. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9983. {
  9984. oa->write_character(to_char_type(0x9B));
  9985. write_number(static_cast<std::uint64_t>(N));
  9986. }
  9987. // LCOV_EXCL_STOP
  9988. // step 2: write each element
  9989. for (const auto& el : *j.m_value.array)
  9990. {
  9991. write_cbor(el);
  9992. }
  9993. break;
  9994. }
  9995. case value_t::object:
  9996. {
  9997. // step 1: write control byte and the object size
  9998. const auto N = j.m_value.object->size();
  9999. if (N <= 0x17)
  10000. {
  10001. write_number(static_cast<std::uint8_t>(0xA0 + N));
  10002. }
  10003. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10004. {
  10005. oa->write_character(to_char_type(0xB8));
  10006. write_number(static_cast<std::uint8_t>(N));
  10007. }
  10008. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10009. {
  10010. oa->write_character(to_char_type(0xB9));
  10011. write_number(static_cast<std::uint16_t>(N));
  10012. }
  10013. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10014. {
  10015. oa->write_character(to_char_type(0xBA));
  10016. write_number(static_cast<std::uint32_t>(N));
  10017. }
  10018. // LCOV_EXCL_START
  10019. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10020. {
  10021. oa->write_character(to_char_type(0xBB));
  10022. write_number(static_cast<std::uint64_t>(N));
  10023. }
  10024. // LCOV_EXCL_STOP
  10025. // step 2: write each element
  10026. for (const auto& el : *j.m_value.object)
  10027. {
  10028. write_cbor(el.first);
  10029. write_cbor(el.second);
  10030. }
  10031. break;
  10032. }
  10033. default:
  10034. break;
  10035. }
  10036. }
  10037. /*!
  10038. @param[in] j JSON value to serialize
  10039. */
  10040. void write_msgpack(const BasicJsonType& j)
  10041. {
  10042. switch (j.type())
  10043. {
  10044. case value_t::null: // nil
  10045. {
  10046. oa->write_character(to_char_type(0xC0));
  10047. break;
  10048. }
  10049. case value_t::boolean: // true and false
  10050. {
  10051. oa->write_character(j.m_value.boolean
  10052. ? to_char_type(0xC3)
  10053. : to_char_type(0xC2));
  10054. break;
  10055. }
  10056. case value_t::number_integer:
  10057. {
  10058. if (j.m_value.number_integer >= 0)
  10059. {
  10060. // MessagePack does not differentiate between positive
  10061. // signed integers and unsigned integers. Therefore, we used
  10062. // the code from the value_t::number_unsigned case here.
  10063. if (j.m_value.number_unsigned < 128)
  10064. {
  10065. // positive fixnum
  10066. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10067. }
  10068. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10069. {
  10070. // uint 8
  10071. oa->write_character(to_char_type(0xCC));
  10072. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10073. }
  10074. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10075. {
  10076. // uint 16
  10077. oa->write_character(to_char_type(0xCD));
  10078. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10079. }
  10080. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10081. {
  10082. // uint 32
  10083. oa->write_character(to_char_type(0xCE));
  10084. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10085. }
  10086. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10087. {
  10088. // uint 64
  10089. oa->write_character(to_char_type(0xCF));
  10090. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10091. }
  10092. }
  10093. else
  10094. {
  10095. if (j.m_value.number_integer >= -32)
  10096. {
  10097. // negative fixnum
  10098. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10099. }
  10100. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10101. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10102. {
  10103. // int 8
  10104. oa->write_character(to_char_type(0xD0));
  10105. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10106. }
  10107. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10108. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10109. {
  10110. // int 16
  10111. oa->write_character(to_char_type(0xD1));
  10112. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10113. }
  10114. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10115. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10116. {
  10117. // int 32
  10118. oa->write_character(to_char_type(0xD2));
  10119. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  10120. }
  10121. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  10122. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  10123. {
  10124. // int 64
  10125. oa->write_character(to_char_type(0xD3));
  10126. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  10127. }
  10128. }
  10129. break;
  10130. }
  10131. case value_t::number_unsigned:
  10132. {
  10133. if (j.m_value.number_unsigned < 128)
  10134. {
  10135. // positive fixnum
  10136. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10137. }
  10138. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10139. {
  10140. // uint 8
  10141. oa->write_character(to_char_type(0xCC));
  10142. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10143. }
  10144. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10145. {
  10146. // uint 16
  10147. oa->write_character(to_char_type(0xCD));
  10148. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10149. }
  10150. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10151. {
  10152. // uint 32
  10153. oa->write_character(to_char_type(0xCE));
  10154. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10155. }
  10156. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10157. {
  10158. // uint 64
  10159. oa->write_character(to_char_type(0xCF));
  10160. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10161. }
  10162. break;
  10163. }
  10164. case value_t::number_float:
  10165. {
  10166. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  10167. write_number(j.m_value.number_float);
  10168. break;
  10169. }
  10170. case value_t::string:
  10171. {
  10172. // step 1: write control byte and the string length
  10173. const auto N = j.m_value.string->size();
  10174. if (N <= 31)
  10175. {
  10176. // fixstr
  10177. write_number(static_cast<std::uint8_t>(0xA0 | N));
  10178. }
  10179. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10180. {
  10181. // str 8
  10182. oa->write_character(to_char_type(0xD9));
  10183. write_number(static_cast<std::uint8_t>(N));
  10184. }
  10185. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10186. {
  10187. // str 16
  10188. oa->write_character(to_char_type(0xDA));
  10189. write_number(static_cast<std::uint16_t>(N));
  10190. }
  10191. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10192. {
  10193. // str 32
  10194. oa->write_character(to_char_type(0xDB));
  10195. write_number(static_cast<std::uint32_t>(N));
  10196. }
  10197. // step 2: write the string
  10198. oa->write_characters(
  10199. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10200. j.m_value.string->size());
  10201. break;
  10202. }
  10203. case value_t::array:
  10204. {
  10205. // step 1: write control byte and the array size
  10206. const auto N = j.m_value.array->size();
  10207. if (N <= 15)
  10208. {
  10209. // fixarray
  10210. write_number(static_cast<std::uint8_t>(0x90 | N));
  10211. }
  10212. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10213. {
  10214. // array 16
  10215. oa->write_character(to_char_type(0xDC));
  10216. write_number(static_cast<std::uint16_t>(N));
  10217. }
  10218. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10219. {
  10220. // array 32
  10221. oa->write_character(to_char_type(0xDD));
  10222. write_number(static_cast<std::uint32_t>(N));
  10223. }
  10224. // step 2: write each element
  10225. for (const auto& el : *j.m_value.array)
  10226. {
  10227. write_msgpack(el);
  10228. }
  10229. break;
  10230. }
  10231. case value_t::object:
  10232. {
  10233. // step 1: write control byte and the object size
  10234. const auto N = j.m_value.object->size();
  10235. if (N <= 15)
  10236. {
  10237. // fixmap
  10238. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  10239. }
  10240. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10241. {
  10242. // map 16
  10243. oa->write_character(to_char_type(0xDE));
  10244. write_number(static_cast<std::uint16_t>(N));
  10245. }
  10246. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10247. {
  10248. // map 32
  10249. oa->write_character(to_char_type(0xDF));
  10250. write_number(static_cast<std::uint32_t>(N));
  10251. }
  10252. // step 2: write each element
  10253. for (const auto& el : *j.m_value.object)
  10254. {
  10255. write_msgpack(el.first);
  10256. write_msgpack(el.second);
  10257. }
  10258. break;
  10259. }
  10260. default:
  10261. break;
  10262. }
  10263. }
  10264. /*!
  10265. @param[in] j JSON value to serialize
  10266. @param[in] use_count whether to use '#' prefixes (optimized format)
  10267. @param[in] use_type whether to use '$' prefixes (optimized format)
  10268. @param[in] add_prefix whether prefixes need to be used for this value
  10269. */
  10270. void write_ubjson(const BasicJsonType& j, const bool use_count,
  10271. const bool use_type, const bool add_prefix = true)
  10272. {
  10273. switch (j.type())
  10274. {
  10275. case value_t::null:
  10276. {
  10277. if (add_prefix)
  10278. {
  10279. oa->write_character(to_char_type('Z'));
  10280. }
  10281. break;
  10282. }
  10283. case value_t::boolean:
  10284. {
  10285. if (add_prefix)
  10286. {
  10287. oa->write_character(j.m_value.boolean
  10288. ? to_char_type('T')
  10289. : to_char_type('F'));
  10290. }
  10291. break;
  10292. }
  10293. case value_t::number_integer:
  10294. {
  10295. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  10296. break;
  10297. }
  10298. case value_t::number_unsigned:
  10299. {
  10300. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  10301. break;
  10302. }
  10303. case value_t::number_float:
  10304. {
  10305. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  10306. break;
  10307. }
  10308. case value_t::string:
  10309. {
  10310. if (add_prefix)
  10311. {
  10312. oa->write_character(to_char_type('S'));
  10313. }
  10314. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  10315. oa->write_characters(
  10316. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10317. j.m_value.string->size());
  10318. break;
  10319. }
  10320. case value_t::array:
  10321. {
  10322. if (add_prefix)
  10323. {
  10324. oa->write_character(to_char_type('['));
  10325. }
  10326. bool prefix_required = true;
  10327. if (use_type and not j.m_value.array->empty())
  10328. {
  10329. assert(use_count);
  10330. const CharType first_prefix = ubjson_prefix(j.front());
  10331. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  10332. [this, first_prefix](const BasicJsonType & v)
  10333. {
  10334. return ubjson_prefix(v) == first_prefix;
  10335. });
  10336. if (same_prefix)
  10337. {
  10338. prefix_required = false;
  10339. oa->write_character(to_char_type('$'));
  10340. oa->write_character(first_prefix);
  10341. }
  10342. }
  10343. if (use_count)
  10344. {
  10345. oa->write_character(to_char_type('#'));
  10346. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  10347. }
  10348. for (const auto& el : *j.m_value.array)
  10349. {
  10350. write_ubjson(el, use_count, use_type, prefix_required);
  10351. }
  10352. if (not use_count)
  10353. {
  10354. oa->write_character(to_char_type(']'));
  10355. }
  10356. break;
  10357. }
  10358. case value_t::object:
  10359. {
  10360. if (add_prefix)
  10361. {
  10362. oa->write_character(to_char_type('{'));
  10363. }
  10364. bool prefix_required = true;
  10365. if (use_type and not j.m_value.object->empty())
  10366. {
  10367. assert(use_count);
  10368. const CharType first_prefix = ubjson_prefix(j.front());
  10369. const bool same_prefix = std::all_of(j.begin(), j.end(),
  10370. [this, first_prefix](const BasicJsonType & v)
  10371. {
  10372. return ubjson_prefix(v) == first_prefix;
  10373. });
  10374. if (same_prefix)
  10375. {
  10376. prefix_required = false;
  10377. oa->write_character(to_char_type('$'));
  10378. oa->write_character(first_prefix);
  10379. }
  10380. }
  10381. if (use_count)
  10382. {
  10383. oa->write_character(to_char_type('#'));
  10384. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  10385. }
  10386. for (const auto& el : *j.m_value.object)
  10387. {
  10388. write_number_with_ubjson_prefix(el.first.size(), true);
  10389. oa->write_characters(
  10390. reinterpret_cast<const CharType*>(el.first.c_str()),
  10391. el.first.size());
  10392. write_ubjson(el.second, use_count, use_type, prefix_required);
  10393. }
  10394. if (not use_count)
  10395. {
  10396. oa->write_character(to_char_type('}'));
  10397. }
  10398. break;
  10399. }
  10400. default:
  10401. break;
  10402. }
  10403. }
  10404. private:
  10405. //////////
  10406. // BSON //
  10407. //////////
  10408. /*!
  10409. @return The size of a BSON document entry header, including the id marker
  10410. and the entry name size (and its null-terminator).
  10411. */
  10412. static std::size_t calc_bson_entry_header_size(const string_t& name)
  10413. {
  10414. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  10415. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  10416. {
  10417. JSON_THROW(out_of_range::create(409,
  10418. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  10419. }
  10420. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  10421. }
  10422. /*!
  10423. @brief Writes the given @a element_type and @a name to the output adapter
  10424. */
  10425. void write_bson_entry_header(const string_t& name,
  10426. const std::uint8_t element_type)
  10427. {
  10428. oa->write_character(to_char_type(element_type)); // boolean
  10429. oa->write_characters(
  10430. reinterpret_cast<const CharType*>(name.c_str()),
  10431. name.size() + 1u);
  10432. }
  10433. /*!
  10434. @brief Writes a BSON element with key @a name and boolean value @a value
  10435. */
  10436. void write_bson_boolean(const string_t& name,
  10437. const bool value)
  10438. {
  10439. write_bson_entry_header(name, 0x08);
  10440. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  10441. }
  10442. /*!
  10443. @brief Writes a BSON element with key @a name and double value @a value
  10444. */
  10445. void write_bson_double(const string_t& name,
  10446. const double value)
  10447. {
  10448. write_bson_entry_header(name, 0x01);
  10449. write_number<double, true>(value);
  10450. }
  10451. /*!
  10452. @return The size of the BSON-encoded string in @a value
  10453. */
  10454. static std::size_t calc_bson_string_size(const string_t& value)
  10455. {
  10456. return sizeof(std::int32_t) + value.size() + 1ul;
  10457. }
  10458. /*!
  10459. @brief Writes a BSON element with key @a name and string value @a value
  10460. */
  10461. void write_bson_string(const string_t& name,
  10462. const string_t& value)
  10463. {
  10464. write_bson_entry_header(name, 0x02);
  10465. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  10466. oa->write_characters(
  10467. reinterpret_cast<const CharType*>(value.c_str()),
  10468. value.size() + 1);
  10469. }
  10470. /*!
  10471. @brief Writes a BSON element with key @a name and null value
  10472. */
  10473. void write_bson_null(const string_t& name)
  10474. {
  10475. write_bson_entry_header(name, 0x0A);
  10476. }
  10477. /*!
  10478. @return The size of the BSON-encoded integer @a value
  10479. */
  10480. static std::size_t calc_bson_integer_size(const std::int64_t value)
  10481. {
  10482. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  10483. ? sizeof(std::int32_t)
  10484. : sizeof(std::int64_t);
  10485. }
  10486. /*!
  10487. @brief Writes a BSON element with key @a name and integer @a value
  10488. */
  10489. void write_bson_integer(const string_t& name,
  10490. const std::int64_t value)
  10491. {
  10492. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  10493. {
  10494. write_bson_entry_header(name, 0x10); // int32
  10495. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10496. }
  10497. else
  10498. {
  10499. write_bson_entry_header(name, 0x12); // int64
  10500. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10501. }
  10502. }
  10503. /*!
  10504. @return The size of the BSON-encoded unsigned integer in @a j
  10505. */
  10506. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  10507. {
  10508. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10509. ? sizeof(std::int32_t)
  10510. : sizeof(std::int64_t);
  10511. }
  10512. /*!
  10513. @brief Writes a BSON element with key @a name and unsigned @a value
  10514. */
  10515. void write_bson_unsigned(const string_t& name,
  10516. const std::uint64_t value)
  10517. {
  10518. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10519. {
  10520. write_bson_entry_header(name, 0x10 /* int32 */);
  10521. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10522. }
  10523. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10524. {
  10525. write_bson_entry_header(name, 0x12 /* int64 */);
  10526. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10527. }
  10528. else
  10529. {
  10530. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  10531. }
  10532. }
  10533. /*!
  10534. @brief Writes a BSON element with key @a name and object @a value
  10535. */
  10536. void write_bson_object_entry(const string_t& name,
  10537. const typename BasicJsonType::object_t& value)
  10538. {
  10539. write_bson_entry_header(name, 0x03); // object
  10540. write_bson_object(value);
  10541. }
  10542. /*!
  10543. @return The size of the BSON-encoded array @a value
  10544. */
  10545. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  10546. {
  10547. std::size_t array_index = 0ul;
  10548. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), 0ul, [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  10549. {
  10550. return result + calc_bson_element_size(std::to_string(array_index++), el);
  10551. });
  10552. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  10553. }
  10554. /*!
  10555. @brief Writes a BSON element with key @a name and array @a value
  10556. */
  10557. void write_bson_array(const string_t& name,
  10558. const typename BasicJsonType::array_t& value)
  10559. {
  10560. write_bson_entry_header(name, 0x04); // array
  10561. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  10562. std::size_t array_index = 0ul;
  10563. for (const auto& el : value)
  10564. {
  10565. write_bson_element(std::to_string(array_index++), el);
  10566. }
  10567. oa->write_character(to_char_type(0x00));
  10568. }
  10569. /*!
  10570. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  10571. @return The calculated size for the BSON document entry for @a j with the given @a name.
  10572. */
  10573. static std::size_t calc_bson_element_size(const string_t& name,
  10574. const BasicJsonType& j)
  10575. {
  10576. const auto header_size = calc_bson_entry_header_size(name);
  10577. switch (j.type())
  10578. {
  10579. case value_t::object:
  10580. return header_size + calc_bson_object_size(*j.m_value.object);
  10581. case value_t::array:
  10582. return header_size + calc_bson_array_size(*j.m_value.array);
  10583. case value_t::boolean:
  10584. return header_size + 1ul;
  10585. case value_t::number_float:
  10586. return header_size + 8ul;
  10587. case value_t::number_integer:
  10588. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  10589. case value_t::number_unsigned:
  10590. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  10591. case value_t::string:
  10592. return header_size + calc_bson_string_size(*j.m_value.string);
  10593. case value_t::null:
  10594. return header_size + 0ul;
  10595. // LCOV_EXCL_START
  10596. default:
  10597. assert(false);
  10598. return 0ul;
  10599. // LCOV_EXCL_STOP
  10600. }
  10601. }
  10602. /*!
  10603. @brief Serializes the JSON value @a j to BSON and associates it with the
  10604. key @a name.
  10605. @param name The name to associate with the JSON entity @a j within the
  10606. current BSON document
  10607. @return The size of the BSON entry
  10608. */
  10609. void write_bson_element(const string_t& name,
  10610. const BasicJsonType& j)
  10611. {
  10612. switch (j.type())
  10613. {
  10614. case value_t::object:
  10615. return write_bson_object_entry(name, *j.m_value.object);
  10616. case value_t::array:
  10617. return write_bson_array(name, *j.m_value.array);
  10618. case value_t::boolean:
  10619. return write_bson_boolean(name, j.m_value.boolean);
  10620. case value_t::number_float:
  10621. return write_bson_double(name, j.m_value.number_float);
  10622. case value_t::number_integer:
  10623. return write_bson_integer(name, j.m_value.number_integer);
  10624. case value_t::number_unsigned:
  10625. return write_bson_unsigned(name, j.m_value.number_unsigned);
  10626. case value_t::string:
  10627. return write_bson_string(name, *j.m_value.string);
  10628. case value_t::null:
  10629. return write_bson_null(name);
  10630. // LCOV_EXCL_START
  10631. default:
  10632. assert(false);
  10633. return;
  10634. // LCOV_EXCL_STOP
  10635. }
  10636. }
  10637. /*!
  10638. @brief Calculates the size of the BSON serialization of the given
  10639. JSON-object @a j.
  10640. @param[in] j JSON value to serialize
  10641. @pre j.type() == value_t::object
  10642. */
  10643. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  10644. {
  10645. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  10646. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  10647. {
  10648. return result += calc_bson_element_size(el.first, el.second);
  10649. });
  10650. return sizeof(std::int32_t) + document_size + 1ul;
  10651. }
  10652. /*!
  10653. @param[in] j JSON value to serialize
  10654. @pre j.type() == value_t::object
  10655. */
  10656. void write_bson_object(const typename BasicJsonType::object_t& value)
  10657. {
  10658. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  10659. for (const auto& el : value)
  10660. {
  10661. write_bson_element(el.first, el.second);
  10662. }
  10663. oa->write_character(to_char_type(0x00));
  10664. }
  10665. //////////
  10666. // CBOR //
  10667. //////////
  10668. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  10669. {
  10670. return to_char_type(0xFA); // Single-Precision Float
  10671. }
  10672. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  10673. {
  10674. return to_char_type(0xFB); // Double-Precision Float
  10675. }
  10676. /////////////
  10677. // MsgPack //
  10678. /////////////
  10679. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  10680. {
  10681. return to_char_type(0xCA); // float 32
  10682. }
  10683. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  10684. {
  10685. return to_char_type(0xCB); // float 64
  10686. }
  10687. ////////////
  10688. // UBJSON //
  10689. ////////////
  10690. // UBJSON: write number (floating point)
  10691. template<typename NumberType, typename std::enable_if<
  10692. std::is_floating_point<NumberType>::value, int>::type = 0>
  10693. void write_number_with_ubjson_prefix(const NumberType n,
  10694. const bool add_prefix)
  10695. {
  10696. if (add_prefix)
  10697. {
  10698. oa->write_character(get_ubjson_float_prefix(n));
  10699. }
  10700. write_number(n);
  10701. }
  10702. // UBJSON: write number (unsigned integer)
  10703. template<typename NumberType, typename std::enable_if<
  10704. std::is_unsigned<NumberType>::value, int>::type = 0>
  10705. void write_number_with_ubjson_prefix(const NumberType n,
  10706. const bool add_prefix)
  10707. {
  10708. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10709. {
  10710. if (add_prefix)
  10711. {
  10712. oa->write_character(to_char_type('i')); // int8
  10713. }
  10714. write_number(static_cast<std::uint8_t>(n));
  10715. }
  10716. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  10717. {
  10718. if (add_prefix)
  10719. {
  10720. oa->write_character(to_char_type('U')); // uint8
  10721. }
  10722. write_number(static_cast<std::uint8_t>(n));
  10723. }
  10724. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10725. {
  10726. if (add_prefix)
  10727. {
  10728. oa->write_character(to_char_type('I')); // int16
  10729. }
  10730. write_number(static_cast<std::int16_t>(n));
  10731. }
  10732. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10733. {
  10734. if (add_prefix)
  10735. {
  10736. oa->write_character(to_char_type('l')); // int32
  10737. }
  10738. write_number(static_cast<std::int32_t>(n));
  10739. }
  10740. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10741. {
  10742. if (add_prefix)
  10743. {
  10744. oa->write_character(to_char_type('L')); // int64
  10745. }
  10746. write_number(static_cast<std::int64_t>(n));
  10747. }
  10748. else
  10749. {
  10750. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10751. }
  10752. }
  10753. // UBJSON: write number (signed integer)
  10754. template<typename NumberType, typename std::enable_if<
  10755. std::is_signed<NumberType>::value and
  10756. not std::is_floating_point<NumberType>::value, int>::type = 0>
  10757. void write_number_with_ubjson_prefix(const NumberType n,
  10758. const bool add_prefix)
  10759. {
  10760. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  10761. {
  10762. if (add_prefix)
  10763. {
  10764. oa->write_character(to_char_type('i')); // int8
  10765. }
  10766. write_number(static_cast<std::int8_t>(n));
  10767. }
  10768. 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)()))
  10769. {
  10770. if (add_prefix)
  10771. {
  10772. oa->write_character(to_char_type('U')); // uint8
  10773. }
  10774. write_number(static_cast<std::uint8_t>(n));
  10775. }
  10776. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  10777. {
  10778. if (add_prefix)
  10779. {
  10780. oa->write_character(to_char_type('I')); // int16
  10781. }
  10782. write_number(static_cast<std::int16_t>(n));
  10783. }
  10784. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  10785. {
  10786. if (add_prefix)
  10787. {
  10788. oa->write_character(to_char_type('l')); // int32
  10789. }
  10790. write_number(static_cast<std::int32_t>(n));
  10791. }
  10792. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  10793. {
  10794. if (add_prefix)
  10795. {
  10796. oa->write_character(to_char_type('L')); // int64
  10797. }
  10798. write_number(static_cast<std::int64_t>(n));
  10799. }
  10800. // LCOV_EXCL_START
  10801. else
  10802. {
  10803. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10804. }
  10805. // LCOV_EXCL_STOP
  10806. }
  10807. /*!
  10808. @brief determine the type prefix of container values
  10809. @note This function does not need to be 100% accurate when it comes to
  10810. integer limits. In case a number exceeds the limits of int64_t,
  10811. this will be detected by a later call to function
  10812. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  10813. value that does not fit the previous limits.
  10814. */
  10815. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  10816. {
  10817. switch (j.type())
  10818. {
  10819. case value_t::null:
  10820. return 'Z';
  10821. case value_t::boolean:
  10822. return j.m_value.boolean ? 'T' : 'F';
  10823. case value_t::number_integer:
  10824. {
  10825. 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)())
  10826. {
  10827. return 'i';
  10828. }
  10829. 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)())
  10830. {
  10831. return 'U';
  10832. }
  10833. 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)())
  10834. {
  10835. return 'I';
  10836. }
  10837. 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)())
  10838. {
  10839. return 'l';
  10840. }
  10841. // no check and assume int64_t (see note above)
  10842. return 'L';
  10843. }
  10844. case value_t::number_unsigned:
  10845. {
  10846. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10847. {
  10848. return 'i';
  10849. }
  10850. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10851. {
  10852. return 'U';
  10853. }
  10854. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10855. {
  10856. return 'I';
  10857. }
  10858. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10859. {
  10860. return 'l';
  10861. }
  10862. // no check and assume int64_t (see note above)
  10863. return 'L';
  10864. }
  10865. case value_t::number_float:
  10866. return get_ubjson_float_prefix(j.m_value.number_float);
  10867. case value_t::string:
  10868. return 'S';
  10869. case value_t::array:
  10870. return '[';
  10871. case value_t::object:
  10872. return '{';
  10873. default: // discarded values
  10874. return 'N';
  10875. }
  10876. }
  10877. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  10878. {
  10879. return 'd'; // float 32
  10880. }
  10881. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  10882. {
  10883. return 'D'; // float 64
  10884. }
  10885. ///////////////////////
  10886. // Utility functions //
  10887. ///////////////////////
  10888. /*
  10889. @brief write a number to output input
  10890. @param[in] n number of type @a NumberType
  10891. @tparam NumberType the type of the number
  10892. @tparam OutputIsLittleEndian Set to true if output data is
  10893. required to be little endian
  10894. @note This function needs to respect the system's endianess, because bytes
  10895. in CBOR, MessagePack, and UBJSON are stored in network order (big
  10896. endian) and therefore need reordering on little endian systems.
  10897. */
  10898. template<typename NumberType, bool OutputIsLittleEndian = false>
  10899. void write_number(const NumberType n)
  10900. {
  10901. // step 1: write number to array of length NumberType
  10902. std::array<CharType, sizeof(NumberType)> vec;
  10903. std::memcpy(vec.data(), &n, sizeof(NumberType));
  10904. // step 2: write array to output (with possible reordering)
  10905. if (is_little_endian != OutputIsLittleEndian)
  10906. {
  10907. // reverse byte order prior to conversion if necessary
  10908. std::reverse(vec.begin(), vec.end());
  10909. }
  10910. oa->write_characters(vec.data(), sizeof(NumberType));
  10911. }
  10912. public:
  10913. // The following to_char_type functions are implement the conversion
  10914. // between uint8_t and CharType. In case CharType is not unsigned,
  10915. // such a conversion is required to allow values greater than 128.
  10916. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  10917. template < typename C = CharType,
  10918. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  10919. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10920. {
  10921. return *reinterpret_cast<char*>(&x);
  10922. }
  10923. template < typename C = CharType,
  10924. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  10925. static CharType to_char_type(std::uint8_t x) noexcept
  10926. {
  10927. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  10928. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  10929. CharType result;
  10930. std::memcpy(&result, &x, sizeof(x));
  10931. return result;
  10932. }
  10933. template<typename C = CharType,
  10934. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  10935. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10936. {
  10937. return x;
  10938. }
  10939. template < typename InputCharType, typename C = CharType,
  10940. enable_if_t <
  10941. std::is_signed<C>::value and
  10942. std::is_signed<char>::value and
  10943. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  10944. > * = nullptr >
  10945. static constexpr CharType to_char_type(InputCharType x) noexcept
  10946. {
  10947. return x;
  10948. }
  10949. private:
  10950. /// whether we can assume little endianess
  10951. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  10952. /// the output
  10953. output_adapter_t<CharType> oa = nullptr;
  10954. };
  10955. } // namespace detail
  10956. } // namespace nlohmann
  10957. // #include <nlohmann/detail/output/output_adapters.hpp>
  10958. // #include <nlohmann/detail/output/serializer.hpp>
  10959. #include <algorithm> // reverse, remove, fill, find, none_of
  10960. #include <array> // array
  10961. #include <cassert> // assert
  10962. #include <ciso646> // and, or
  10963. #include <clocale> // localeconv, lconv
  10964. #include <cmath> // labs, isfinite, isnan, signbit
  10965. #include <cstddef> // size_t, ptrdiff_t
  10966. #include <cstdint> // uint8_t
  10967. #include <cstdio> // snprintf
  10968. #include <limits> // numeric_limits
  10969. #include <string> // string
  10970. #include <type_traits> // is_same
  10971. #include <utility> // move
  10972. // #include <nlohmann/detail/conversions/to_chars.hpp>
  10973. #include <array> // array
  10974. #include <cassert> // assert
  10975. #include <ciso646> // or, and, not
  10976. #include <cmath> // signbit, isfinite
  10977. #include <cstdint> // intN_t, uintN_t
  10978. #include <cstring> // memcpy, memmove
  10979. #include <limits> // numeric_limits
  10980. #include <type_traits> // conditional
  10981. // #include <nlohmann/detail/macro_scope.hpp>
  10982. namespace nlohmann
  10983. {
  10984. namespace detail
  10985. {
  10986. /*!
  10987. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  10988. conversion.
  10989. This implementation is a slightly modified version of the reference
  10990. implementation which may be obtained from
  10991. http://florian.loitsch.com/publications (bench.tar.gz).
  10992. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  10993. For a detailed description of the algorithm see:
  10994. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  10995. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  10996. Language Design and Implementation, PLDI 2010
  10997. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  10998. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  10999. Design and Implementation, PLDI 1996
  11000. */
  11001. namespace dtoa_impl
  11002. {
  11003. template <typename Target, typename Source>
  11004. Target reinterpret_bits(const Source source)
  11005. {
  11006. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  11007. Target target;
  11008. std::memcpy(&target, &source, sizeof(Source));
  11009. return target;
  11010. }
  11011. struct diyfp // f * 2^e
  11012. {
  11013. static constexpr int kPrecision = 64; // = q
  11014. std::uint64_t f = 0;
  11015. int e = 0;
  11016. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  11017. /*!
  11018. @brief returns x - y
  11019. @pre x.e == y.e and x.f >= y.f
  11020. */
  11021. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  11022. {
  11023. assert(x.e == y.e);
  11024. assert(x.f >= y.f);
  11025. return {x.f - y.f, x.e};
  11026. }
  11027. /*!
  11028. @brief returns x * y
  11029. @note The result is rounded. (Only the upper q bits are returned.)
  11030. */
  11031. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  11032. {
  11033. static_assert(kPrecision == 64, "internal error");
  11034. // Computes:
  11035. // f = round((x.f * y.f) / 2^q)
  11036. // e = x.e + y.e + q
  11037. // Emulate the 64-bit * 64-bit multiplication:
  11038. //
  11039. // p = u * v
  11040. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  11041. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  11042. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  11043. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  11044. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  11045. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  11046. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  11047. //
  11048. // (Since Q might be larger than 2^32 - 1)
  11049. //
  11050. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  11051. //
  11052. // (Q_hi + H does not overflow a 64-bit int)
  11053. //
  11054. // = p_lo + 2^64 p_hi
  11055. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  11056. const std::uint64_t u_hi = x.f >> 32u;
  11057. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  11058. const std::uint64_t v_hi = y.f >> 32u;
  11059. const std::uint64_t p0 = u_lo * v_lo;
  11060. const std::uint64_t p1 = u_lo * v_hi;
  11061. const std::uint64_t p2 = u_hi * v_lo;
  11062. const std::uint64_t p3 = u_hi * v_hi;
  11063. const std::uint64_t p0_hi = p0 >> 32u;
  11064. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  11065. const std::uint64_t p1_hi = p1 >> 32u;
  11066. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  11067. const std::uint64_t p2_hi = p2 >> 32u;
  11068. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  11069. // The full product might now be computed as
  11070. //
  11071. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  11072. // p_lo = p0_lo + (Q << 32)
  11073. //
  11074. // But in this particular case here, the full p_lo is not required.
  11075. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  11076. // Q_hi + 1 does not overflow).
  11077. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  11078. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  11079. return {h, x.e + y.e + 64};
  11080. }
  11081. /*!
  11082. @brief normalize x such that the significand is >= 2^(q-1)
  11083. @pre x.f != 0
  11084. */
  11085. static diyfp normalize(diyfp x) noexcept
  11086. {
  11087. assert(x.f != 0);
  11088. while ((x.f >> 63u) == 0)
  11089. {
  11090. x.f <<= 1u;
  11091. x.e--;
  11092. }
  11093. return x;
  11094. }
  11095. /*!
  11096. @brief normalize x such that the result has the exponent E
  11097. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  11098. */
  11099. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  11100. {
  11101. const int delta = x.e - target_exponent;
  11102. assert(delta >= 0);
  11103. assert(((x.f << delta) >> delta) == x.f);
  11104. return {x.f << delta, target_exponent};
  11105. }
  11106. };
  11107. struct boundaries
  11108. {
  11109. diyfp w;
  11110. diyfp minus;
  11111. diyfp plus;
  11112. };
  11113. /*!
  11114. Compute the (normalized) diyfp representing the input number 'value' and its
  11115. boundaries.
  11116. @pre value must be finite and positive
  11117. */
  11118. template <typename FloatType>
  11119. boundaries compute_boundaries(FloatType value)
  11120. {
  11121. assert(std::isfinite(value));
  11122. assert(value > 0);
  11123. // Convert the IEEE representation into a diyfp.
  11124. //
  11125. // If v is denormal:
  11126. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  11127. // If v is normalized:
  11128. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  11129. static_assert(std::numeric_limits<FloatType>::is_iec559,
  11130. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  11131. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  11132. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  11133. constexpr int kMinExp = 1 - kBias;
  11134. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  11135. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  11136. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  11137. const std::uint64_t E = bits >> (kPrecision - 1);
  11138. const std::uint64_t F = bits & (kHiddenBit - 1);
  11139. const bool is_denormal = E == 0;
  11140. const diyfp v = is_denormal
  11141. ? diyfp(F, kMinExp)
  11142. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  11143. // Compute the boundaries m- and m+ of the floating-point value
  11144. // v = f * 2^e.
  11145. //
  11146. // Determine v- and v+, the floating-point predecessor and successor if v,
  11147. // respectively.
  11148. //
  11149. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  11150. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  11151. //
  11152. // v+ = v + 2^e
  11153. //
  11154. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  11155. // between m- and m+ round to v, regardless of how the input rounding
  11156. // algorithm breaks ties.
  11157. //
  11158. // ---+-------------+-------------+-------------+-------------+--- (A)
  11159. // v- m- v m+ v+
  11160. //
  11161. // -----------------+------+------+-------------+-------------+--- (B)
  11162. // v- m- v m+ v+
  11163. const bool lower_boundary_is_closer = F == 0 and E > 1;
  11164. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  11165. const diyfp m_minus = lower_boundary_is_closer
  11166. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  11167. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  11168. // Determine the normalized w+ = m+.
  11169. const diyfp w_plus = diyfp::normalize(m_plus);
  11170. // Determine w- = m- such that e_(w-) = e_(w+).
  11171. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  11172. return {diyfp::normalize(v), w_minus, w_plus};
  11173. }
  11174. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  11175. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  11176. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  11177. //
  11178. // alpha <= e = e_c + e_w + q <= gamma
  11179. //
  11180. // or
  11181. //
  11182. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  11183. // <= f_c * f_w * 2^gamma
  11184. //
  11185. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  11186. //
  11187. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  11188. //
  11189. // or
  11190. //
  11191. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  11192. //
  11193. // The choice of (alpha,gamma) determines the size of the table and the form of
  11194. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  11195. // in practice:
  11196. //
  11197. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  11198. // processed independently: An integral part p1, and a fractional part p2:
  11199. //
  11200. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  11201. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  11202. // = p1 + p2 * 2^e
  11203. //
  11204. // The conversion of p1 into decimal form requires a series of divisions and
  11205. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  11206. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  11207. // achieved by choosing
  11208. //
  11209. // -e >= 32 or e <= -32 := gamma
  11210. //
  11211. // In order to convert the fractional part
  11212. //
  11213. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11214. //
  11215. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  11216. // d[-i] are extracted in order:
  11217. //
  11218. // (10 * p2) div 2^-e = d[-1]
  11219. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  11220. //
  11221. // The multiplication by 10 must not overflow. It is sufficient to choose
  11222. //
  11223. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  11224. //
  11225. // Since p2 = f mod 2^-e < 2^-e,
  11226. //
  11227. // -e <= 60 or e >= -60 := alpha
  11228. constexpr int kAlpha = -60;
  11229. constexpr int kGamma = -32;
  11230. struct cached_power // c = f * 2^e ~= 10^k
  11231. {
  11232. std::uint64_t f;
  11233. int e;
  11234. int k;
  11235. };
  11236. /*!
  11237. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  11238. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  11239. satisfies (Definition 3.2 from [1])
  11240. alpha <= e_c + e + q <= gamma.
  11241. */
  11242. inline cached_power get_cached_power_for_binary_exponent(int e)
  11243. {
  11244. // Now
  11245. //
  11246. // alpha <= e_c + e + q <= gamma (1)
  11247. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  11248. //
  11249. // and since the c's are normalized, 2^(q-1) <= f_c,
  11250. //
  11251. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  11252. // ==> 2^(alpha - e - 1) <= c
  11253. //
  11254. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  11255. //
  11256. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  11257. // = ceil( (alpha - e - 1) * log_10(2) )
  11258. //
  11259. // From the paper:
  11260. // "In theory the result of the procedure could be wrong since c is rounded,
  11261. // and the computation itself is approximated [...]. In practice, however,
  11262. // this simple function is sufficient."
  11263. //
  11264. // For IEEE double precision floating-point numbers converted into
  11265. // normalized diyfp's w = f * 2^e, with q = 64,
  11266. //
  11267. // e >= -1022 (min IEEE exponent)
  11268. // -52 (p - 1)
  11269. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  11270. // -11 (normalize the diyfp)
  11271. // = -1137
  11272. //
  11273. // and
  11274. //
  11275. // e <= +1023 (max IEEE exponent)
  11276. // -52 (p - 1)
  11277. // -11 (normalize the diyfp)
  11278. // = 960
  11279. //
  11280. // This binary exponent range [-1137,960] results in a decimal exponent
  11281. // range [-307,324]. One does not need to store a cached power for each
  11282. // k in this range. For each such k it suffices to find a cached power
  11283. // such that the exponent of the product lies in [alpha,gamma].
  11284. // This implies that the difference of the decimal exponents of adjacent
  11285. // table entries must be less than or equal to
  11286. //
  11287. // floor( (gamma - alpha) * log_10(2) ) = 8.
  11288. //
  11289. // (A smaller distance gamma-alpha would require a larger table.)
  11290. // NB:
  11291. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  11292. constexpr int kCachedPowersMinDecExp = -300;
  11293. constexpr int kCachedPowersDecStep = 8;
  11294. static constexpr std::array<cached_power, 79> kCachedPowers =
  11295. {
  11296. {
  11297. { 0xAB70FE17C79AC6CA, -1060, -300 },
  11298. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  11299. { 0xBE5691EF416BD60C, -1007, -284 },
  11300. { 0x8DD01FAD907FFC3C, -980, -276 },
  11301. { 0xD3515C2831559A83, -954, -268 },
  11302. { 0x9D71AC8FADA6C9B5, -927, -260 },
  11303. { 0xEA9C227723EE8BCB, -901, -252 },
  11304. { 0xAECC49914078536D, -874, -244 },
  11305. { 0x823C12795DB6CE57, -847, -236 },
  11306. { 0xC21094364DFB5637, -821, -228 },
  11307. { 0x9096EA6F3848984F, -794, -220 },
  11308. { 0xD77485CB25823AC7, -768, -212 },
  11309. { 0xA086CFCD97BF97F4, -741, -204 },
  11310. { 0xEF340A98172AACE5, -715, -196 },
  11311. { 0xB23867FB2A35B28E, -688, -188 },
  11312. { 0x84C8D4DFD2C63F3B, -661, -180 },
  11313. { 0xC5DD44271AD3CDBA, -635, -172 },
  11314. { 0x936B9FCEBB25C996, -608, -164 },
  11315. { 0xDBAC6C247D62A584, -582, -156 },
  11316. { 0xA3AB66580D5FDAF6, -555, -148 },
  11317. { 0xF3E2F893DEC3F126, -529, -140 },
  11318. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  11319. { 0x87625F056C7C4A8B, -475, -124 },
  11320. { 0xC9BCFF6034C13053, -449, -116 },
  11321. { 0x964E858C91BA2655, -422, -108 },
  11322. { 0xDFF9772470297EBD, -396, -100 },
  11323. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  11324. { 0xF8A95FCF88747D94, -343, -84 },
  11325. { 0xB94470938FA89BCF, -316, -76 },
  11326. { 0x8A08F0F8BF0F156B, -289, -68 },
  11327. { 0xCDB02555653131B6, -263, -60 },
  11328. { 0x993FE2C6D07B7FAC, -236, -52 },
  11329. { 0xE45C10C42A2B3B06, -210, -44 },
  11330. { 0xAA242499697392D3, -183, -36 },
  11331. { 0xFD87B5F28300CA0E, -157, -28 },
  11332. { 0xBCE5086492111AEB, -130, -20 },
  11333. { 0x8CBCCC096F5088CC, -103, -12 },
  11334. { 0xD1B71758E219652C, -77, -4 },
  11335. { 0x9C40000000000000, -50, 4 },
  11336. { 0xE8D4A51000000000, -24, 12 },
  11337. { 0xAD78EBC5AC620000, 3, 20 },
  11338. { 0x813F3978F8940984, 30, 28 },
  11339. { 0xC097CE7BC90715B3, 56, 36 },
  11340. { 0x8F7E32CE7BEA5C70, 83, 44 },
  11341. { 0xD5D238A4ABE98068, 109, 52 },
  11342. { 0x9F4F2726179A2245, 136, 60 },
  11343. { 0xED63A231D4C4FB27, 162, 68 },
  11344. { 0xB0DE65388CC8ADA8, 189, 76 },
  11345. { 0x83C7088E1AAB65DB, 216, 84 },
  11346. { 0xC45D1DF942711D9A, 242, 92 },
  11347. { 0x924D692CA61BE758, 269, 100 },
  11348. { 0xDA01EE641A708DEA, 295, 108 },
  11349. { 0xA26DA3999AEF774A, 322, 116 },
  11350. { 0xF209787BB47D6B85, 348, 124 },
  11351. { 0xB454E4A179DD1877, 375, 132 },
  11352. { 0x865B86925B9BC5C2, 402, 140 },
  11353. { 0xC83553C5C8965D3D, 428, 148 },
  11354. { 0x952AB45CFA97A0B3, 455, 156 },
  11355. { 0xDE469FBD99A05FE3, 481, 164 },
  11356. { 0xA59BC234DB398C25, 508, 172 },
  11357. { 0xF6C69A72A3989F5C, 534, 180 },
  11358. { 0xB7DCBF5354E9BECE, 561, 188 },
  11359. { 0x88FCF317F22241E2, 588, 196 },
  11360. { 0xCC20CE9BD35C78A5, 614, 204 },
  11361. { 0x98165AF37B2153DF, 641, 212 },
  11362. { 0xE2A0B5DC971F303A, 667, 220 },
  11363. { 0xA8D9D1535CE3B396, 694, 228 },
  11364. { 0xFB9B7CD9A4A7443C, 720, 236 },
  11365. { 0xBB764C4CA7A44410, 747, 244 },
  11366. { 0x8BAB8EEFB6409C1A, 774, 252 },
  11367. { 0xD01FEF10A657842C, 800, 260 },
  11368. { 0x9B10A4E5E9913129, 827, 268 },
  11369. { 0xE7109BFBA19C0C9D, 853, 276 },
  11370. { 0xAC2820D9623BF429, 880, 284 },
  11371. { 0x80444B5E7AA7CF85, 907, 292 },
  11372. { 0xBF21E44003ACDD2D, 933, 300 },
  11373. { 0x8E679C2F5E44FF8F, 960, 308 },
  11374. { 0xD433179D9C8CB841, 986, 316 },
  11375. { 0x9E19DB92B4E31BA9, 1013, 324 },
  11376. }
  11377. };
  11378. // This computation gives exactly the same results for k as
  11379. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  11380. // for |e| <= 1500, but doesn't require floating-point operations.
  11381. // NB: log_10(2) ~= 78913 / 2^18
  11382. assert(e >= -1500);
  11383. assert(e <= 1500);
  11384. const int f = kAlpha - e - 1;
  11385. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  11386. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  11387. assert(index >= 0);
  11388. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  11389. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  11390. assert(kAlpha <= cached.e + e + 64);
  11391. assert(kGamma >= cached.e + e + 64);
  11392. return cached;
  11393. }
  11394. /*!
  11395. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  11396. For n == 0, returns 1 and sets pow10 := 1.
  11397. */
  11398. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  11399. {
  11400. // LCOV_EXCL_START
  11401. if (n >= 1000000000)
  11402. {
  11403. pow10 = 1000000000;
  11404. return 10;
  11405. }
  11406. // LCOV_EXCL_STOP
  11407. else if (n >= 100000000)
  11408. {
  11409. pow10 = 100000000;
  11410. return 9;
  11411. }
  11412. else if (n >= 10000000)
  11413. {
  11414. pow10 = 10000000;
  11415. return 8;
  11416. }
  11417. else if (n >= 1000000)
  11418. {
  11419. pow10 = 1000000;
  11420. return 7;
  11421. }
  11422. else if (n >= 100000)
  11423. {
  11424. pow10 = 100000;
  11425. return 6;
  11426. }
  11427. else if (n >= 10000)
  11428. {
  11429. pow10 = 10000;
  11430. return 5;
  11431. }
  11432. else if (n >= 1000)
  11433. {
  11434. pow10 = 1000;
  11435. return 4;
  11436. }
  11437. else if (n >= 100)
  11438. {
  11439. pow10 = 100;
  11440. return 3;
  11441. }
  11442. else if (n >= 10)
  11443. {
  11444. pow10 = 10;
  11445. return 2;
  11446. }
  11447. else
  11448. {
  11449. pow10 = 1;
  11450. return 1;
  11451. }
  11452. }
  11453. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  11454. std::uint64_t rest, std::uint64_t ten_k)
  11455. {
  11456. assert(len >= 1);
  11457. assert(dist <= delta);
  11458. assert(rest <= delta);
  11459. assert(ten_k > 0);
  11460. // <--------------------------- delta ---->
  11461. // <---- dist --------->
  11462. // --------------[------------------+-------------------]--------------
  11463. // M- w M+
  11464. //
  11465. // ten_k
  11466. // <------>
  11467. // <---- rest ---->
  11468. // --------------[------------------+----+--------------]--------------
  11469. // w V
  11470. // = buf * 10^k
  11471. //
  11472. // ten_k represents a unit-in-the-last-place in the decimal representation
  11473. // stored in buf.
  11474. // Decrement buf by ten_k while this takes buf closer to w.
  11475. // The tests are written in this order to avoid overflow in unsigned
  11476. // integer arithmetic.
  11477. while (rest < dist
  11478. and delta - rest >= ten_k
  11479. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  11480. {
  11481. assert(buf[len - 1] != '0');
  11482. buf[len - 1]--;
  11483. rest += ten_k;
  11484. }
  11485. }
  11486. /*!
  11487. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  11488. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  11489. */
  11490. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  11491. diyfp M_minus, diyfp w, diyfp M_plus)
  11492. {
  11493. static_assert(kAlpha >= -60, "internal error");
  11494. static_assert(kGamma <= -32, "internal error");
  11495. // Generates the digits (and the exponent) of a decimal floating-point
  11496. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  11497. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  11498. //
  11499. // <--------------------------- delta ---->
  11500. // <---- dist --------->
  11501. // --------------[------------------+-------------------]--------------
  11502. // M- w M+
  11503. //
  11504. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  11505. // V is in [M-,M+].
  11506. assert(M_plus.e >= kAlpha);
  11507. assert(M_plus.e <= kGamma);
  11508. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  11509. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  11510. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  11511. //
  11512. // M+ = f * 2^e
  11513. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  11514. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  11515. // = p1 + p2 * 2^e
  11516. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  11517. 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.)
  11518. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  11519. // 1)
  11520. //
  11521. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  11522. assert(p1 > 0);
  11523. std::uint32_t pow10;
  11524. const int k = find_largest_pow10(p1, pow10);
  11525. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  11526. //
  11527. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  11528. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  11529. //
  11530. // M+ = p1 + p2 * 2^e
  11531. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  11532. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  11533. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  11534. //
  11535. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  11536. //
  11537. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  11538. //
  11539. // but stop as soon as
  11540. //
  11541. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  11542. int n = k;
  11543. while (n > 0)
  11544. {
  11545. // Invariants:
  11546. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  11547. // pow10 = 10^(n-1) <= p1 < 10^n
  11548. //
  11549. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  11550. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  11551. //
  11552. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  11553. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  11554. //
  11555. assert(d <= 9);
  11556. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11557. //
  11558. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  11559. //
  11560. p1 = r;
  11561. n--;
  11562. //
  11563. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  11564. // pow10 = 10^n
  11565. //
  11566. // Now check if enough digits have been generated.
  11567. // Compute
  11568. //
  11569. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  11570. //
  11571. // Note:
  11572. // Since rest and delta share the same exponent e, it suffices to
  11573. // compare the significands.
  11574. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  11575. if (rest <= delta)
  11576. {
  11577. // V = buffer * 10^n, with M- <= V <= M+.
  11578. decimal_exponent += n;
  11579. // We may now just stop. But instead look if the buffer could be
  11580. // decremented to bring V closer to w.
  11581. //
  11582. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  11583. // The rounding procedure works with diyfp's with an implicit
  11584. // exponent of e.
  11585. //
  11586. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  11587. //
  11588. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  11589. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  11590. return;
  11591. }
  11592. pow10 /= 10;
  11593. //
  11594. // pow10 = 10^(n-1) <= p1 < 10^n
  11595. // Invariants restored.
  11596. }
  11597. // 2)
  11598. //
  11599. // The digits of the integral part have been generated:
  11600. //
  11601. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  11602. // = buffer + p2 * 2^e
  11603. //
  11604. // Now generate the digits of the fractional part p2 * 2^e.
  11605. //
  11606. // Note:
  11607. // No decimal point is generated: the exponent is adjusted instead.
  11608. //
  11609. // p2 actually represents the fraction
  11610. //
  11611. // p2 * 2^e
  11612. // = p2 / 2^-e
  11613. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11614. //
  11615. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  11616. //
  11617. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  11618. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  11619. //
  11620. // using
  11621. //
  11622. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  11623. // = ( d) * 2^-e + ( r)
  11624. //
  11625. // or
  11626. // 10^m * p2 * 2^e = d + r * 2^e
  11627. //
  11628. // i.e.
  11629. //
  11630. // M+ = buffer + p2 * 2^e
  11631. // = buffer + 10^-m * (d + r * 2^e)
  11632. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  11633. //
  11634. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  11635. assert(p2 > delta);
  11636. int m = 0;
  11637. for (;;)
  11638. {
  11639. // Invariant:
  11640. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  11641. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  11642. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  11643. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  11644. //
  11645. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  11646. p2 *= 10;
  11647. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  11648. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  11649. //
  11650. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  11651. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  11652. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11653. //
  11654. assert(d <= 9);
  11655. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11656. //
  11657. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11658. //
  11659. p2 = r;
  11660. m++;
  11661. //
  11662. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  11663. // Invariant restored.
  11664. // Check if enough digits have been generated.
  11665. //
  11666. // 10^-m * p2 * 2^e <= delta * 2^e
  11667. // p2 * 2^e <= 10^m * delta * 2^e
  11668. // p2 <= 10^m * delta
  11669. delta *= 10;
  11670. dist *= 10;
  11671. if (p2 <= delta)
  11672. {
  11673. break;
  11674. }
  11675. }
  11676. // V = buffer * 10^-m, with M- <= V <= M+.
  11677. decimal_exponent -= m;
  11678. // 1 ulp in the decimal representation is now 10^-m.
  11679. // Since delta and dist are now scaled by 10^m, we need to do the
  11680. // same with ulp in order to keep the units in sync.
  11681. //
  11682. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  11683. //
  11684. const std::uint64_t ten_m = one.f;
  11685. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  11686. // By construction this algorithm generates the shortest possible decimal
  11687. // number (Loitsch, Theorem 6.2) which rounds back to w.
  11688. // For an input number of precision p, at least
  11689. //
  11690. // N = 1 + ceil(p * log_10(2))
  11691. //
  11692. // decimal digits are sufficient to identify all binary floating-point
  11693. // numbers (Matula, "In-and-Out conversions").
  11694. // This implies that the algorithm does not produce more than N decimal
  11695. // digits.
  11696. //
  11697. // N = 17 for p = 53 (IEEE double precision)
  11698. // N = 9 for p = 24 (IEEE single precision)
  11699. }
  11700. /*!
  11701. v = buf * 10^decimal_exponent
  11702. len is the length of the buffer (number of decimal digits)
  11703. The buffer must be large enough, i.e. >= max_digits10.
  11704. */
  11705. JSON_HEDLEY_NON_NULL(1)
  11706. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  11707. diyfp m_minus, diyfp v, diyfp m_plus)
  11708. {
  11709. assert(m_plus.e == m_minus.e);
  11710. assert(m_plus.e == v.e);
  11711. // --------(-----------------------+-----------------------)-------- (A)
  11712. // m- v m+
  11713. //
  11714. // --------------------(-----------+-----------------------)-------- (B)
  11715. // m- v m+
  11716. //
  11717. // First scale v (and m- and m+) such that the exponent is in the range
  11718. // [alpha, gamma].
  11719. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  11720. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  11721. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  11722. const diyfp w = diyfp::mul(v, c_minus_k);
  11723. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  11724. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  11725. // ----(---+---)---------------(---+---)---------------(---+---)----
  11726. // w- w w+
  11727. // = c*m- = c*v = c*m+
  11728. //
  11729. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  11730. // w+ are now off by a small amount.
  11731. // In fact:
  11732. //
  11733. // w - v * 10^k < 1 ulp
  11734. //
  11735. // To account for this inaccuracy, add resp. subtract 1 ulp.
  11736. //
  11737. // --------+---[---------------(---+---)---------------]---+--------
  11738. // w- M- w M+ w+
  11739. //
  11740. // Now any number in [M-, M+] (bounds included) will round to w when input,
  11741. // regardless of how the input rounding algorithm breaks ties.
  11742. //
  11743. // And digit_gen generates the shortest possible such number in [M-, M+].
  11744. // Note that this does not mean that Grisu2 always generates the shortest
  11745. // possible number in the interval (m-, m+).
  11746. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  11747. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  11748. decimal_exponent = -cached.k; // = -(-k) = k
  11749. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  11750. }
  11751. /*!
  11752. v = buf * 10^decimal_exponent
  11753. len is the length of the buffer (number of decimal digits)
  11754. The buffer must be large enough, i.e. >= max_digits10.
  11755. */
  11756. template <typename FloatType>
  11757. JSON_HEDLEY_NON_NULL(1)
  11758. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  11759. {
  11760. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  11761. "internal error: not enough precision");
  11762. assert(std::isfinite(value));
  11763. assert(value > 0);
  11764. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  11765. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  11766. // decimal representations are not exactly "short".
  11767. //
  11768. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  11769. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  11770. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  11771. // does.
  11772. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  11773. // representation using the corresponding std::from_chars function recovers value exactly". That
  11774. // indicates that single precision floating-point numbers should be recovered using
  11775. // 'std::strtof'.
  11776. //
  11777. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  11778. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  11779. // value is off by 1 ulp.
  11780. #if 0
  11781. const boundaries w = compute_boundaries(static_cast<double>(value));
  11782. #else
  11783. const boundaries w = compute_boundaries(value);
  11784. #endif
  11785. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  11786. }
  11787. /*!
  11788. @brief appends a decimal representation of e to buf
  11789. @return a pointer to the element following the exponent.
  11790. @pre -1000 < e < 1000
  11791. */
  11792. JSON_HEDLEY_NON_NULL(1)
  11793. JSON_HEDLEY_RETURNS_NON_NULL
  11794. inline char* append_exponent(char* buf, int e)
  11795. {
  11796. assert(e > -1000);
  11797. assert(e < 1000);
  11798. if (e < 0)
  11799. {
  11800. e = -e;
  11801. *buf++ = '-';
  11802. }
  11803. else
  11804. {
  11805. *buf++ = '+';
  11806. }
  11807. auto k = static_cast<std::uint32_t>(e);
  11808. if (k < 10)
  11809. {
  11810. // Always print at least two digits in the exponent.
  11811. // This is for compatibility with printf("%g").
  11812. *buf++ = '0';
  11813. *buf++ = static_cast<char>('0' + k);
  11814. }
  11815. else if (k < 100)
  11816. {
  11817. *buf++ = static_cast<char>('0' + k / 10);
  11818. k %= 10;
  11819. *buf++ = static_cast<char>('0' + k);
  11820. }
  11821. else
  11822. {
  11823. *buf++ = static_cast<char>('0' + k / 100);
  11824. k %= 100;
  11825. *buf++ = static_cast<char>('0' + k / 10);
  11826. k %= 10;
  11827. *buf++ = static_cast<char>('0' + k);
  11828. }
  11829. return buf;
  11830. }
  11831. /*!
  11832. @brief prettify v = buf * 10^decimal_exponent
  11833. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  11834. notation. Otherwise it will be printed in exponential notation.
  11835. @pre min_exp < 0
  11836. @pre max_exp > 0
  11837. */
  11838. JSON_HEDLEY_NON_NULL(1)
  11839. JSON_HEDLEY_RETURNS_NON_NULL
  11840. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  11841. int min_exp, int max_exp)
  11842. {
  11843. assert(min_exp < 0);
  11844. assert(max_exp > 0);
  11845. const int k = len;
  11846. const int n = len + decimal_exponent;
  11847. // v = buf * 10^(n-k)
  11848. // k is the length of the buffer (number of decimal digits)
  11849. // n is the position of the decimal point relative to the start of the buffer.
  11850. if (k <= n and n <= max_exp)
  11851. {
  11852. // digits[000]
  11853. // len <= max_exp + 2
  11854. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  11855. // Make it look like a floating-point number (#362, #378)
  11856. buf[n + 0] = '.';
  11857. buf[n + 1] = '0';
  11858. return buf + (n + 2);
  11859. }
  11860. if (0 < n and n <= max_exp)
  11861. {
  11862. // dig.its
  11863. // len <= max_digits10 + 1
  11864. assert(k > n);
  11865. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  11866. buf[n] = '.';
  11867. return buf + (k + 1);
  11868. }
  11869. if (min_exp < n and n <= 0)
  11870. {
  11871. // 0.[000]digits
  11872. // len <= 2 + (-min_exp - 1) + max_digits10
  11873. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  11874. buf[0] = '0';
  11875. buf[1] = '.';
  11876. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  11877. return buf + (2 + (-n) + k);
  11878. }
  11879. if (k == 1)
  11880. {
  11881. // dE+123
  11882. // len <= 1 + 5
  11883. buf += 1;
  11884. }
  11885. else
  11886. {
  11887. // d.igitsE+123
  11888. // len <= max_digits10 + 1 + 5
  11889. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  11890. buf[1] = '.';
  11891. buf += 1 + k;
  11892. }
  11893. *buf++ = 'e';
  11894. return append_exponent(buf, n - 1);
  11895. }
  11896. } // namespace dtoa_impl
  11897. /*!
  11898. @brief generates a decimal representation of the floating-point number value in [first, last).
  11899. The format of the resulting decimal representation is similar to printf's %g
  11900. format. Returns an iterator pointing past-the-end of the decimal representation.
  11901. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  11902. @note The buffer must be large enough.
  11903. @note The result is NOT null-terminated.
  11904. */
  11905. template <typename FloatType>
  11906. JSON_HEDLEY_NON_NULL(1, 2)
  11907. JSON_HEDLEY_RETURNS_NON_NULL
  11908. char* to_chars(char* first, const char* last, FloatType value)
  11909. {
  11910. static_cast<void>(last); // maybe unused - fix warning
  11911. assert(std::isfinite(value));
  11912. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  11913. if (std::signbit(value))
  11914. {
  11915. value = -value;
  11916. *first++ = '-';
  11917. }
  11918. if (value == 0) // +-0
  11919. {
  11920. *first++ = '0';
  11921. // Make it look like a floating-point number (#362, #378)
  11922. *first++ = '.';
  11923. *first++ = '0';
  11924. return first;
  11925. }
  11926. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  11927. // Compute v = buffer * 10^decimal_exponent.
  11928. // The decimal digits are stored in the buffer, which needs to be interpreted
  11929. // as an unsigned decimal integer.
  11930. // len is the length of the buffer, i.e. the number of decimal digits.
  11931. int len = 0;
  11932. int decimal_exponent = 0;
  11933. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  11934. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  11935. // Format the buffer like printf("%.*g", prec, value)
  11936. constexpr int kMinExp = -4;
  11937. // Use digits10 here to increase compatibility with version 2.
  11938. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  11939. assert(last - first >= kMaxExp + 2);
  11940. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  11941. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  11942. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  11943. }
  11944. } // namespace detail
  11945. } // namespace nlohmann
  11946. // #include <nlohmann/detail/exceptions.hpp>
  11947. // #include <nlohmann/detail/macro_scope.hpp>
  11948. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11949. // #include <nlohmann/detail/output/binary_writer.hpp>
  11950. // #include <nlohmann/detail/output/output_adapters.hpp>
  11951. // #include <nlohmann/detail/value_t.hpp>
  11952. namespace nlohmann
  11953. {
  11954. namespace detail
  11955. {
  11956. ///////////////////
  11957. // serialization //
  11958. ///////////////////
  11959. /// how to treat decoding errors
  11960. enum class error_handler_t
  11961. {
  11962. strict, ///< throw a type_error exception in case of invalid UTF-8
  11963. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  11964. ignore ///< ignore invalid UTF-8 sequences
  11965. };
  11966. template<typename BasicJsonType>
  11967. class serializer
  11968. {
  11969. using string_t = typename BasicJsonType::string_t;
  11970. using number_float_t = typename BasicJsonType::number_float_t;
  11971. using number_integer_t = typename BasicJsonType::number_integer_t;
  11972. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  11973. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  11974. static constexpr std::uint8_t UTF8_REJECT = 1;
  11975. public:
  11976. /*!
  11977. @param[in] s output stream to serialize to
  11978. @param[in] ichar indentation character to use
  11979. @param[in] error_handler_ how to react on decoding errors
  11980. */
  11981. serializer(output_adapter_t<char> s, const char ichar,
  11982. error_handler_t error_handler_ = error_handler_t::strict)
  11983. : o(std::move(s))
  11984. , loc(std::localeconv())
  11985. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  11986. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  11987. , indent_char(ichar)
  11988. , indent_string(512, indent_char)
  11989. , error_handler(error_handler_)
  11990. {}
  11991. // delete because of pointer members
  11992. serializer(const serializer&) = delete;
  11993. serializer& operator=(const serializer&) = delete;
  11994. serializer(serializer&&) = delete;
  11995. serializer& operator=(serializer&&) = delete;
  11996. ~serializer() = default;
  11997. /*!
  11998. @brief internal implementation of the serialization function
  11999. This function is called by the public member function dump and organizes
  12000. the serialization internally. The indentation level is propagated as
  12001. additional parameter. In case of arrays and objects, the function is
  12002. called recursively.
  12003. - strings and object keys are escaped using `escape_string()`
  12004. - integer numbers are converted implicitly via `operator<<`
  12005. - floating-point numbers are converted to a string using `"%g"` format
  12006. @param[in] val value to serialize
  12007. @param[in] pretty_print whether the output shall be pretty-printed
  12008. @param[in] indent_step the indent level
  12009. @param[in] current_indent the current indent level (only used internally)
  12010. */
  12011. void dump(const BasicJsonType& val, const bool pretty_print,
  12012. const bool ensure_ascii,
  12013. const unsigned int indent_step,
  12014. const unsigned int current_indent = 0)
  12015. {
  12016. switch (val.m_type)
  12017. {
  12018. case value_t::object:
  12019. {
  12020. if (val.m_value.object->empty())
  12021. {
  12022. o->write_characters("{}", 2);
  12023. return;
  12024. }
  12025. if (pretty_print)
  12026. {
  12027. o->write_characters("{\n", 2);
  12028. // variable to hold indentation for recursive calls
  12029. const auto new_indent = current_indent + indent_step;
  12030. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12031. {
  12032. indent_string.resize(indent_string.size() * 2, ' ');
  12033. }
  12034. // first n-1 elements
  12035. auto i = val.m_value.object->cbegin();
  12036. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12037. {
  12038. o->write_characters(indent_string.c_str(), new_indent);
  12039. o->write_character('\"');
  12040. dump_escaped(i->first, ensure_ascii);
  12041. o->write_characters("\": ", 3);
  12042. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  12043. o->write_characters(",\n", 2);
  12044. }
  12045. // last element
  12046. assert(i != val.m_value.object->cend());
  12047. assert(std::next(i) == val.m_value.object->cend());
  12048. o->write_characters(indent_string.c_str(), new_indent);
  12049. o->write_character('\"');
  12050. dump_escaped(i->first, ensure_ascii);
  12051. o->write_characters("\": ", 3);
  12052. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  12053. o->write_character('\n');
  12054. o->write_characters(indent_string.c_str(), current_indent);
  12055. o->write_character('}');
  12056. }
  12057. else
  12058. {
  12059. o->write_character('{');
  12060. // first n-1 elements
  12061. auto i = val.m_value.object->cbegin();
  12062. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12063. {
  12064. o->write_character('\"');
  12065. dump_escaped(i->first, ensure_ascii);
  12066. o->write_characters("\":", 2);
  12067. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  12068. o->write_character(',');
  12069. }
  12070. // last element
  12071. assert(i != val.m_value.object->cend());
  12072. assert(std::next(i) == val.m_value.object->cend());
  12073. o->write_character('\"');
  12074. dump_escaped(i->first, ensure_ascii);
  12075. o->write_characters("\":", 2);
  12076. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  12077. o->write_character('}');
  12078. }
  12079. return;
  12080. }
  12081. case value_t::array:
  12082. {
  12083. if (val.m_value.array->empty())
  12084. {
  12085. o->write_characters("[]", 2);
  12086. return;
  12087. }
  12088. if (pretty_print)
  12089. {
  12090. o->write_characters("[\n", 2);
  12091. // variable to hold indentation for recursive calls
  12092. const auto new_indent = current_indent + indent_step;
  12093. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12094. {
  12095. indent_string.resize(indent_string.size() * 2, ' ');
  12096. }
  12097. // first n-1 elements
  12098. for (auto i = val.m_value.array->cbegin();
  12099. i != val.m_value.array->cend() - 1; ++i)
  12100. {
  12101. o->write_characters(indent_string.c_str(), new_indent);
  12102. dump(*i, true, ensure_ascii, indent_step, new_indent);
  12103. o->write_characters(",\n", 2);
  12104. }
  12105. // last element
  12106. assert(not val.m_value.array->empty());
  12107. o->write_characters(indent_string.c_str(), new_indent);
  12108. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  12109. o->write_character('\n');
  12110. o->write_characters(indent_string.c_str(), current_indent);
  12111. o->write_character(']');
  12112. }
  12113. else
  12114. {
  12115. o->write_character('[');
  12116. // first n-1 elements
  12117. for (auto i = val.m_value.array->cbegin();
  12118. i != val.m_value.array->cend() - 1; ++i)
  12119. {
  12120. dump(*i, false, ensure_ascii, indent_step, current_indent);
  12121. o->write_character(',');
  12122. }
  12123. // last element
  12124. assert(not val.m_value.array->empty());
  12125. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  12126. o->write_character(']');
  12127. }
  12128. return;
  12129. }
  12130. case value_t::string:
  12131. {
  12132. o->write_character('\"');
  12133. dump_escaped(*val.m_value.string, ensure_ascii);
  12134. o->write_character('\"');
  12135. return;
  12136. }
  12137. case value_t::boolean:
  12138. {
  12139. if (val.m_value.boolean)
  12140. {
  12141. o->write_characters("true", 4);
  12142. }
  12143. else
  12144. {
  12145. o->write_characters("false", 5);
  12146. }
  12147. return;
  12148. }
  12149. case value_t::number_integer:
  12150. {
  12151. dump_integer(val.m_value.number_integer);
  12152. return;
  12153. }
  12154. case value_t::number_unsigned:
  12155. {
  12156. dump_integer(val.m_value.number_unsigned);
  12157. return;
  12158. }
  12159. case value_t::number_float:
  12160. {
  12161. dump_float(val.m_value.number_float);
  12162. return;
  12163. }
  12164. case value_t::discarded:
  12165. {
  12166. o->write_characters("<discarded>", 11);
  12167. return;
  12168. }
  12169. case value_t::null:
  12170. {
  12171. o->write_characters("null", 4);
  12172. return;
  12173. }
  12174. default: // LCOV_EXCL_LINE
  12175. assert(false); // LCOV_EXCL_LINE
  12176. }
  12177. }
  12178. private:
  12179. /*!
  12180. @brief dump escaped string
  12181. Escape a string by replacing certain special characters by a sequence of an
  12182. escape character (backslash) and another character and other control
  12183. characters by a sequence of "\u" followed by a four-digit hex
  12184. representation. The escaped string is written to output stream @a o.
  12185. @param[in] s the string to escape
  12186. @param[in] ensure_ascii whether to escape non-ASCII characters with
  12187. \uXXXX sequences
  12188. @complexity Linear in the length of string @a s.
  12189. */
  12190. void dump_escaped(const string_t& s, const bool ensure_ascii)
  12191. {
  12192. std::uint32_t codepoint;
  12193. std::uint8_t state = UTF8_ACCEPT;
  12194. std::size_t bytes = 0; // number of bytes written to string_buffer
  12195. // number of bytes written at the point of the last valid byte
  12196. std::size_t bytes_after_last_accept = 0;
  12197. std::size_t undumped_chars = 0;
  12198. for (std::size_t i = 0; i < s.size(); ++i)
  12199. {
  12200. const auto byte = static_cast<uint8_t>(s[i]);
  12201. switch (decode(state, codepoint, byte))
  12202. {
  12203. case UTF8_ACCEPT: // decode found a new code point
  12204. {
  12205. switch (codepoint)
  12206. {
  12207. case 0x08: // backspace
  12208. {
  12209. string_buffer[bytes++] = '\\';
  12210. string_buffer[bytes++] = 'b';
  12211. break;
  12212. }
  12213. case 0x09: // horizontal tab
  12214. {
  12215. string_buffer[bytes++] = '\\';
  12216. string_buffer[bytes++] = 't';
  12217. break;
  12218. }
  12219. case 0x0A: // newline
  12220. {
  12221. string_buffer[bytes++] = '\\';
  12222. string_buffer[bytes++] = 'n';
  12223. break;
  12224. }
  12225. case 0x0C: // formfeed
  12226. {
  12227. string_buffer[bytes++] = '\\';
  12228. string_buffer[bytes++] = 'f';
  12229. break;
  12230. }
  12231. case 0x0D: // carriage return
  12232. {
  12233. string_buffer[bytes++] = '\\';
  12234. string_buffer[bytes++] = 'r';
  12235. break;
  12236. }
  12237. case 0x22: // quotation mark
  12238. {
  12239. string_buffer[bytes++] = '\\';
  12240. string_buffer[bytes++] = '\"';
  12241. break;
  12242. }
  12243. case 0x5C: // reverse solidus
  12244. {
  12245. string_buffer[bytes++] = '\\';
  12246. string_buffer[bytes++] = '\\';
  12247. break;
  12248. }
  12249. default:
  12250. {
  12251. // escape control characters (0x00..0x1F) or, if
  12252. // ensure_ascii parameter is used, non-ASCII characters
  12253. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  12254. {
  12255. if (codepoint <= 0xFFFF)
  12256. {
  12257. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  12258. static_cast<std::uint16_t>(codepoint));
  12259. bytes += 6;
  12260. }
  12261. else
  12262. {
  12263. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  12264. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  12265. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  12266. bytes += 12;
  12267. }
  12268. }
  12269. else
  12270. {
  12271. // copy byte to buffer (all previous bytes
  12272. // been copied have in default case above)
  12273. string_buffer[bytes++] = s[i];
  12274. }
  12275. break;
  12276. }
  12277. }
  12278. // write buffer and reset index; there must be 13 bytes
  12279. // left, as this is the maximal number of bytes to be
  12280. // written ("\uxxxx\uxxxx\0") for one code point
  12281. if (string_buffer.size() - bytes < 13)
  12282. {
  12283. o->write_characters(string_buffer.data(), bytes);
  12284. bytes = 0;
  12285. }
  12286. // remember the byte position of this accept
  12287. bytes_after_last_accept = bytes;
  12288. undumped_chars = 0;
  12289. break;
  12290. }
  12291. case UTF8_REJECT: // decode found invalid UTF-8 byte
  12292. {
  12293. switch (error_handler)
  12294. {
  12295. case error_handler_t::strict:
  12296. {
  12297. std::string sn(3, '\0');
  12298. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  12299. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  12300. }
  12301. case error_handler_t::ignore:
  12302. case error_handler_t::replace:
  12303. {
  12304. // in case we saw this character the first time, we
  12305. // would like to read it again, because the byte
  12306. // may be OK for itself, but just not OK for the
  12307. // previous sequence
  12308. if (undumped_chars > 0)
  12309. {
  12310. --i;
  12311. }
  12312. // reset length buffer to the last accepted index;
  12313. // thus removing/ignoring the invalid characters
  12314. bytes = bytes_after_last_accept;
  12315. if (error_handler == error_handler_t::replace)
  12316. {
  12317. // add a replacement character
  12318. if (ensure_ascii)
  12319. {
  12320. string_buffer[bytes++] = '\\';
  12321. string_buffer[bytes++] = 'u';
  12322. string_buffer[bytes++] = 'f';
  12323. string_buffer[bytes++] = 'f';
  12324. string_buffer[bytes++] = 'f';
  12325. string_buffer[bytes++] = 'd';
  12326. }
  12327. else
  12328. {
  12329. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  12330. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  12331. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  12332. }
  12333. // write buffer and reset index; there must be 13 bytes
  12334. // left, as this is the maximal number of bytes to be
  12335. // written ("\uxxxx\uxxxx\0") for one code point
  12336. if (string_buffer.size() - bytes < 13)
  12337. {
  12338. o->write_characters(string_buffer.data(), bytes);
  12339. bytes = 0;
  12340. }
  12341. bytes_after_last_accept = bytes;
  12342. }
  12343. undumped_chars = 0;
  12344. // continue processing the string
  12345. state = UTF8_ACCEPT;
  12346. break;
  12347. }
  12348. default: // LCOV_EXCL_LINE
  12349. assert(false); // LCOV_EXCL_LINE
  12350. }
  12351. break;
  12352. }
  12353. default: // decode found yet incomplete multi-byte code point
  12354. {
  12355. if (not ensure_ascii)
  12356. {
  12357. // code point will not be escaped - copy byte to buffer
  12358. string_buffer[bytes++] = s[i];
  12359. }
  12360. ++undumped_chars;
  12361. break;
  12362. }
  12363. }
  12364. }
  12365. // we finished processing the string
  12366. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  12367. {
  12368. // write buffer
  12369. if (bytes > 0)
  12370. {
  12371. o->write_characters(string_buffer.data(), bytes);
  12372. }
  12373. }
  12374. else
  12375. {
  12376. // we finish reading, but do not accept: string was incomplete
  12377. switch (error_handler)
  12378. {
  12379. case error_handler_t::strict:
  12380. {
  12381. std::string sn(3, '\0');
  12382. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  12383. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  12384. }
  12385. case error_handler_t::ignore:
  12386. {
  12387. // write all accepted bytes
  12388. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12389. break;
  12390. }
  12391. case error_handler_t::replace:
  12392. {
  12393. // write all accepted bytes
  12394. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12395. // add a replacement character
  12396. if (ensure_ascii)
  12397. {
  12398. o->write_characters("\\ufffd", 6);
  12399. }
  12400. else
  12401. {
  12402. o->write_characters("\xEF\xBF\xBD", 3);
  12403. }
  12404. break;
  12405. }
  12406. default: // LCOV_EXCL_LINE
  12407. assert(false); // LCOV_EXCL_LINE
  12408. }
  12409. }
  12410. }
  12411. /*!
  12412. @brief count digits
  12413. Count the number of decimal (base 10) digits for an input unsigned integer.
  12414. @param[in] x unsigned integer number to count its digits
  12415. @return number of decimal digits
  12416. */
  12417. inline unsigned int count_digits(number_unsigned_t x) noexcept
  12418. {
  12419. unsigned int n_digits = 1;
  12420. for (;;)
  12421. {
  12422. if (x < 10)
  12423. {
  12424. return n_digits;
  12425. }
  12426. if (x < 100)
  12427. {
  12428. return n_digits + 1;
  12429. }
  12430. if (x < 1000)
  12431. {
  12432. return n_digits + 2;
  12433. }
  12434. if (x < 10000)
  12435. {
  12436. return n_digits + 3;
  12437. }
  12438. x = x / 10000u;
  12439. n_digits += 4;
  12440. }
  12441. }
  12442. /*!
  12443. @brief dump an integer
  12444. Dump a given integer to output stream @a o. Works internally with
  12445. @a number_buffer.
  12446. @param[in] x integer number (signed or unsigned) to dump
  12447. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  12448. */
  12449. template<typename NumberType, detail::enable_if_t<
  12450. std::is_same<NumberType, number_unsigned_t>::value or
  12451. std::is_same<NumberType, number_integer_t>::value,
  12452. int> = 0>
  12453. void dump_integer(NumberType x)
  12454. {
  12455. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  12456. {
  12457. {
  12458. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  12459. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  12460. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  12461. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  12462. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  12463. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  12464. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  12465. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  12466. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  12467. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  12468. }
  12469. };
  12470. // special case for "0"
  12471. if (x == 0)
  12472. {
  12473. o->write_character('0');
  12474. return;
  12475. }
  12476. // use a pointer to fill the buffer
  12477. auto buffer_ptr = number_buffer.begin();
  12478. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  12479. number_unsigned_t abs_value;
  12480. unsigned int n_chars;
  12481. if (is_negative)
  12482. {
  12483. *buffer_ptr = '-';
  12484. abs_value = remove_sign(x);
  12485. // account one more byte for the minus sign
  12486. n_chars = 1 + count_digits(abs_value);
  12487. }
  12488. else
  12489. {
  12490. abs_value = static_cast<number_unsigned_t>(x);
  12491. n_chars = count_digits(abs_value);
  12492. }
  12493. // spare 1 byte for '\0'
  12494. assert(n_chars < number_buffer.size() - 1);
  12495. // jump to the end to generate the string from backward
  12496. // so we later avoid reversing the result
  12497. buffer_ptr += n_chars;
  12498. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  12499. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  12500. while (abs_value >= 100)
  12501. {
  12502. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  12503. abs_value /= 100;
  12504. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12505. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12506. }
  12507. if (abs_value >= 10)
  12508. {
  12509. const auto digits_index = static_cast<unsigned>(abs_value);
  12510. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12511. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12512. }
  12513. else
  12514. {
  12515. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  12516. }
  12517. o->write_characters(number_buffer.data(), n_chars);
  12518. }
  12519. /*!
  12520. @brief dump a floating-point number
  12521. Dump a given floating-point number to output stream @a o. Works internally
  12522. with @a number_buffer.
  12523. @param[in] x floating-point number to dump
  12524. */
  12525. void dump_float(number_float_t x)
  12526. {
  12527. // NaN / inf
  12528. if (not std::isfinite(x))
  12529. {
  12530. o->write_characters("null", 4);
  12531. return;
  12532. }
  12533. // If number_float_t is an IEEE-754 single or double precision number,
  12534. // use the Grisu2 algorithm to produce short numbers which are
  12535. // guaranteed to round-trip, using strtof and strtod, resp.
  12536. //
  12537. // NB: The test below works if <long double> == <double>.
  12538. static constexpr bool is_ieee_single_or_double
  12539. = (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
  12540. (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);
  12541. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  12542. }
  12543. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  12544. {
  12545. char* begin = number_buffer.data();
  12546. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  12547. o->write_characters(begin, static_cast<size_t>(end - begin));
  12548. }
  12549. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  12550. {
  12551. // get number of digits for a float -> text -> float round-trip
  12552. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  12553. // the actual conversion
  12554. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  12555. // negative value indicates an error
  12556. assert(len > 0);
  12557. // check if buffer was large enough
  12558. assert(static_cast<std::size_t>(len) < number_buffer.size());
  12559. // erase thousands separator
  12560. if (thousands_sep != '\0')
  12561. {
  12562. const auto end = std::remove(number_buffer.begin(),
  12563. number_buffer.begin() + len, thousands_sep);
  12564. std::fill(end, number_buffer.end(), '\0');
  12565. assert((end - number_buffer.begin()) <= len);
  12566. len = (end - number_buffer.begin());
  12567. }
  12568. // convert decimal point to '.'
  12569. if (decimal_point != '\0' and decimal_point != '.')
  12570. {
  12571. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  12572. if (dec_pos != number_buffer.end())
  12573. {
  12574. *dec_pos = '.';
  12575. }
  12576. }
  12577. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  12578. // determine if need to append ".0"
  12579. const bool value_is_int_like =
  12580. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  12581. [](char c)
  12582. {
  12583. return c == '.' or c == 'e';
  12584. });
  12585. if (value_is_int_like)
  12586. {
  12587. o->write_characters(".0", 2);
  12588. }
  12589. }
  12590. /*!
  12591. @brief check whether a string is UTF-8 encoded
  12592. The function checks each byte of a string whether it is UTF-8 encoded. The
  12593. result of the check is stored in the @a state parameter. The function must
  12594. be called initially with state 0 (accept). State 1 means the string must
  12595. be rejected, because the current byte is not allowed. If the string is
  12596. completely processed, but the state is non-zero, the string ended
  12597. prematurely; that is, the last byte indicated more bytes should have
  12598. followed.
  12599. @param[in,out] state the state of the decoding
  12600. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  12601. @param[in] byte next byte to decode
  12602. @return new state
  12603. @note The function has been edited: a std::array is used.
  12604. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  12605. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  12606. */
  12607. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  12608. {
  12609. static const std::array<std::uint8_t, 400> utf8d =
  12610. {
  12611. {
  12612. 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
  12613. 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
  12614. 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
  12615. 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
  12616. 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
  12617. 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
  12618. 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
  12619. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  12620. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  12621. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  12622. 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
  12623. 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
  12624. 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
  12625. 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
  12626. }
  12627. };
  12628. const std::uint8_t type = utf8d[byte];
  12629. codep = (state != UTF8_ACCEPT)
  12630. ? (byte & 0x3fu) | (codep << 6u)
  12631. : (0xFFu >> type) & (byte);
  12632. state = utf8d[256u + state * 16u + type];
  12633. return state;
  12634. }
  12635. /*
  12636. * Overload to make the compiler happy while it is instantiating
  12637. * dump_integer for number_unsigned_t.
  12638. * Must never be called.
  12639. */
  12640. number_unsigned_t remove_sign(number_unsigned_t x)
  12641. {
  12642. assert(false); // LCOV_EXCL_LINE
  12643. return x; // LCOV_EXCL_LINE
  12644. }
  12645. /*
  12646. * Helper function for dump_integer
  12647. *
  12648. * This function takes a negative signed integer and returns its absolute
  12649. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  12650. * not directly remove the sign of an arbitrary signed integer as the
  12651. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  12652. * #1708 for details.
  12653. */
  12654. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  12655. {
  12656. assert(x < 0 and x < (std::numeric_limits<number_integer_t>::max)());
  12657. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  12658. }
  12659. private:
  12660. /// the output of the serializer
  12661. output_adapter_t<char> o = nullptr;
  12662. /// a (hopefully) large enough character buffer
  12663. std::array<char, 64> number_buffer{{}};
  12664. /// the locale
  12665. const std::lconv* loc = nullptr;
  12666. /// the locale's thousand separator character
  12667. const char thousands_sep = '\0';
  12668. /// the locale's decimal point character
  12669. const char decimal_point = '\0';
  12670. /// string buffer
  12671. std::array<char, 512> string_buffer{{}};
  12672. /// the indentation character
  12673. const char indent_char;
  12674. /// the indentation string
  12675. string_t indent_string;
  12676. /// error_handler how to react on decoding errors
  12677. const error_handler_t error_handler;
  12678. };
  12679. } // namespace detail
  12680. } // namespace nlohmann
  12681. // #include <nlohmann/detail/value_t.hpp>
  12682. // #include <nlohmann/json_fwd.hpp>
  12683. /*!
  12684. @brief namespace for Niels Lohmann
  12685. @see https://github.com/nlohmann
  12686. @since version 1.0.0
  12687. */
  12688. namespace nlohmann
  12689. {
  12690. /*!
  12691. @brief a class to store JSON values
  12692. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  12693. in @ref object_t)
  12694. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  12695. in @ref array_t)
  12696. @tparam StringType type for JSON strings and object keys (`std::string` by
  12697. default; will be used in @ref string_t)
  12698. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  12699. in @ref boolean_t)
  12700. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  12701. default; will be used in @ref number_integer_t)
  12702. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  12703. `uint64_t` by default; will be used in @ref number_unsigned_t)
  12704. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  12705. default; will be used in @ref number_float_t)
  12706. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  12707. default)
  12708. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  12709. and `from_json()` (@ref adl_serializer by default)
  12710. @requirement The class satisfies the following concept requirements:
  12711. - Basic
  12712. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  12713. JSON values can be default constructed. The result will be a JSON null
  12714. value.
  12715. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  12716. A JSON value can be constructed from an rvalue argument.
  12717. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  12718. A JSON value can be copy-constructed from an lvalue expression.
  12719. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  12720. A JSON value van be assigned from an rvalue argument.
  12721. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  12722. A JSON value can be copy-assigned from an lvalue expression.
  12723. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  12724. JSON values can be destructed.
  12725. - Layout
  12726. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  12727. JSON values have
  12728. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  12729. All non-static data members are private and standard layout types, the
  12730. class has no virtual functions or (virtual) base classes.
  12731. - Library-wide
  12732. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  12733. JSON values can be compared with `==`, see @ref
  12734. operator==(const_reference,const_reference).
  12735. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  12736. JSON values can be compared with `<`, see @ref
  12737. operator<(const_reference,const_reference).
  12738. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  12739. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  12740. other compatible types, using unqualified function call @ref swap().
  12741. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  12742. JSON values can be compared against `std::nullptr_t` objects which are used
  12743. to model the `null` value.
  12744. - Container
  12745. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  12746. JSON values can be used like STL containers and provide iterator access.
  12747. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  12748. JSON values can be used like STL containers and provide reverse iterator
  12749. access.
  12750. @invariant The member variables @a m_value and @a m_type have the following
  12751. relationship:
  12752. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  12753. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  12754. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  12755. The invariants are checked by member function assert_invariant().
  12756. @internal
  12757. @note ObjectType trick from http://stackoverflow.com/a/9860911
  12758. @endinternal
  12759. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  12760. Format](http://rfc7159.net/rfc7159)
  12761. @since version 1.0.0
  12762. @nosubgrouping
  12763. */
  12764. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12765. class basic_json
  12766. {
  12767. private:
  12768. template<detail::value_t> friend struct detail::external_constructor;
  12769. friend ::nlohmann::json_pointer<basic_json>;
  12770. friend ::nlohmann::detail::parser<basic_json>;
  12771. friend ::nlohmann::detail::serializer<basic_json>;
  12772. template<typename BasicJsonType>
  12773. friend class ::nlohmann::detail::iter_impl;
  12774. template<typename BasicJsonType, typename CharType>
  12775. friend class ::nlohmann::detail::binary_writer;
  12776. template<typename BasicJsonType, typename SAX>
  12777. friend class ::nlohmann::detail::binary_reader;
  12778. template<typename BasicJsonType>
  12779. friend class ::nlohmann::detail::json_sax_dom_parser;
  12780. template<typename BasicJsonType>
  12781. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  12782. /// workaround type for MSVC
  12783. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  12784. // convenience aliases for types residing in namespace detail;
  12785. using lexer = ::nlohmann::detail::lexer<basic_json>;
  12786. using parser = ::nlohmann::detail::parser<basic_json>;
  12787. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  12788. template<typename BasicJsonType>
  12789. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  12790. template<typename BasicJsonType>
  12791. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  12792. template<typename Iterator>
  12793. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  12794. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  12795. template<typename CharType>
  12796. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  12797. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  12798. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  12799. using serializer = ::nlohmann::detail::serializer<basic_json>;
  12800. public:
  12801. using value_t = detail::value_t;
  12802. /// JSON Pointer, see @ref nlohmann::json_pointer
  12803. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  12804. template<typename T, typename SFINAE>
  12805. using json_serializer = JSONSerializer<T, SFINAE>;
  12806. /// how to treat decoding errors
  12807. using error_handler_t = detail::error_handler_t;
  12808. /// helper type for initializer lists of basic_json values
  12809. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  12810. using input_format_t = detail::input_format_t;
  12811. /// SAX interface type, see @ref nlohmann::json_sax
  12812. using json_sax_t = json_sax<basic_json>;
  12813. ////////////////
  12814. // exceptions //
  12815. ////////////////
  12816. /// @name exceptions
  12817. /// Classes to implement user-defined exceptions.
  12818. /// @{
  12819. /// @copydoc detail::exception
  12820. using exception = detail::exception;
  12821. /// @copydoc detail::parse_error
  12822. using parse_error = detail::parse_error;
  12823. /// @copydoc detail::invalid_iterator
  12824. using invalid_iterator = detail::invalid_iterator;
  12825. /// @copydoc detail::type_error
  12826. using type_error = detail::type_error;
  12827. /// @copydoc detail::out_of_range
  12828. using out_of_range = detail::out_of_range;
  12829. /// @copydoc detail::other_error
  12830. using other_error = detail::other_error;
  12831. /// @}
  12832. /////////////////////
  12833. // container types //
  12834. /////////////////////
  12835. /// @name container types
  12836. /// The canonic container types to use @ref basic_json like any other STL
  12837. /// container.
  12838. /// @{
  12839. /// the type of elements in a basic_json container
  12840. using value_type = basic_json;
  12841. /// the type of an element reference
  12842. using reference = value_type&;
  12843. /// the type of an element const reference
  12844. using const_reference = const value_type&;
  12845. /// a type to represent differences between iterators
  12846. using difference_type = std::ptrdiff_t;
  12847. /// a type to represent container sizes
  12848. using size_type = std::size_t;
  12849. /// the allocator type
  12850. using allocator_type = AllocatorType<basic_json>;
  12851. /// the type of an element pointer
  12852. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  12853. /// the type of an element const pointer
  12854. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  12855. /// an iterator for a basic_json container
  12856. using iterator = iter_impl<basic_json>;
  12857. /// a const iterator for a basic_json container
  12858. using const_iterator = iter_impl<const basic_json>;
  12859. /// a reverse iterator for a basic_json container
  12860. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  12861. /// a const reverse iterator for a basic_json container
  12862. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  12863. /// @}
  12864. /*!
  12865. @brief returns the allocator associated with the container
  12866. */
  12867. static allocator_type get_allocator()
  12868. {
  12869. return allocator_type();
  12870. }
  12871. /*!
  12872. @brief returns version information on the library
  12873. This function returns a JSON object with information about the library,
  12874. including the version number and information on the platform and compiler.
  12875. @return JSON object holding version information
  12876. key | description
  12877. ----------- | ---------------
  12878. `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).
  12879. `copyright` | The copyright line for the library as string.
  12880. `name` | The name of the library as string.
  12881. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  12882. `url` | The URL of the project as string.
  12883. `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).
  12884. @liveexample{The following code shows an example output of the `meta()`
  12885. function.,meta}
  12886. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12887. changes to any JSON value.
  12888. @complexity Constant.
  12889. @since 2.1.0
  12890. */
  12891. JSON_HEDLEY_WARN_UNUSED_RESULT
  12892. static basic_json meta()
  12893. {
  12894. basic_json result;
  12895. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  12896. result["name"] = "JSON for Modern C++";
  12897. result["url"] = "https://github.com/nlohmann/json";
  12898. result["version"]["string"] =
  12899. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  12900. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  12901. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  12902. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  12903. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  12904. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  12905. #ifdef _WIN32
  12906. result["platform"] = "win32";
  12907. #elif defined __linux__
  12908. result["platform"] = "linux";
  12909. #elif defined __APPLE__
  12910. result["platform"] = "apple";
  12911. #elif defined __unix__
  12912. result["platform"] = "unix";
  12913. #else
  12914. result["platform"] = "unknown";
  12915. #endif
  12916. #if defined(__ICC) || defined(__INTEL_COMPILER)
  12917. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  12918. #elif defined(__clang__)
  12919. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  12920. #elif defined(__GNUC__) || defined(__GNUG__)
  12921. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  12922. #elif defined(__HP_cc) || defined(__HP_aCC)
  12923. result["compiler"] = "hp"
  12924. #elif defined(__IBMCPP__)
  12925. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  12926. #elif defined(_MSC_VER)
  12927. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  12928. #elif defined(__PGI)
  12929. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  12930. #elif defined(__SUNPRO_CC)
  12931. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  12932. #else
  12933. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  12934. #endif
  12935. #ifdef __cplusplus
  12936. result["compiler"]["c++"] = std::to_string(__cplusplus);
  12937. #else
  12938. result["compiler"]["c++"] = "unknown";
  12939. #endif
  12940. return result;
  12941. }
  12942. ///////////////////////////
  12943. // JSON value data types //
  12944. ///////////////////////////
  12945. /// @name JSON value data types
  12946. /// The data types to store a JSON value. These types are derived from
  12947. /// the template arguments passed to class @ref basic_json.
  12948. /// @{
  12949. #if defined(JSON_HAS_CPP_14)
  12950. // Use transparent comparator if possible, combined with perfect forwarding
  12951. // on find() and count() calls prevents unnecessary string construction.
  12952. using object_comparator_t = std::less<>;
  12953. #else
  12954. using object_comparator_t = std::less<StringType>;
  12955. #endif
  12956. /*!
  12957. @brief a type for an object
  12958. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  12959. > An object is an unordered collection of zero or more name/value pairs,
  12960. > where a name is a string and a value is a string, number, boolean, null,
  12961. > object, or array.
  12962. To store objects in C++, a type is defined by the template parameters
  12963. described below.
  12964. @tparam ObjectType the container to store objects (e.g., `std::map` or
  12965. `std::unordered_map`)
  12966. @tparam StringType the type of the keys or names (e.g., `std::string`).
  12967. The comparison function `std::less<StringType>` is used to order elements
  12968. inside the container.
  12969. @tparam AllocatorType the allocator to use for objects (e.g.,
  12970. `std::allocator`)
  12971. #### Default type
  12972. With the default values for @a ObjectType (`std::map`), @a StringType
  12973. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  12974. value for @a object_t is:
  12975. @code {.cpp}
  12976. std::map<
  12977. std::string, // key_type
  12978. basic_json, // value_type
  12979. std::less<std::string>, // key_compare
  12980. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  12981. >
  12982. @endcode
  12983. #### Behavior
  12984. The choice of @a object_t influences the behavior of the JSON class. With
  12985. the default type, objects have the following behavior:
  12986. - When all names are unique, objects will be interoperable in the sense
  12987. that all software implementations receiving that object will agree on
  12988. the name-value mappings.
  12989. - When the names within an object are not unique, it is unspecified which
  12990. one of the values for a given key will be chosen. For instance,
  12991. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  12992. `{"key": 2}`.
  12993. - Internally, name/value pairs are stored in lexicographical order of the
  12994. names. Objects will also be serialized (see @ref dump) in this order.
  12995. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  12996. and serialized as `{"a": 2, "b": 1}`.
  12997. - When comparing objects, the order of the name/value pairs is irrelevant.
  12998. This makes objects interoperable in the sense that they will not be
  12999. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  13000. `{"a": 2, "b": 1}` will be treated as equal.
  13001. #### Limits
  13002. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13003. > An implementation may set limits on the maximum depth of nesting.
  13004. In this class, the object's limit of nesting is not explicitly constrained.
  13005. However, a maximum depth of nesting may be introduced by the compiler or
  13006. runtime environment. A theoretical limit can be queried by calling the
  13007. @ref max_size function of a JSON object.
  13008. #### Storage
  13009. Objects are stored as pointers in a @ref basic_json type. That is, for any
  13010. access to object values, a pointer of type `object_t*` must be
  13011. dereferenced.
  13012. @sa @ref array_t -- type for an array value
  13013. @since version 1.0.0
  13014. @note The order name/value pairs are added to the object is *not*
  13015. preserved by the library. Therefore, iterating an object may return
  13016. name/value pairs in a different order than they were originally stored. In
  13017. fact, keys will be traversed in alphabetical order as `std::map` with
  13018. `std::less` is used by default. Please note this behavior conforms to [RFC
  13019. 7159](http://rfc7159.net/rfc7159), because any order implements the
  13020. specified "unordered" nature of JSON objects.
  13021. */
  13022. using object_t = ObjectType<StringType,
  13023. basic_json,
  13024. object_comparator_t,
  13025. AllocatorType<std::pair<const StringType,
  13026. basic_json>>>;
  13027. /*!
  13028. @brief a type for an array
  13029. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  13030. > An array is an ordered sequence of zero or more values.
  13031. To store objects in C++, a type is defined by the template parameters
  13032. explained below.
  13033. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  13034. `std::list`)
  13035. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  13036. #### Default type
  13037. With the default values for @a ArrayType (`std::vector`) and @a
  13038. AllocatorType (`std::allocator`), the default value for @a array_t is:
  13039. @code {.cpp}
  13040. std::vector<
  13041. basic_json, // value_type
  13042. std::allocator<basic_json> // allocator_type
  13043. >
  13044. @endcode
  13045. #### Limits
  13046. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13047. > An implementation may set limits on the maximum depth of nesting.
  13048. In this class, the array's limit of nesting is not explicitly constrained.
  13049. However, a maximum depth of nesting may be introduced by the compiler or
  13050. runtime environment. A theoretical limit can be queried by calling the
  13051. @ref max_size function of a JSON array.
  13052. #### Storage
  13053. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  13054. access to array values, a pointer of type `array_t*` must be dereferenced.
  13055. @sa @ref object_t -- type for an object value
  13056. @since version 1.0.0
  13057. */
  13058. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  13059. /*!
  13060. @brief a type for a string
  13061. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  13062. > A string is a sequence of zero or more Unicode characters.
  13063. To store objects in C++, a type is defined by the template parameter
  13064. described below. Unicode values are split by the JSON class into
  13065. byte-sized characters during deserialization.
  13066. @tparam StringType the container to store strings (e.g., `std::string`).
  13067. Note this container is used for keys/names in objects, see @ref object_t.
  13068. #### Default type
  13069. With the default values for @a StringType (`std::string`), the default
  13070. value for @a string_t is:
  13071. @code {.cpp}
  13072. std::string
  13073. @endcode
  13074. #### Encoding
  13075. Strings are stored in UTF-8 encoding. Therefore, functions like
  13076. `std::string::size()` or `std::string::length()` return the number of
  13077. bytes in the string rather than the number of characters or glyphs.
  13078. #### String comparison
  13079. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13080. > Software implementations are typically required to test names of object
  13081. > members for equality. Implementations that transform the textual
  13082. > representation into sequences of Unicode code units and then perform the
  13083. > comparison numerically, code unit by code unit, are interoperable in the
  13084. > sense that implementations will agree in all cases on equality or
  13085. > inequality of two strings. For example, implementations that compare
  13086. > strings with escaped characters unconverted may incorrectly find that
  13087. > `"a\\b"` and `"a\u005Cb"` are not equal.
  13088. This implementation is interoperable as it does compare strings code unit
  13089. by code unit.
  13090. #### Storage
  13091. String values are stored as pointers in a @ref basic_json type. That is,
  13092. for any access to string values, a pointer of type `string_t*` must be
  13093. dereferenced.
  13094. @since version 1.0.0
  13095. */
  13096. using string_t = StringType;
  13097. /*!
  13098. @brief a type for a boolean
  13099. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  13100. type which differentiates the two literals `true` and `false`.
  13101. To store objects in C++, a type is defined by the template parameter @a
  13102. BooleanType which chooses the type to use.
  13103. #### Default type
  13104. With the default values for @a BooleanType (`bool`), the default value for
  13105. @a boolean_t is:
  13106. @code {.cpp}
  13107. bool
  13108. @endcode
  13109. #### Storage
  13110. Boolean values are stored directly inside a @ref basic_json type.
  13111. @since version 1.0.0
  13112. */
  13113. using boolean_t = BooleanType;
  13114. /*!
  13115. @brief a type for a number (integer)
  13116. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13117. > The representation of numbers is similar to that used in most
  13118. > programming languages. A number is represented in base 10 using decimal
  13119. > digits. It contains an integer component that may be prefixed with an
  13120. > optional minus sign, which may be followed by a fraction part and/or an
  13121. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13122. > cannot be represented in the grammar below (such as Infinity and NaN)
  13123. > are not permitted.
  13124. This description includes both integer and floating-point numbers.
  13125. However, C++ allows more precise storage if it is known whether the number
  13126. is a signed integer, an unsigned integer or a floating-point number.
  13127. Therefore, three different types, @ref number_integer_t, @ref
  13128. number_unsigned_t and @ref number_float_t are used.
  13129. To store integer numbers in C++, a type is defined by the template
  13130. parameter @a NumberIntegerType which chooses the type to use.
  13131. #### Default type
  13132. With the default values for @a NumberIntegerType (`int64_t`), the default
  13133. value for @a number_integer_t is:
  13134. @code {.cpp}
  13135. int64_t
  13136. @endcode
  13137. #### Default behavior
  13138. - The restrictions about leading zeros is not enforced in C++. Instead,
  13139. leading zeros in integer literals lead to an interpretation as octal
  13140. number. Internally, the value will be stored as decimal number. For
  13141. instance, the C++ integer literal `010` will be serialized to `8`.
  13142. During deserialization, leading zeros yield an error.
  13143. - Not-a-number (NaN) values will be serialized to `null`.
  13144. #### Limits
  13145. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13146. > An implementation may set limits on the range and precision of numbers.
  13147. When the default type is used, the maximal integer number that can be
  13148. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  13149. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  13150. that are out of range will yield over/underflow when used in a
  13151. constructor. During deserialization, too large or small integer numbers
  13152. will be automatically be stored as @ref number_unsigned_t or @ref
  13153. number_float_t.
  13154. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13155. > Note that when such software is used, numbers that are integers and are
  13156. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13157. > that implementations will agree exactly on their numeric values.
  13158. As this range is a subrange of the exactly supported range [INT64_MIN,
  13159. INT64_MAX], this class's integer type is interoperable.
  13160. #### Storage
  13161. Integer number values are stored directly inside a @ref basic_json type.
  13162. @sa @ref number_float_t -- type for number values (floating-point)
  13163. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13164. @since version 1.0.0
  13165. */
  13166. using number_integer_t = NumberIntegerType;
  13167. /*!
  13168. @brief a type for a number (unsigned)
  13169. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13170. > The representation of numbers is similar to that used in most
  13171. > programming languages. A number is represented in base 10 using decimal
  13172. > digits. It contains an integer component that may be prefixed with an
  13173. > optional minus sign, which may be followed by a fraction part and/or an
  13174. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13175. > cannot be represented in the grammar below (such as Infinity and NaN)
  13176. > are not permitted.
  13177. This description includes both integer and floating-point numbers.
  13178. However, C++ allows more precise storage if it is known whether the number
  13179. is a signed integer, an unsigned integer or a floating-point number.
  13180. Therefore, three different types, @ref number_integer_t, @ref
  13181. number_unsigned_t and @ref number_float_t are used.
  13182. To store unsigned integer numbers in C++, a type is defined by the
  13183. template parameter @a NumberUnsignedType which chooses the type to use.
  13184. #### Default type
  13185. With the default values for @a NumberUnsignedType (`uint64_t`), the
  13186. default value for @a number_unsigned_t is:
  13187. @code {.cpp}
  13188. uint64_t
  13189. @endcode
  13190. #### Default behavior
  13191. - The restrictions about leading zeros is not enforced in C++. Instead,
  13192. leading zeros in integer literals lead to an interpretation as octal
  13193. number. Internally, the value will be stored as decimal number. For
  13194. instance, the C++ integer literal `010` will be serialized to `8`.
  13195. During deserialization, leading zeros yield an error.
  13196. - Not-a-number (NaN) values will be serialized to `null`.
  13197. #### Limits
  13198. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13199. > An implementation may set limits on the range and precision of numbers.
  13200. When the default type is used, the maximal integer number that can be
  13201. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  13202. number that can be stored is `0`. Integer numbers that are out of range
  13203. will yield over/underflow when used in a constructor. During
  13204. deserialization, too large or small integer numbers will be automatically
  13205. be stored as @ref number_integer_t or @ref number_float_t.
  13206. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13207. > Note that when such software is used, numbers that are integers and are
  13208. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13209. > that implementations will agree exactly on their numeric values.
  13210. As this range is a subrange (when considered in conjunction with the
  13211. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  13212. this class's integer type is interoperable.
  13213. #### Storage
  13214. Integer number values are stored directly inside a @ref basic_json type.
  13215. @sa @ref number_float_t -- type for number values (floating-point)
  13216. @sa @ref number_integer_t -- type for number values (integer)
  13217. @since version 2.0.0
  13218. */
  13219. using number_unsigned_t = NumberUnsignedType;
  13220. /*!
  13221. @brief a type for a number (floating-point)
  13222. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13223. > The representation of numbers is similar to that used in most
  13224. > programming languages. A number is represented in base 10 using decimal
  13225. > digits. It contains an integer component that may be prefixed with an
  13226. > optional minus sign, which may be followed by a fraction part and/or an
  13227. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13228. > cannot be represented in the grammar below (such as Infinity and NaN)
  13229. > are not permitted.
  13230. This description includes both integer and floating-point numbers.
  13231. However, C++ allows more precise storage if it is known whether the number
  13232. is a signed integer, an unsigned integer or a floating-point number.
  13233. Therefore, three different types, @ref number_integer_t, @ref
  13234. number_unsigned_t and @ref number_float_t are used.
  13235. To store floating-point numbers in C++, a type is defined by the template
  13236. parameter @a NumberFloatType which chooses the type to use.
  13237. #### Default type
  13238. With the default values for @a NumberFloatType (`double`), the default
  13239. value for @a number_float_t is:
  13240. @code {.cpp}
  13241. double
  13242. @endcode
  13243. #### Default behavior
  13244. - The restrictions about leading zeros is not enforced in C++. Instead,
  13245. leading zeros in floating-point literals will be ignored. Internally,
  13246. the value will be stored as decimal number. For instance, the C++
  13247. floating-point literal `01.2` will be serialized to `1.2`. During
  13248. deserialization, leading zeros yield an error.
  13249. - Not-a-number (NaN) values will be serialized to `null`.
  13250. #### Limits
  13251. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13252. > This specification allows implementations to set limits on the range and
  13253. > precision of numbers accepted. Since software that implements IEEE
  13254. > 754-2008 binary64 (double precision) numbers is generally available and
  13255. > widely used, good interoperability can be achieved by implementations
  13256. > that expect no more precision or range than these provide, in the sense
  13257. > that implementations will approximate JSON numbers within the expected
  13258. > precision.
  13259. This implementation does exactly follow this approach, as it uses double
  13260. precision floating-point numbers. Note values smaller than
  13261. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  13262. will be stored as NaN internally and be serialized to `null`.
  13263. #### Storage
  13264. Floating-point number values are stored directly inside a @ref basic_json
  13265. type.
  13266. @sa @ref number_integer_t -- type for number values (integer)
  13267. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13268. @since version 1.0.0
  13269. */
  13270. using number_float_t = NumberFloatType;
  13271. /// @}
  13272. private:
  13273. /// helper for exception-safe object creation
  13274. template<typename T, typename... Args>
  13275. JSON_HEDLEY_RETURNS_NON_NULL
  13276. static T* create(Args&& ... args)
  13277. {
  13278. AllocatorType<T> alloc;
  13279. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  13280. auto deleter = [&](T * object)
  13281. {
  13282. AllocatorTraits::deallocate(alloc, object, 1);
  13283. };
  13284. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  13285. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  13286. assert(object != nullptr);
  13287. return object.release();
  13288. }
  13289. ////////////////////////
  13290. // JSON value storage //
  13291. ////////////////////////
  13292. /*!
  13293. @brief a JSON value
  13294. The actual storage for a JSON value of the @ref basic_json class. This
  13295. union combines the different storage types for the JSON value types
  13296. defined in @ref value_t.
  13297. JSON type | value_t type | used type
  13298. --------- | --------------- | ------------------------
  13299. object | object | pointer to @ref object_t
  13300. array | array | pointer to @ref array_t
  13301. string | string | pointer to @ref string_t
  13302. boolean | boolean | @ref boolean_t
  13303. number | number_integer | @ref number_integer_t
  13304. number | number_unsigned | @ref number_unsigned_t
  13305. number | number_float | @ref number_float_t
  13306. null | null | *no value is stored*
  13307. @note Variable-length types (objects, arrays, and strings) are stored as
  13308. pointers. The size of the union should not exceed 64 bits if the default
  13309. value types are used.
  13310. @since version 1.0.0
  13311. */
  13312. union json_value
  13313. {
  13314. /// object (stored with pointer to save storage)
  13315. object_t* object;
  13316. /// array (stored with pointer to save storage)
  13317. array_t* array;
  13318. /// string (stored with pointer to save storage)
  13319. string_t* string;
  13320. /// boolean
  13321. boolean_t boolean;
  13322. /// number (integer)
  13323. number_integer_t number_integer;
  13324. /// number (unsigned integer)
  13325. number_unsigned_t number_unsigned;
  13326. /// number (floating-point)
  13327. number_float_t number_float;
  13328. /// default constructor (for null values)
  13329. json_value() = default;
  13330. /// constructor for booleans
  13331. json_value(boolean_t v) noexcept : boolean(v) {}
  13332. /// constructor for numbers (integer)
  13333. json_value(number_integer_t v) noexcept : number_integer(v) {}
  13334. /// constructor for numbers (unsigned)
  13335. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  13336. /// constructor for numbers (floating-point)
  13337. json_value(number_float_t v) noexcept : number_float(v) {}
  13338. /// constructor for empty values of a given type
  13339. json_value(value_t t)
  13340. {
  13341. switch (t)
  13342. {
  13343. case value_t::object:
  13344. {
  13345. object = create<object_t>();
  13346. break;
  13347. }
  13348. case value_t::array:
  13349. {
  13350. array = create<array_t>();
  13351. break;
  13352. }
  13353. case value_t::string:
  13354. {
  13355. string = create<string_t>("");
  13356. break;
  13357. }
  13358. case value_t::boolean:
  13359. {
  13360. boolean = boolean_t(false);
  13361. break;
  13362. }
  13363. case value_t::number_integer:
  13364. {
  13365. number_integer = number_integer_t(0);
  13366. break;
  13367. }
  13368. case value_t::number_unsigned:
  13369. {
  13370. number_unsigned = number_unsigned_t(0);
  13371. break;
  13372. }
  13373. case value_t::number_float:
  13374. {
  13375. number_float = number_float_t(0.0);
  13376. break;
  13377. }
  13378. case value_t::null:
  13379. {
  13380. object = nullptr; // silence warning, see #821
  13381. break;
  13382. }
  13383. default:
  13384. {
  13385. object = nullptr; // silence warning, see #821
  13386. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  13387. {
  13388. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.0")); // LCOV_EXCL_LINE
  13389. }
  13390. break;
  13391. }
  13392. }
  13393. }
  13394. /// constructor for strings
  13395. json_value(const string_t& value)
  13396. {
  13397. string = create<string_t>(value);
  13398. }
  13399. /// constructor for rvalue strings
  13400. json_value(string_t&& value)
  13401. {
  13402. string = create<string_t>(std::move(value));
  13403. }
  13404. /// constructor for objects
  13405. json_value(const object_t& value)
  13406. {
  13407. object = create<object_t>(value);
  13408. }
  13409. /// constructor for rvalue objects
  13410. json_value(object_t&& value)
  13411. {
  13412. object = create<object_t>(std::move(value));
  13413. }
  13414. /// constructor for arrays
  13415. json_value(const array_t& value)
  13416. {
  13417. array = create<array_t>(value);
  13418. }
  13419. /// constructor for rvalue arrays
  13420. json_value(array_t&& value)
  13421. {
  13422. array = create<array_t>(std::move(value));
  13423. }
  13424. void destroy(value_t t) noexcept
  13425. {
  13426. switch (t)
  13427. {
  13428. case value_t::object:
  13429. {
  13430. AllocatorType<object_t> alloc;
  13431. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  13432. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  13433. break;
  13434. }
  13435. case value_t::array:
  13436. {
  13437. AllocatorType<array_t> alloc;
  13438. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  13439. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  13440. break;
  13441. }
  13442. case value_t::string:
  13443. {
  13444. AllocatorType<string_t> alloc;
  13445. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  13446. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  13447. break;
  13448. }
  13449. default:
  13450. {
  13451. break;
  13452. }
  13453. }
  13454. }
  13455. };
  13456. /*!
  13457. @brief checks the class invariants
  13458. This function asserts the class invariants. It needs to be called at the
  13459. end of every constructor to make sure that created objects respect the
  13460. invariant. Furthermore, it has to be called each time the type of a JSON
  13461. value is changed, because the invariant expresses a relationship between
  13462. @a m_type and @a m_value.
  13463. */
  13464. void assert_invariant() const noexcept
  13465. {
  13466. assert(m_type != value_t::object or m_value.object != nullptr);
  13467. assert(m_type != value_t::array or m_value.array != nullptr);
  13468. assert(m_type != value_t::string or m_value.string != nullptr);
  13469. }
  13470. public:
  13471. //////////////////////////
  13472. // JSON parser callback //
  13473. //////////////////////////
  13474. /*!
  13475. @brief parser event types
  13476. The parser callback distinguishes the following events:
  13477. - `object_start`: the parser read `{` and started to process a JSON object
  13478. - `key`: the parser read a key of a value in an object
  13479. - `object_end`: the parser read `}` and finished processing a JSON object
  13480. - `array_start`: the parser read `[` and started to process a JSON array
  13481. - `array_end`: the parser read `]` and finished processing a JSON array
  13482. - `value`: the parser finished reading a JSON value
  13483. @image html callback_events.png "Example when certain parse events are triggered"
  13484. @sa @ref parser_callback_t for more information and examples
  13485. */
  13486. using parse_event_t = typename parser::parse_event_t;
  13487. /*!
  13488. @brief per-element parser callback type
  13489. With a parser callback function, the result of parsing a JSON text can be
  13490. influenced. When passed to @ref parse, it is called on certain events
  13491. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  13492. depth @a depth and context JSON value @a parsed. The return value of the
  13493. callback function is a boolean indicating whether the element that emitted
  13494. the callback shall be kept or not.
  13495. We distinguish six scenarios (determined by the event type) in which the
  13496. callback function can be called. The following table describes the values
  13497. of the parameters @a depth, @a event, and @a parsed.
  13498. parameter @a event | description | parameter @a depth | parameter @a parsed
  13499. ------------------ | ----------- | ------------------ | -------------------
  13500. 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
  13501. 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
  13502. 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
  13503. 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
  13504. 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
  13505. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  13506. @image html callback_events.png "Example when certain parse events are triggered"
  13507. Discarding a value (i.e., returning `false`) has different effects
  13508. depending on the context in which function was called:
  13509. - Discarded values in structured types are skipped. That is, the parser
  13510. will behave as if the discarded value was never read.
  13511. - In case a value outside a structured type is skipped, it is replaced
  13512. with `null`. This case happens if the top-level element is skipped.
  13513. @param[in] depth the depth of the recursion during parsing
  13514. @param[in] event an event of type parse_event_t indicating the context in
  13515. the callback function has been called
  13516. @param[in,out] parsed the current intermediate parse result; note that
  13517. writing to this value has no effect for parse_event_t::key events
  13518. @return Whether the JSON value which called the function during parsing
  13519. should be kept (`true`) or not (`false`). In the latter case, it is either
  13520. skipped completely or replaced by an empty discarded object.
  13521. @sa @ref parse for examples
  13522. @since version 1.0.0
  13523. */
  13524. using parser_callback_t = typename parser::parser_callback_t;
  13525. //////////////////
  13526. // constructors //
  13527. //////////////////
  13528. /// @name constructors and destructors
  13529. /// Constructors of class @ref basic_json, copy/move constructor, copy
  13530. /// assignment, static functions creating objects, and the destructor.
  13531. /// @{
  13532. /*!
  13533. @brief create an empty value with a given type
  13534. Create an empty JSON value with a given type. The value will be default
  13535. initialized with an empty value which depends on the type:
  13536. Value type | initial value
  13537. ----------- | -------------
  13538. null | `null`
  13539. boolean | `false`
  13540. string | `""`
  13541. number | `0`
  13542. object | `{}`
  13543. array | `[]`
  13544. @param[in] v the type of the value to create
  13545. @complexity Constant.
  13546. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13547. changes to any JSON value.
  13548. @liveexample{The following code shows the constructor for different @ref
  13549. value_t values,basic_json__value_t}
  13550. @sa @ref clear() -- restores the postcondition of this constructor
  13551. @since version 1.0.0
  13552. */
  13553. basic_json(const value_t v)
  13554. : m_type(v), m_value(v)
  13555. {
  13556. assert_invariant();
  13557. }
  13558. /*!
  13559. @brief create a null object
  13560. Create a `null` JSON value. It either takes a null pointer as parameter
  13561. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  13562. The passed null pointer itself is not read -- it is only used to choose
  13563. the right constructor.
  13564. @complexity Constant.
  13565. @exceptionsafety No-throw guarantee: this constructor never throws
  13566. exceptions.
  13567. @liveexample{The following code shows the constructor with and without a
  13568. null pointer parameter.,basic_json__nullptr_t}
  13569. @since version 1.0.0
  13570. */
  13571. basic_json(std::nullptr_t = nullptr) noexcept
  13572. : basic_json(value_t::null)
  13573. {
  13574. assert_invariant();
  13575. }
  13576. /*!
  13577. @brief create a JSON value
  13578. This is a "catch all" constructor for all compatible JSON types; that is,
  13579. types for which a `to_json()` method exists. The constructor forwards the
  13580. parameter @a val to that method (to `json_serializer<U>::to_json` method
  13581. with `U = uncvref_t<CompatibleType>`, to be exact).
  13582. Template type @a CompatibleType includes, but is not limited to, the
  13583. following types:
  13584. - **arrays**: @ref array_t and all kinds of compatible containers such as
  13585. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  13586. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  13587. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  13588. which a @ref basic_json value can be constructed.
  13589. - **objects**: @ref object_t and all kinds of compatible associative
  13590. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  13591. and `std::unordered_multimap` with a `key_type` compatible to
  13592. @ref string_t and a `value_type` from which a @ref basic_json value can
  13593. be constructed.
  13594. - **strings**: @ref string_t, string literals, and all compatible string
  13595. containers can be used.
  13596. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  13597. @ref number_float_t, and all convertible number types such as `int`,
  13598. `size_t`, `int64_t`, `float` or `double` can be used.
  13599. - **boolean**: @ref boolean_t / `bool` can be used.
  13600. See the examples below.
  13601. @tparam CompatibleType a type such that:
  13602. - @a CompatibleType is not derived from `std::istream`,
  13603. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  13604. constructors),
  13605. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  13606. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  13607. @ref json_pointer, @ref iterator, etc ...)
  13608. - @ref @ref json_serializer<U> has a
  13609. `to_json(basic_json_t&, CompatibleType&&)` method
  13610. @tparam U = `uncvref_t<CompatibleType>`
  13611. @param[in] val the value to be forwarded to the respective constructor
  13612. @complexity Usually linear in the size of the passed @a val, also
  13613. depending on the implementation of the called `to_json()`
  13614. method.
  13615. @exceptionsafety Depends on the called constructor. For types directly
  13616. supported by the library (i.e., all types for which no `to_json()` function
  13617. was provided), strong guarantee holds: if an exception is thrown, there are
  13618. no changes to any JSON value.
  13619. @liveexample{The following code shows the constructor with several
  13620. compatible types.,basic_json__CompatibleType}
  13621. @since version 2.1.0
  13622. */
  13623. template <typename CompatibleType,
  13624. typename U = detail::uncvref_t<CompatibleType>,
  13625. detail::enable_if_t<
  13626. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  13627. basic_json(CompatibleType && val) noexcept(noexcept(
  13628. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  13629. std::forward<CompatibleType>(val))))
  13630. {
  13631. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  13632. assert_invariant();
  13633. }
  13634. /*!
  13635. @brief create a JSON value from an existing one
  13636. This is a constructor for existing @ref basic_json types.
  13637. It does not hijack copy/move constructors, since the parameter has different
  13638. template arguments than the current ones.
  13639. The constructor tries to convert the internal @ref m_value of the parameter.
  13640. @tparam BasicJsonType a type such that:
  13641. - @a BasicJsonType is a @ref basic_json type.
  13642. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  13643. @param[in] val the @ref basic_json value to be converted.
  13644. @complexity Usually linear in the size of the passed @a val, also
  13645. depending on the implementation of the called `to_json()`
  13646. method.
  13647. @exceptionsafety Depends on the called constructor. For types directly
  13648. supported by the library (i.e., all types for which no `to_json()` function
  13649. was provided), strong guarantee holds: if an exception is thrown, there are
  13650. no changes to any JSON value.
  13651. @since version 3.2.0
  13652. */
  13653. template <typename BasicJsonType,
  13654. detail::enable_if_t<
  13655. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  13656. basic_json(const BasicJsonType& val)
  13657. {
  13658. using other_boolean_t = typename BasicJsonType::boolean_t;
  13659. using other_number_float_t = typename BasicJsonType::number_float_t;
  13660. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  13661. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13662. using other_string_t = typename BasicJsonType::string_t;
  13663. using other_object_t = typename BasicJsonType::object_t;
  13664. using other_array_t = typename BasicJsonType::array_t;
  13665. switch (val.type())
  13666. {
  13667. case value_t::boolean:
  13668. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  13669. break;
  13670. case value_t::number_float:
  13671. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  13672. break;
  13673. case value_t::number_integer:
  13674. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  13675. break;
  13676. case value_t::number_unsigned:
  13677. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  13678. break;
  13679. case value_t::string:
  13680. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  13681. break;
  13682. case value_t::object:
  13683. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  13684. break;
  13685. case value_t::array:
  13686. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  13687. break;
  13688. case value_t::null:
  13689. *this = nullptr;
  13690. break;
  13691. case value_t::discarded:
  13692. m_type = value_t::discarded;
  13693. break;
  13694. default: // LCOV_EXCL_LINE
  13695. assert(false); // LCOV_EXCL_LINE
  13696. }
  13697. assert_invariant();
  13698. }
  13699. /*!
  13700. @brief create a container (array or object) from an initializer list
  13701. Creates a JSON value of type array or object from the passed initializer
  13702. list @a init. In case @a type_deduction is `true` (default), the type of
  13703. the JSON value to be created is deducted from the initializer list @a init
  13704. according to the following rules:
  13705. 1. If the list is empty, an empty JSON object value `{}` is created.
  13706. 2. If the list consists of pairs whose first element is a string, a JSON
  13707. object value is created where the first elements of the pairs are
  13708. treated as keys and the second elements are as values.
  13709. 3. In all other cases, an array is created.
  13710. The rules aim to create the best fit between a C++ initializer list and
  13711. JSON values. The rationale is as follows:
  13712. 1. The empty initializer list is written as `{}` which is exactly an empty
  13713. JSON object.
  13714. 2. C++ has no way of describing mapped types other than to list a list of
  13715. pairs. As JSON requires that keys must be of type string, rule 2 is the
  13716. weakest constraint one can pose on initializer lists to interpret them
  13717. as an object.
  13718. 3. In all other cases, the initializer list could not be interpreted as
  13719. JSON object type, so interpreting it as JSON array type is safe.
  13720. With the rules described above, the following JSON values cannot be
  13721. expressed by an initializer list:
  13722. - the empty array (`[]`): use @ref array(initializer_list_t)
  13723. with an empty initializer list in this case
  13724. - arrays whose elements satisfy rule 2: use @ref
  13725. array(initializer_list_t) with the same initializer list
  13726. in this case
  13727. @note When used without parentheses around an empty initializer list, @ref
  13728. basic_json() is called instead of this function, yielding the JSON null
  13729. value.
  13730. @param[in] init initializer list with JSON values
  13731. @param[in] type_deduction internal parameter; when set to `true`, the type
  13732. of the JSON value is deducted from the initializer list @a init; when set
  13733. to `false`, the type provided via @a manual_type is forced. This mode is
  13734. used by the functions @ref array(initializer_list_t) and
  13735. @ref object(initializer_list_t).
  13736. @param[in] manual_type internal parameter; when @a type_deduction is set
  13737. to `false`, the created JSON value will use the provided type (only @ref
  13738. value_t::array and @ref value_t::object are valid); when @a type_deduction
  13739. is set to `true`, this parameter has no effect
  13740. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  13741. `value_t::object`, but @a init contains an element which is not a pair
  13742. whose first element is a string. In this case, the constructor could not
  13743. create an object. If @a type_deduction would have be `true`, an array
  13744. would have been created. See @ref object(initializer_list_t)
  13745. for an example.
  13746. @complexity Linear in the size of the initializer list @a init.
  13747. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13748. changes to any JSON value.
  13749. @liveexample{The example below shows how JSON values are created from
  13750. initializer lists.,basic_json__list_init_t}
  13751. @sa @ref array(initializer_list_t) -- create a JSON array
  13752. value from an initializer list
  13753. @sa @ref object(initializer_list_t) -- create a JSON object
  13754. value from an initializer list
  13755. @since version 1.0.0
  13756. */
  13757. basic_json(initializer_list_t init,
  13758. bool type_deduction = true,
  13759. value_t manual_type = value_t::array)
  13760. {
  13761. // check if each element is an array with two elements whose first
  13762. // element is a string
  13763. bool is_an_object = std::all_of(init.begin(), init.end(),
  13764. [](const detail::json_ref<basic_json>& element_ref)
  13765. {
  13766. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  13767. });
  13768. // adjust type if type deduction is not wanted
  13769. if (not type_deduction)
  13770. {
  13771. // if array is wanted, do not create an object though possible
  13772. if (manual_type == value_t::array)
  13773. {
  13774. is_an_object = false;
  13775. }
  13776. // if object is wanted but impossible, throw an exception
  13777. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  13778. {
  13779. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  13780. }
  13781. }
  13782. if (is_an_object)
  13783. {
  13784. // the initializer list is a list of pairs -> create object
  13785. m_type = value_t::object;
  13786. m_value = value_t::object;
  13787. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  13788. {
  13789. auto element = element_ref.moved_or_copied();
  13790. m_value.object->emplace(
  13791. std::move(*((*element.m_value.array)[0].m_value.string)),
  13792. std::move((*element.m_value.array)[1]));
  13793. });
  13794. }
  13795. else
  13796. {
  13797. // the initializer list describes an array -> create array
  13798. m_type = value_t::array;
  13799. m_value.array = create<array_t>(init.begin(), init.end());
  13800. }
  13801. assert_invariant();
  13802. }
  13803. /*!
  13804. @brief explicitly create an array from an initializer list
  13805. Creates a JSON array value from a given initializer list. That is, given a
  13806. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  13807. initializer list is empty, the empty array `[]` is created.
  13808. @note This function is only needed to express two edge cases that cannot
  13809. be realized with the initializer list constructor (@ref
  13810. basic_json(initializer_list_t, bool, value_t)). These cases
  13811. are:
  13812. 1. creating an array whose elements are all pairs whose first element is a
  13813. string -- in this case, the initializer list constructor would create an
  13814. object, taking the first elements as keys
  13815. 2. creating an empty array -- passing the empty initializer list to the
  13816. initializer list constructor yields an empty object
  13817. @param[in] init initializer list with JSON values to create an array from
  13818. (optional)
  13819. @return JSON array value
  13820. @complexity Linear in the size of @a init.
  13821. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13822. changes to any JSON value.
  13823. @liveexample{The following code shows an example for the `array`
  13824. function.,array}
  13825. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13826. create a JSON value from an initializer list
  13827. @sa @ref object(initializer_list_t) -- create a JSON object
  13828. value from an initializer list
  13829. @since version 1.0.0
  13830. */
  13831. JSON_HEDLEY_WARN_UNUSED_RESULT
  13832. static basic_json array(initializer_list_t init = {})
  13833. {
  13834. return basic_json(init, false, value_t::array);
  13835. }
  13836. /*!
  13837. @brief explicitly create an object from an initializer list
  13838. Creates a JSON object value from a given initializer list. The initializer
  13839. lists elements must be pairs, and their first elements must be strings. If
  13840. the initializer list is empty, the empty object `{}` is created.
  13841. @note This function is only added for symmetry reasons. In contrast to the
  13842. related function @ref array(initializer_list_t), there are
  13843. no cases which can only be expressed by this function. That is, any
  13844. initializer list @a init can also be passed to the initializer list
  13845. constructor @ref basic_json(initializer_list_t, bool, value_t).
  13846. @param[in] init initializer list to create an object from (optional)
  13847. @return JSON object value
  13848. @throw type_error.301 if @a init is not a list of pairs whose first
  13849. elements are strings. In this case, no object can be created. When such a
  13850. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  13851. an array would have been created from the passed initializer list @a init.
  13852. See example below.
  13853. @complexity Linear in the size of @a init.
  13854. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13855. changes to any JSON value.
  13856. @liveexample{The following code shows an example for the `object`
  13857. function.,object}
  13858. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13859. create a JSON value from an initializer list
  13860. @sa @ref array(initializer_list_t) -- create a JSON array
  13861. value from an initializer list
  13862. @since version 1.0.0
  13863. */
  13864. JSON_HEDLEY_WARN_UNUSED_RESULT
  13865. static basic_json object(initializer_list_t init = {})
  13866. {
  13867. return basic_json(init, false, value_t::object);
  13868. }
  13869. /*!
  13870. @brief construct an array with count copies of given value
  13871. Constructs a JSON array value by creating @a cnt copies of a passed value.
  13872. In case @a cnt is `0`, an empty array is created.
  13873. @param[in] cnt the number of JSON copies of @a val to create
  13874. @param[in] val the JSON value to copy
  13875. @post `std::distance(begin(),end()) == cnt` holds.
  13876. @complexity Linear in @a cnt.
  13877. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13878. changes to any JSON value.
  13879. @liveexample{The following code shows examples for the @ref
  13880. basic_json(size_type\, const basic_json&)
  13881. constructor.,basic_json__size_type_basic_json}
  13882. @since version 1.0.0
  13883. */
  13884. basic_json(size_type cnt, const basic_json& val)
  13885. : m_type(value_t::array)
  13886. {
  13887. m_value.array = create<array_t>(cnt, val);
  13888. assert_invariant();
  13889. }
  13890. /*!
  13891. @brief construct a JSON container given an iterator range
  13892. Constructs the JSON value with the contents of the range `[first, last)`.
  13893. The semantics depends on the different types a JSON value can have:
  13894. - In case of a null type, invalid_iterator.206 is thrown.
  13895. - In case of other primitive types (number, boolean, or string), @a first
  13896. must be `begin()` and @a last must be `end()`. In this case, the value is
  13897. copied. Otherwise, invalid_iterator.204 is thrown.
  13898. - In case of structured types (array, object), the constructor behaves as
  13899. similar versions for `std::vector` or `std::map`; that is, a JSON array
  13900. or object is constructed from the values in the range.
  13901. @tparam InputIT an input iterator type (@ref iterator or @ref
  13902. const_iterator)
  13903. @param[in] first begin of the range to copy from (included)
  13904. @param[in] last end of the range to copy from (excluded)
  13905. @pre Iterators @a first and @a last must be initialized. **This
  13906. precondition is enforced with an assertion (see warning).** If
  13907. assertions are switched off, a violation of this precondition yields
  13908. undefined behavior.
  13909. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  13910. checked efficiently. Only certain edge cases are detected; see the
  13911. description of the exceptions below. A violation of this precondition
  13912. yields undefined behavior.
  13913. @warning A precondition is enforced with a runtime assertion that will
  13914. result in calling `std::abort` if this precondition is not met.
  13915. Assertions can be disabled by defining `NDEBUG` at compile time.
  13916. See https://en.cppreference.com/w/cpp/error/assert for more
  13917. information.
  13918. @throw invalid_iterator.201 if iterators @a first and @a last are not
  13919. compatible (i.e., do not belong to the same JSON value). In this case,
  13920. the range `[first, last)` is undefined.
  13921. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  13922. primitive type (number, boolean, or string), but @a first does not point
  13923. to the first element any more. In this case, the range `[first, last)` is
  13924. undefined. See example code below.
  13925. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  13926. null value. In this case, the range `[first, last)` is undefined.
  13927. @complexity Linear in distance between @a first and @a last.
  13928. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13929. changes to any JSON value.
  13930. @liveexample{The example below shows several ways to create JSON values by
  13931. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  13932. @since version 1.0.0
  13933. */
  13934. template<class InputIT, typename std::enable_if<
  13935. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  13936. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  13937. basic_json(InputIT first, InputIT last)
  13938. {
  13939. assert(first.m_object != nullptr);
  13940. assert(last.m_object != nullptr);
  13941. // make sure iterator fits the current value
  13942. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  13943. {
  13944. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  13945. }
  13946. // copy type from first iterator
  13947. m_type = first.m_object->m_type;
  13948. // check if iterator range is complete for primitive values
  13949. switch (m_type)
  13950. {
  13951. case value_t::boolean:
  13952. case value_t::number_float:
  13953. case value_t::number_integer:
  13954. case value_t::number_unsigned:
  13955. case value_t::string:
  13956. {
  13957. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  13958. or not last.m_it.primitive_iterator.is_end()))
  13959. {
  13960. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13961. }
  13962. break;
  13963. }
  13964. default:
  13965. break;
  13966. }
  13967. switch (m_type)
  13968. {
  13969. case value_t::number_integer:
  13970. {
  13971. m_value.number_integer = first.m_object->m_value.number_integer;
  13972. break;
  13973. }
  13974. case value_t::number_unsigned:
  13975. {
  13976. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  13977. break;
  13978. }
  13979. case value_t::number_float:
  13980. {
  13981. m_value.number_float = first.m_object->m_value.number_float;
  13982. break;
  13983. }
  13984. case value_t::boolean:
  13985. {
  13986. m_value.boolean = first.m_object->m_value.boolean;
  13987. break;
  13988. }
  13989. case value_t::string:
  13990. {
  13991. m_value = *first.m_object->m_value.string;
  13992. break;
  13993. }
  13994. case value_t::object:
  13995. {
  13996. m_value.object = create<object_t>(first.m_it.object_iterator,
  13997. last.m_it.object_iterator);
  13998. break;
  13999. }
  14000. case value_t::array:
  14001. {
  14002. m_value.array = create<array_t>(first.m_it.array_iterator,
  14003. last.m_it.array_iterator);
  14004. break;
  14005. }
  14006. default:
  14007. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  14008. std::string(first.m_object->type_name())));
  14009. }
  14010. assert_invariant();
  14011. }
  14012. ///////////////////////////////////////
  14013. // other constructors and destructor //
  14014. ///////////////////////////////////////
  14015. /// @private
  14016. basic_json(const detail::json_ref<basic_json>& ref)
  14017. : basic_json(ref.moved_or_copied())
  14018. {}
  14019. /*!
  14020. @brief copy constructor
  14021. Creates a copy of a given JSON value.
  14022. @param[in] other the JSON value to copy
  14023. @post `*this == other`
  14024. @complexity Linear in the size of @a other.
  14025. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14026. changes to any JSON value.
  14027. @requirement This function helps `basic_json` satisfying the
  14028. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14029. requirements:
  14030. - The complexity is linear.
  14031. - As postcondition, it holds: `other == basic_json(other)`.
  14032. @liveexample{The following code shows an example for the copy
  14033. constructor.,basic_json__basic_json}
  14034. @since version 1.0.0
  14035. */
  14036. basic_json(const basic_json& other)
  14037. : m_type(other.m_type)
  14038. {
  14039. // check of passed value is valid
  14040. other.assert_invariant();
  14041. switch (m_type)
  14042. {
  14043. case value_t::object:
  14044. {
  14045. m_value = *other.m_value.object;
  14046. break;
  14047. }
  14048. case value_t::array:
  14049. {
  14050. m_value = *other.m_value.array;
  14051. break;
  14052. }
  14053. case value_t::string:
  14054. {
  14055. m_value = *other.m_value.string;
  14056. break;
  14057. }
  14058. case value_t::boolean:
  14059. {
  14060. m_value = other.m_value.boolean;
  14061. break;
  14062. }
  14063. case value_t::number_integer:
  14064. {
  14065. m_value = other.m_value.number_integer;
  14066. break;
  14067. }
  14068. case value_t::number_unsigned:
  14069. {
  14070. m_value = other.m_value.number_unsigned;
  14071. break;
  14072. }
  14073. case value_t::number_float:
  14074. {
  14075. m_value = other.m_value.number_float;
  14076. break;
  14077. }
  14078. default:
  14079. break;
  14080. }
  14081. assert_invariant();
  14082. }
  14083. /*!
  14084. @brief move constructor
  14085. Move constructor. Constructs a JSON value with the contents of the given
  14086. value @a other using move semantics. It "steals" the resources from @a
  14087. other and leaves it as JSON null value.
  14088. @param[in,out] other value to move to this object
  14089. @post `*this` has the same value as @a other before the call.
  14090. @post @a other is a JSON null value.
  14091. @complexity Constant.
  14092. @exceptionsafety No-throw guarantee: this constructor never throws
  14093. exceptions.
  14094. @requirement This function helps `basic_json` satisfying the
  14095. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  14096. requirements.
  14097. @liveexample{The code below shows the move constructor explicitly called
  14098. via std::move.,basic_json__moveconstructor}
  14099. @since version 1.0.0
  14100. */
  14101. basic_json(basic_json&& other) noexcept
  14102. : m_type(std::move(other.m_type)),
  14103. m_value(std::move(other.m_value))
  14104. {
  14105. // check that passed value is valid
  14106. other.assert_invariant();
  14107. // invalidate payload
  14108. other.m_type = value_t::null;
  14109. other.m_value = {};
  14110. assert_invariant();
  14111. }
  14112. /*!
  14113. @brief copy assignment
  14114. Copy assignment operator. Copies a JSON value via the "copy and swap"
  14115. strategy: It is expressed in terms of the copy constructor, destructor,
  14116. and the `swap()` member function.
  14117. @param[in] other value to copy from
  14118. @complexity Linear.
  14119. @requirement This function helps `basic_json` satisfying the
  14120. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14121. requirements:
  14122. - The complexity is linear.
  14123. @liveexample{The code below shows and example for the copy assignment. It
  14124. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  14125. copy of `a` (which is the null value after the swap) is
  14126. destroyed.,basic_json__copyassignment}
  14127. @since version 1.0.0
  14128. */
  14129. basic_json& operator=(basic_json other) noexcept (
  14130. std::is_nothrow_move_constructible<value_t>::value and
  14131. std::is_nothrow_move_assignable<value_t>::value and
  14132. std::is_nothrow_move_constructible<json_value>::value and
  14133. std::is_nothrow_move_assignable<json_value>::value
  14134. )
  14135. {
  14136. // check that passed value is valid
  14137. other.assert_invariant();
  14138. using std::swap;
  14139. swap(m_type, other.m_type);
  14140. swap(m_value, other.m_value);
  14141. assert_invariant();
  14142. return *this;
  14143. }
  14144. /*!
  14145. @brief destructor
  14146. Destroys the JSON value and frees all allocated memory.
  14147. @complexity Linear.
  14148. @requirement This function helps `basic_json` satisfying the
  14149. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14150. requirements:
  14151. - The complexity is linear.
  14152. - All stored elements are destroyed and all memory is freed.
  14153. @since version 1.0.0
  14154. */
  14155. ~basic_json() noexcept
  14156. {
  14157. assert_invariant();
  14158. m_value.destroy(m_type);
  14159. }
  14160. /// @}
  14161. public:
  14162. ///////////////////////
  14163. // object inspection //
  14164. ///////////////////////
  14165. /// @name object inspection
  14166. /// Functions to inspect the type of a JSON value.
  14167. /// @{
  14168. /*!
  14169. @brief serialization
  14170. Serialization function for JSON values. The function tries to mimic
  14171. Python's `json.dumps()` function, and currently supports its @a indent
  14172. and @a ensure_ascii parameters.
  14173. @param[in] indent If indent is nonnegative, then array elements and object
  14174. members will be pretty-printed with that indent level. An indent level of
  14175. `0` will only insert newlines. `-1` (the default) selects the most compact
  14176. representation.
  14177. @param[in] indent_char The character to use for indentation if @a indent is
  14178. greater than `0`. The default is ` ` (space).
  14179. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14180. in the output are escaped with `\uXXXX` sequences, and the result consists
  14181. of ASCII characters only.
  14182. @param[in] error_handler how to react on decoding errors; there are three
  14183. possible values: `strict` (throws and exception in case a decoding error
  14184. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  14185. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  14186. @return string containing the serialization of the JSON value
  14187. @throw type_error.316 if a string stored inside the JSON value is not
  14188. UTF-8 encoded
  14189. @complexity Linear.
  14190. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14191. changes in the JSON value.
  14192. @liveexample{The following example shows the effect of different @a indent\,
  14193. @a indent_char\, and @a ensure_ascii parameters to the result of the
  14194. serialization.,dump}
  14195. @see https://docs.python.org/2/library/json.html#json.dump
  14196. @since version 1.0.0; indentation character @a indent_char, option
  14197. @a ensure_ascii and exceptions added in version 3.0.0; error
  14198. handlers added in version 3.4.0.
  14199. */
  14200. string_t dump(const int indent = -1,
  14201. const char indent_char = ' ',
  14202. const bool ensure_ascii = false,
  14203. const error_handler_t error_handler = error_handler_t::strict) const
  14204. {
  14205. string_t result;
  14206. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  14207. if (indent >= 0)
  14208. {
  14209. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  14210. }
  14211. else
  14212. {
  14213. s.dump(*this, false, ensure_ascii, 0);
  14214. }
  14215. return result;
  14216. }
  14217. /*!
  14218. @brief return the type of the JSON value (explicit)
  14219. Return the type of the JSON value as a value from the @ref value_t
  14220. enumeration.
  14221. @return the type of the JSON value
  14222. Value type | return value
  14223. ------------------------- | -------------------------
  14224. null | value_t::null
  14225. boolean | value_t::boolean
  14226. string | value_t::string
  14227. number (integer) | value_t::number_integer
  14228. number (unsigned integer) | value_t::number_unsigned
  14229. number (floating-point) | value_t::number_float
  14230. object | value_t::object
  14231. array | value_t::array
  14232. discarded | value_t::discarded
  14233. @complexity Constant.
  14234. @exceptionsafety No-throw guarantee: this member function never throws
  14235. exceptions.
  14236. @liveexample{The following code exemplifies `type()` for all JSON
  14237. types.,type}
  14238. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  14239. @sa @ref type_name() -- return the type as string
  14240. @since version 1.0.0
  14241. */
  14242. constexpr value_t type() const noexcept
  14243. {
  14244. return m_type;
  14245. }
  14246. /*!
  14247. @brief return whether type is primitive
  14248. This function returns true if and only if the JSON type is primitive
  14249. (string, number, boolean, or null).
  14250. @return `true` if type is primitive (string, number, boolean, or null),
  14251. `false` otherwise.
  14252. @complexity Constant.
  14253. @exceptionsafety No-throw guarantee: this member function never throws
  14254. exceptions.
  14255. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  14256. types.,is_primitive}
  14257. @sa @ref is_structured() -- returns whether JSON value is structured
  14258. @sa @ref is_null() -- returns whether JSON value is `null`
  14259. @sa @ref is_string() -- returns whether JSON value is a string
  14260. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  14261. @sa @ref is_number() -- returns whether JSON value is a number
  14262. @since version 1.0.0
  14263. */
  14264. constexpr bool is_primitive() const noexcept
  14265. {
  14266. return is_null() or is_string() or is_boolean() or is_number();
  14267. }
  14268. /*!
  14269. @brief return whether type is structured
  14270. This function returns true if and only if the JSON type is structured
  14271. (array or object).
  14272. @return `true` if type is structured (array or object), `false` otherwise.
  14273. @complexity Constant.
  14274. @exceptionsafety No-throw guarantee: this member function never throws
  14275. exceptions.
  14276. @liveexample{The following code exemplifies `is_structured()` for all JSON
  14277. types.,is_structured}
  14278. @sa @ref is_primitive() -- returns whether value is primitive
  14279. @sa @ref is_array() -- returns whether value is an array
  14280. @sa @ref is_object() -- returns whether value is an object
  14281. @since version 1.0.0
  14282. */
  14283. constexpr bool is_structured() const noexcept
  14284. {
  14285. return is_array() or is_object();
  14286. }
  14287. /*!
  14288. @brief return whether value is null
  14289. This function returns true if and only if the JSON value is null.
  14290. @return `true` if type is null, `false` otherwise.
  14291. @complexity Constant.
  14292. @exceptionsafety No-throw guarantee: this member function never throws
  14293. exceptions.
  14294. @liveexample{The following code exemplifies `is_null()` for all JSON
  14295. types.,is_null}
  14296. @since version 1.0.0
  14297. */
  14298. constexpr bool is_null() const noexcept
  14299. {
  14300. return m_type == value_t::null;
  14301. }
  14302. /*!
  14303. @brief return whether value is a boolean
  14304. This function returns true if and only if the JSON value is a boolean.
  14305. @return `true` if type is boolean, `false` otherwise.
  14306. @complexity Constant.
  14307. @exceptionsafety No-throw guarantee: this member function never throws
  14308. exceptions.
  14309. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  14310. types.,is_boolean}
  14311. @since version 1.0.0
  14312. */
  14313. constexpr bool is_boolean() const noexcept
  14314. {
  14315. return m_type == value_t::boolean;
  14316. }
  14317. /*!
  14318. @brief return whether value is a number
  14319. This function returns true if and only if the JSON value is a number. This
  14320. includes both integer (signed and unsigned) and floating-point values.
  14321. @return `true` if type is number (regardless whether integer, unsigned
  14322. integer or floating-type), `false` otherwise.
  14323. @complexity Constant.
  14324. @exceptionsafety No-throw guarantee: this member function never throws
  14325. exceptions.
  14326. @liveexample{The following code exemplifies `is_number()` for all JSON
  14327. types.,is_number}
  14328. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14329. integer number
  14330. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14331. number
  14332. @sa @ref is_number_float() -- check if value is a floating-point number
  14333. @since version 1.0.0
  14334. */
  14335. constexpr bool is_number() const noexcept
  14336. {
  14337. return is_number_integer() or is_number_float();
  14338. }
  14339. /*!
  14340. @brief return whether value is an integer number
  14341. This function returns true if and only if the JSON value is a signed or
  14342. unsigned integer number. This excludes floating-point values.
  14343. @return `true` if type is an integer or unsigned integer number, `false`
  14344. otherwise.
  14345. @complexity Constant.
  14346. @exceptionsafety No-throw guarantee: this member function never throws
  14347. exceptions.
  14348. @liveexample{The following code exemplifies `is_number_integer()` for all
  14349. JSON types.,is_number_integer}
  14350. @sa @ref is_number() -- check if value is a number
  14351. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14352. number
  14353. @sa @ref is_number_float() -- check if value is a floating-point number
  14354. @since version 1.0.0
  14355. */
  14356. constexpr bool is_number_integer() const noexcept
  14357. {
  14358. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  14359. }
  14360. /*!
  14361. @brief return whether value is an unsigned integer number
  14362. This function returns true if and only if the JSON value is an unsigned
  14363. integer number. This excludes floating-point and signed integer values.
  14364. @return `true` if type is an unsigned integer number, `false` otherwise.
  14365. @complexity Constant.
  14366. @exceptionsafety No-throw guarantee: this member function never throws
  14367. exceptions.
  14368. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  14369. JSON types.,is_number_unsigned}
  14370. @sa @ref is_number() -- check if value is a number
  14371. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14372. integer number
  14373. @sa @ref is_number_float() -- check if value is a floating-point number
  14374. @since version 2.0.0
  14375. */
  14376. constexpr bool is_number_unsigned() const noexcept
  14377. {
  14378. return m_type == value_t::number_unsigned;
  14379. }
  14380. /*!
  14381. @brief return whether value is a floating-point number
  14382. This function returns true if and only if the JSON value is a
  14383. floating-point number. This excludes signed and unsigned integer values.
  14384. @return `true` if type is a floating-point number, `false` otherwise.
  14385. @complexity Constant.
  14386. @exceptionsafety No-throw guarantee: this member function never throws
  14387. exceptions.
  14388. @liveexample{The following code exemplifies `is_number_float()` for all
  14389. JSON types.,is_number_float}
  14390. @sa @ref is_number() -- check if value is number
  14391. @sa @ref is_number_integer() -- check if value is an integer number
  14392. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14393. number
  14394. @since version 1.0.0
  14395. */
  14396. constexpr bool is_number_float() const noexcept
  14397. {
  14398. return m_type == value_t::number_float;
  14399. }
  14400. /*!
  14401. @brief return whether value is an object
  14402. This function returns true if and only if the JSON value is an object.
  14403. @return `true` if type is object, `false` otherwise.
  14404. @complexity Constant.
  14405. @exceptionsafety No-throw guarantee: this member function never throws
  14406. exceptions.
  14407. @liveexample{The following code exemplifies `is_object()` for all JSON
  14408. types.,is_object}
  14409. @since version 1.0.0
  14410. */
  14411. constexpr bool is_object() const noexcept
  14412. {
  14413. return m_type == value_t::object;
  14414. }
  14415. /*!
  14416. @brief return whether value is an array
  14417. This function returns true if and only if the JSON value is an array.
  14418. @return `true` if type is array, `false` otherwise.
  14419. @complexity Constant.
  14420. @exceptionsafety No-throw guarantee: this member function never throws
  14421. exceptions.
  14422. @liveexample{The following code exemplifies `is_array()` for all JSON
  14423. types.,is_array}
  14424. @since version 1.0.0
  14425. */
  14426. constexpr bool is_array() const noexcept
  14427. {
  14428. return m_type == value_t::array;
  14429. }
  14430. /*!
  14431. @brief return whether value is a string
  14432. This function returns true if and only if the JSON value is a string.
  14433. @return `true` if type is string, `false` otherwise.
  14434. @complexity Constant.
  14435. @exceptionsafety No-throw guarantee: this member function never throws
  14436. exceptions.
  14437. @liveexample{The following code exemplifies `is_string()` for all JSON
  14438. types.,is_string}
  14439. @since version 1.0.0
  14440. */
  14441. constexpr bool is_string() const noexcept
  14442. {
  14443. return m_type == value_t::string;
  14444. }
  14445. /*!
  14446. @brief return whether value is discarded
  14447. This function returns true if and only if the JSON value was discarded
  14448. during parsing with a callback function (see @ref parser_callback_t).
  14449. @note This function will always be `false` for JSON values after parsing.
  14450. That is, discarded values can only occur during parsing, but will be
  14451. removed when inside a structured value or replaced by null in other cases.
  14452. @return `true` if type is discarded, `false` otherwise.
  14453. @complexity Constant.
  14454. @exceptionsafety No-throw guarantee: this member function never throws
  14455. exceptions.
  14456. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  14457. types.,is_discarded}
  14458. @since version 1.0.0
  14459. */
  14460. constexpr bool is_discarded() const noexcept
  14461. {
  14462. return m_type == value_t::discarded;
  14463. }
  14464. /*!
  14465. @brief return the type of the JSON value (implicit)
  14466. Implicitly return the type of the JSON value as a value from the @ref
  14467. value_t enumeration.
  14468. @return the type of the JSON value
  14469. @complexity Constant.
  14470. @exceptionsafety No-throw guarantee: this member function never throws
  14471. exceptions.
  14472. @liveexample{The following code exemplifies the @ref value_t operator for
  14473. all JSON types.,operator__value_t}
  14474. @sa @ref type() -- return the type of the JSON value (explicit)
  14475. @sa @ref type_name() -- return the type as string
  14476. @since version 1.0.0
  14477. */
  14478. constexpr operator value_t() const noexcept
  14479. {
  14480. return m_type;
  14481. }
  14482. /// @}
  14483. private:
  14484. //////////////////
  14485. // value access //
  14486. //////////////////
  14487. /// get a boolean (explicit)
  14488. boolean_t get_impl(boolean_t* /*unused*/) const
  14489. {
  14490. if (JSON_HEDLEY_LIKELY(is_boolean()))
  14491. {
  14492. return m_value.boolean;
  14493. }
  14494. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  14495. }
  14496. /// get a pointer to the value (object)
  14497. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  14498. {
  14499. return is_object() ? m_value.object : nullptr;
  14500. }
  14501. /// get a pointer to the value (object)
  14502. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  14503. {
  14504. return is_object() ? m_value.object : nullptr;
  14505. }
  14506. /// get a pointer to the value (array)
  14507. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  14508. {
  14509. return is_array() ? m_value.array : nullptr;
  14510. }
  14511. /// get a pointer to the value (array)
  14512. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  14513. {
  14514. return is_array() ? m_value.array : nullptr;
  14515. }
  14516. /// get a pointer to the value (string)
  14517. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  14518. {
  14519. return is_string() ? m_value.string : nullptr;
  14520. }
  14521. /// get a pointer to the value (string)
  14522. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  14523. {
  14524. return is_string() ? m_value.string : nullptr;
  14525. }
  14526. /// get a pointer to the value (boolean)
  14527. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  14528. {
  14529. return is_boolean() ? &m_value.boolean : nullptr;
  14530. }
  14531. /// get a pointer to the value (boolean)
  14532. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  14533. {
  14534. return is_boolean() ? &m_value.boolean : nullptr;
  14535. }
  14536. /// get a pointer to the value (integer number)
  14537. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  14538. {
  14539. return is_number_integer() ? &m_value.number_integer : nullptr;
  14540. }
  14541. /// get a pointer to the value (integer number)
  14542. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  14543. {
  14544. return is_number_integer() ? &m_value.number_integer : nullptr;
  14545. }
  14546. /// get a pointer to the value (unsigned number)
  14547. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  14548. {
  14549. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14550. }
  14551. /// get a pointer to the value (unsigned number)
  14552. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  14553. {
  14554. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14555. }
  14556. /// get a pointer to the value (floating-point number)
  14557. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  14558. {
  14559. return is_number_float() ? &m_value.number_float : nullptr;
  14560. }
  14561. /// get a pointer to the value (floating-point number)
  14562. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  14563. {
  14564. return is_number_float() ? &m_value.number_float : nullptr;
  14565. }
  14566. /*!
  14567. @brief helper function to implement get_ref()
  14568. This function helps to implement get_ref() without code duplication for
  14569. const and non-const overloads
  14570. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  14571. @throw type_error.303 if ReferenceType does not match underlying value
  14572. type of the current JSON
  14573. */
  14574. template<typename ReferenceType, typename ThisType>
  14575. static ReferenceType get_ref_impl(ThisType& obj)
  14576. {
  14577. // delegate the call to get_ptr<>()
  14578. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  14579. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  14580. {
  14581. return *ptr;
  14582. }
  14583. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  14584. }
  14585. public:
  14586. /// @name value access
  14587. /// Direct access to the stored value of a JSON value.
  14588. /// @{
  14589. /*!
  14590. @brief get special-case overload
  14591. This overloads avoids a lot of template boilerplate, it can be seen as the
  14592. identity method
  14593. @tparam BasicJsonType == @ref basic_json
  14594. @return a copy of *this
  14595. @complexity Constant.
  14596. @since version 2.1.0
  14597. */
  14598. template<typename BasicJsonType, detail::enable_if_t<
  14599. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  14600. int> = 0>
  14601. basic_json get() const
  14602. {
  14603. return *this;
  14604. }
  14605. /*!
  14606. @brief get special-case overload
  14607. This overloads converts the current @ref basic_json in a different
  14608. @ref basic_json type
  14609. @tparam BasicJsonType == @ref basic_json
  14610. @return a copy of *this, converted into @tparam BasicJsonType
  14611. @complexity Depending on the implementation of the called `from_json()`
  14612. method.
  14613. @since version 3.2.0
  14614. */
  14615. template<typename BasicJsonType, detail::enable_if_t<
  14616. not std::is_same<BasicJsonType, basic_json>::value and
  14617. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  14618. BasicJsonType get() const
  14619. {
  14620. return *this;
  14621. }
  14622. /*!
  14623. @brief get a value (explicit)
  14624. Explicit type conversion between the JSON value and a compatible value
  14625. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14626. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14627. The value is converted by calling the @ref json_serializer<ValueType>
  14628. `from_json()` method.
  14629. The function is equivalent to executing
  14630. @code {.cpp}
  14631. ValueType ret;
  14632. JSONSerializer<ValueType>::from_json(*this, ret);
  14633. return ret;
  14634. @endcode
  14635. This overloads is chosen if:
  14636. - @a ValueType is not @ref basic_json,
  14637. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14638. `void from_json(const basic_json&, ValueType&)`, and
  14639. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  14640. the form `ValueType from_json(const basic_json&)`
  14641. @tparam ValueTypeCV the provided value type
  14642. @tparam ValueType the returned value type
  14643. @return copy of the JSON value, converted to @a ValueType
  14644. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14645. @liveexample{The example below shows several conversions from JSON values
  14646. to other types. There a few things to note: (1) Floating-point numbers can
  14647. be converted to integers\, (2) A JSON array can be converted to a standard
  14648. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14649. associative containers such as `std::unordered_map<std::string\,
  14650. json>`.,get__ValueType_const}
  14651. @since version 2.1.0
  14652. */
  14653. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14654. detail::enable_if_t <
  14655. not detail::is_basic_json<ValueType>::value and
  14656. detail::has_from_json<basic_json_t, ValueType>::value and
  14657. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14658. int> = 0>
  14659. ValueType get() const noexcept(noexcept(
  14660. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  14661. {
  14662. // we cannot static_assert on ValueTypeCV being non-const, because
  14663. // there is support for get<const basic_json_t>(), which is why we
  14664. // still need the uncvref
  14665. static_assert(not std::is_reference<ValueTypeCV>::value,
  14666. "get() cannot be used with reference types, you might want to use get_ref()");
  14667. static_assert(std::is_default_constructible<ValueType>::value,
  14668. "types must be DefaultConstructible when used with get()");
  14669. ValueType ret;
  14670. JSONSerializer<ValueType>::from_json(*this, ret);
  14671. return ret;
  14672. }
  14673. /*!
  14674. @brief get a value (explicit); special case
  14675. Explicit type conversion between the JSON value and a compatible value
  14676. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14677. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14678. The value is converted by calling the @ref json_serializer<ValueType>
  14679. `from_json()` method.
  14680. The function is equivalent to executing
  14681. @code {.cpp}
  14682. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14683. @endcode
  14684. This overloads is chosen if:
  14685. - @a ValueType is not @ref basic_json and
  14686. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14687. `ValueType from_json(const basic_json&)`
  14688. @note If @ref json_serializer<ValueType> has both overloads of
  14689. `from_json()`, this one is chosen.
  14690. @tparam ValueTypeCV the provided value type
  14691. @tparam ValueType the returned value type
  14692. @return copy of the JSON value, converted to @a ValueType
  14693. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14694. @since version 2.1.0
  14695. */
  14696. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14697. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  14698. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14699. int> = 0>
  14700. ValueType get() const noexcept(noexcept(
  14701. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  14702. {
  14703. static_assert(not std::is_reference<ValueTypeCV>::value,
  14704. "get() cannot be used with reference types, you might want to use get_ref()");
  14705. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14706. }
  14707. /*!
  14708. @brief get a value (explicit)
  14709. Explicit type conversion between the JSON value and a compatible value.
  14710. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  14711. `from_json()` method.
  14712. The function is equivalent to executing
  14713. @code {.cpp}
  14714. ValueType v;
  14715. JSONSerializer<ValueType>::from_json(*this, v);
  14716. @endcode
  14717. This overloads is chosen if:
  14718. - @a ValueType is not @ref basic_json,
  14719. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14720. `void from_json(const basic_json&, ValueType&)`, and
  14721. @tparam ValueType the input parameter type.
  14722. @return the input parameter, allowing chaining calls.
  14723. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14724. @liveexample{The example below shows several conversions from JSON values
  14725. to other types. There a few things to note: (1) Floating-point numbers can
  14726. be converted to integers\, (2) A JSON array can be converted to a standard
  14727. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14728. associative containers such as `std::unordered_map<std::string\,
  14729. json>`.,get_to}
  14730. @since version 3.3.0
  14731. */
  14732. template<typename ValueType,
  14733. detail::enable_if_t <
  14734. not detail::is_basic_json<ValueType>::value and
  14735. detail::has_from_json<basic_json_t, ValueType>::value,
  14736. int> = 0>
  14737. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  14738. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  14739. {
  14740. JSONSerializer<ValueType>::from_json(*this, v);
  14741. return v;
  14742. }
  14743. template <
  14744. typename T, std::size_t N,
  14745. typename Array = T (&)[N],
  14746. detail::enable_if_t <
  14747. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  14748. Array get_to(T (&v)[N]) const
  14749. noexcept(noexcept(JSONSerializer<Array>::from_json(
  14750. std::declval<const basic_json_t&>(), v)))
  14751. {
  14752. JSONSerializer<Array>::from_json(*this, v);
  14753. return v;
  14754. }
  14755. /*!
  14756. @brief get a pointer value (implicit)
  14757. Implicit pointer access to the internally stored JSON value. No copies are
  14758. made.
  14759. @warning Writing data to the pointee of the result yields an undefined
  14760. state.
  14761. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14762. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14763. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  14764. assertion.
  14765. @return pointer to the internally stored JSON value if the requested
  14766. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14767. @complexity Constant.
  14768. @liveexample{The example below shows how pointers to internal values of a
  14769. JSON value can be requested. Note that no type conversions are made and a
  14770. `nullptr` is returned if the value and the requested pointer type does not
  14771. match.,get_ptr}
  14772. @since version 1.0.0
  14773. */
  14774. template<typename PointerType, typename std::enable_if<
  14775. std::is_pointer<PointerType>::value, int>::type = 0>
  14776. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14777. {
  14778. // delegate the call to get_impl_ptr<>()
  14779. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14780. }
  14781. /*!
  14782. @brief get a pointer value (implicit)
  14783. @copydoc get_ptr()
  14784. */
  14785. template<typename PointerType, typename std::enable_if<
  14786. std::is_pointer<PointerType>::value and
  14787. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  14788. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14789. {
  14790. // delegate the call to get_impl_ptr<>() const
  14791. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14792. }
  14793. /*!
  14794. @brief get a pointer value (explicit)
  14795. Explicit pointer access to the internally stored JSON value. No copies are
  14796. made.
  14797. @warning The pointer becomes invalid if the underlying JSON object
  14798. changes.
  14799. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14800. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14801. @ref number_unsigned_t, or @ref number_float_t.
  14802. @return pointer to the internally stored JSON value if the requested
  14803. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14804. @complexity Constant.
  14805. @liveexample{The example below shows how pointers to internal values of a
  14806. JSON value can be requested. Note that no type conversions are made and a
  14807. `nullptr` is returned if the value and the requested pointer type does not
  14808. match.,get__PointerType}
  14809. @sa @ref get_ptr() for explicit pointer-member access
  14810. @since version 1.0.0
  14811. */
  14812. template<typename PointerType, typename std::enable_if<
  14813. std::is_pointer<PointerType>::value, int>::type = 0>
  14814. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  14815. {
  14816. // delegate the call to get_ptr
  14817. return get_ptr<PointerType>();
  14818. }
  14819. /*!
  14820. @brief get a pointer value (explicit)
  14821. @copydoc get()
  14822. */
  14823. template<typename PointerType, typename std::enable_if<
  14824. std::is_pointer<PointerType>::value, int>::type = 0>
  14825. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  14826. {
  14827. // delegate the call to get_ptr
  14828. return get_ptr<PointerType>();
  14829. }
  14830. /*!
  14831. @brief get a reference value (implicit)
  14832. Implicit reference access to the internally stored JSON value. No copies
  14833. are made.
  14834. @warning Writing data to the referee of the result yields an undefined
  14835. state.
  14836. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  14837. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  14838. @ref number_float_t. Enforced by static assertion.
  14839. @return reference to the internally stored JSON value if the requested
  14840. reference type @a ReferenceType fits to the JSON value; throws
  14841. type_error.303 otherwise
  14842. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  14843. with the stored JSON value; see example below
  14844. @complexity Constant.
  14845. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  14846. @since version 1.1.0
  14847. */
  14848. template<typename ReferenceType, typename std::enable_if<
  14849. std::is_reference<ReferenceType>::value, int>::type = 0>
  14850. ReferenceType get_ref()
  14851. {
  14852. // delegate call to get_ref_impl
  14853. return get_ref_impl<ReferenceType>(*this);
  14854. }
  14855. /*!
  14856. @brief get a reference value (implicit)
  14857. @copydoc get_ref()
  14858. */
  14859. template<typename ReferenceType, typename std::enable_if<
  14860. std::is_reference<ReferenceType>::value and
  14861. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  14862. ReferenceType get_ref() const
  14863. {
  14864. // delegate call to get_ref_impl
  14865. return get_ref_impl<ReferenceType>(*this);
  14866. }
  14867. /*!
  14868. @brief get a value (implicit)
  14869. Implicit type conversion between the JSON value and a compatible value.
  14870. The call is realized by calling @ref get() const.
  14871. @tparam ValueType non-pointer type compatible to the JSON value, for
  14872. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  14873. `std::vector` types for JSON arrays. The character type of @ref string_t
  14874. as well as an initializer list of this type is excluded to avoid
  14875. ambiguities as these types implicitly convert to `std::string`.
  14876. @return copy of the JSON value, converted to type @a ValueType
  14877. @throw type_error.302 in case passed type @a ValueType is incompatible
  14878. to the JSON value type (e.g., the JSON value is of type boolean, but a
  14879. string is requested); see example below
  14880. @complexity Linear in the size of the JSON value.
  14881. @liveexample{The example below shows several conversions from JSON values
  14882. to other types. There a few things to note: (1) Floating-point numbers can
  14883. be converted to integers\, (2) A JSON array can be converted to a standard
  14884. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14885. associative containers such as `std::unordered_map<std::string\,
  14886. json>`.,operator__ValueType}
  14887. @since version 1.0.0
  14888. */
  14889. template < typename ValueType, typename std::enable_if <
  14890. not std::is_pointer<ValueType>::value and
  14891. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  14892. not std::is_same<ValueType, typename string_t::value_type>::value and
  14893. not detail::is_basic_json<ValueType>::value
  14894. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  14895. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  14896. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  14897. and not std::is_same<ValueType, typename std::string_view>::value
  14898. #endif
  14899. #endif
  14900. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  14901. , int >::type = 0 >
  14902. operator ValueType() const
  14903. {
  14904. // delegate the call to get<>() const
  14905. return get<ValueType>();
  14906. }
  14907. /// @}
  14908. ////////////////////
  14909. // element access //
  14910. ////////////////////
  14911. /// @name element access
  14912. /// Access to the JSON value.
  14913. /// @{
  14914. /*!
  14915. @brief access specified array element with bounds checking
  14916. Returns a reference to the element at specified location @a idx, with
  14917. bounds checking.
  14918. @param[in] idx index of the element to access
  14919. @return reference to the element at index @a idx
  14920. @throw type_error.304 if the JSON value is not an array; in this case,
  14921. calling `at` with an index makes no sense. See example below.
  14922. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14923. that is, `idx >= size()`. See example below.
  14924. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14925. changes in the JSON value.
  14926. @complexity Constant.
  14927. @since version 1.0.0
  14928. @liveexample{The example below shows how array elements can be read and
  14929. written using `at()`. It also demonstrates the different exceptions that
  14930. can be thrown.,at__size_type}
  14931. */
  14932. reference at(size_type idx)
  14933. {
  14934. // at only works for arrays
  14935. if (JSON_HEDLEY_LIKELY(is_array()))
  14936. {
  14937. JSON_TRY
  14938. {
  14939. return m_value.array->at(idx);
  14940. }
  14941. JSON_CATCH (std::out_of_range&)
  14942. {
  14943. // create better exception explanation
  14944. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14945. }
  14946. }
  14947. else
  14948. {
  14949. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14950. }
  14951. }
  14952. /*!
  14953. @brief access specified array element with bounds checking
  14954. Returns a const reference to the element at specified location @a idx,
  14955. with bounds checking.
  14956. @param[in] idx index of the element to access
  14957. @return const reference to the element at index @a idx
  14958. @throw type_error.304 if the JSON value is not an array; in this case,
  14959. calling `at` with an index makes no sense. See example below.
  14960. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14961. that is, `idx >= size()`. See example below.
  14962. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14963. changes in the JSON value.
  14964. @complexity Constant.
  14965. @since version 1.0.0
  14966. @liveexample{The example below shows how array elements can be read using
  14967. `at()`. It also demonstrates the different exceptions that can be thrown.,
  14968. at__size_type_const}
  14969. */
  14970. const_reference at(size_type idx) const
  14971. {
  14972. // at only works for arrays
  14973. if (JSON_HEDLEY_LIKELY(is_array()))
  14974. {
  14975. JSON_TRY
  14976. {
  14977. return m_value.array->at(idx);
  14978. }
  14979. JSON_CATCH (std::out_of_range&)
  14980. {
  14981. // create better exception explanation
  14982. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14983. }
  14984. }
  14985. else
  14986. {
  14987. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14988. }
  14989. }
  14990. /*!
  14991. @brief access specified object element with bounds checking
  14992. Returns a reference to the element at with specified key @a key, with
  14993. bounds checking.
  14994. @param[in] key key of the element to access
  14995. @return reference to the element at key @a key
  14996. @throw type_error.304 if the JSON value is not an object; in this case,
  14997. calling `at` with a key makes no sense. See example below.
  14998. @throw out_of_range.403 if the key @a key is is not stored in the object;
  14999. that is, `find(key) == end()`. See example below.
  15000. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15001. changes in the JSON value.
  15002. @complexity Logarithmic in the size of the container.
  15003. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15004. access by reference
  15005. @sa @ref value() for access by value with a default value
  15006. @since version 1.0.0
  15007. @liveexample{The example below shows how object elements can be read and
  15008. written using `at()`. It also demonstrates the different exceptions that
  15009. can be thrown.,at__object_t_key_type}
  15010. */
  15011. reference at(const typename object_t::key_type& key)
  15012. {
  15013. // at only works for objects
  15014. if (JSON_HEDLEY_LIKELY(is_object()))
  15015. {
  15016. JSON_TRY
  15017. {
  15018. return m_value.object->at(key);
  15019. }
  15020. JSON_CATCH (std::out_of_range&)
  15021. {
  15022. // create better exception explanation
  15023. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  15024. }
  15025. }
  15026. else
  15027. {
  15028. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  15029. }
  15030. }
  15031. /*!
  15032. @brief access specified object element with bounds checking
  15033. Returns a const reference to the element at with specified key @a key,
  15034. with bounds checking.
  15035. @param[in] key key of the element to access
  15036. @return const reference to the element at key @a key
  15037. @throw type_error.304 if the JSON value is not an object; in this case,
  15038. calling `at` with a key makes no sense. See example below.
  15039. @throw out_of_range.403 if the key @a key is is not stored in the object;
  15040. that is, `find(key) == end()`. See example below.
  15041. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15042. changes in the JSON value.
  15043. @complexity Logarithmic in the size of the container.
  15044. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15045. access by reference
  15046. @sa @ref value() for access by value with a default value
  15047. @since version 1.0.0
  15048. @liveexample{The example below shows how object elements can be read using
  15049. `at()`. It also demonstrates the different exceptions that can be thrown.,
  15050. at__object_t_key_type_const}
  15051. */
  15052. const_reference at(const typename object_t::key_type& key) const
  15053. {
  15054. // at only works for objects
  15055. if (JSON_HEDLEY_LIKELY(is_object()))
  15056. {
  15057. JSON_TRY
  15058. {
  15059. return m_value.object->at(key);
  15060. }
  15061. JSON_CATCH (std::out_of_range&)
  15062. {
  15063. // create better exception explanation
  15064. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  15065. }
  15066. }
  15067. else
  15068. {
  15069. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  15070. }
  15071. }
  15072. /*!
  15073. @brief access specified array element
  15074. Returns a reference to the element at specified location @a idx.
  15075. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  15076. then the array is silently filled up with `null` values to make `idx` a
  15077. valid reference to the last stored element.
  15078. @param[in] idx index of the element to access
  15079. @return reference to the element at index @a idx
  15080. @throw type_error.305 if the JSON value is not an array or null; in that
  15081. cases, using the [] operator with an index makes no sense.
  15082. @complexity Constant if @a idx is in the range of the array. Otherwise
  15083. linear in `idx - size()`.
  15084. @liveexample{The example below shows how array elements can be read and
  15085. written using `[]` operator. Note the addition of `null`
  15086. values.,operatorarray__size_type}
  15087. @since version 1.0.0
  15088. */
  15089. reference operator[](size_type idx)
  15090. {
  15091. // implicitly convert null value to an empty array
  15092. if (is_null())
  15093. {
  15094. m_type = value_t::array;
  15095. m_value.array = create<array_t>();
  15096. assert_invariant();
  15097. }
  15098. // operator[] only works for arrays
  15099. if (JSON_HEDLEY_LIKELY(is_array()))
  15100. {
  15101. // fill up array with null values if given idx is outside range
  15102. if (idx >= m_value.array->size())
  15103. {
  15104. m_value.array->insert(m_value.array->end(),
  15105. idx - m_value.array->size() + 1,
  15106. basic_json());
  15107. }
  15108. return m_value.array->operator[](idx);
  15109. }
  15110. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  15111. }
  15112. /*!
  15113. @brief access specified array element
  15114. Returns a const reference to the element at specified location @a idx.
  15115. @param[in] idx index of the element to access
  15116. @return const reference to the element at index @a idx
  15117. @throw type_error.305 if the JSON value is not an array; in that case,
  15118. using the [] operator with an index makes no sense.
  15119. @complexity Constant.
  15120. @liveexample{The example below shows how array elements can be read using
  15121. the `[]` operator.,operatorarray__size_type_const}
  15122. @since version 1.0.0
  15123. */
  15124. const_reference operator[](size_type idx) const
  15125. {
  15126. // const operator[] only works for arrays
  15127. if (JSON_HEDLEY_LIKELY(is_array()))
  15128. {
  15129. return m_value.array->operator[](idx);
  15130. }
  15131. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  15132. }
  15133. /*!
  15134. @brief access specified object element
  15135. Returns a reference to the element at with specified key @a key.
  15136. @note If @a key is not found in the object, then it is silently added to
  15137. the object and filled with a `null` value to make `key` a valid reference.
  15138. In case the value was `null` before, it is converted to an object.
  15139. @param[in] key key of the element to access
  15140. @return reference to the element at key @a key
  15141. @throw type_error.305 if the JSON value is not an object or null; in that
  15142. cases, using the [] operator with a key makes no sense.
  15143. @complexity Logarithmic in the size of the container.
  15144. @liveexample{The example below shows how object elements can be read and
  15145. written using the `[]` operator.,operatorarray__key_type}
  15146. @sa @ref at(const typename object_t::key_type&) for access by reference
  15147. with range checking
  15148. @sa @ref value() for access by value with a default value
  15149. @since version 1.0.0
  15150. */
  15151. reference operator[](const typename object_t::key_type& key)
  15152. {
  15153. // implicitly convert null value to an empty object
  15154. if (is_null())
  15155. {
  15156. m_type = value_t::object;
  15157. m_value.object = create<object_t>();
  15158. assert_invariant();
  15159. }
  15160. // operator[] only works for objects
  15161. if (JSON_HEDLEY_LIKELY(is_object()))
  15162. {
  15163. return m_value.object->operator[](key);
  15164. }
  15165. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15166. }
  15167. /*!
  15168. @brief read-only access specified object element
  15169. Returns a const reference to the element at with specified key @a key. No
  15170. bounds checking is performed.
  15171. @warning If the element with key @a key does not exist, the behavior is
  15172. undefined.
  15173. @param[in] key key of the element to access
  15174. @return const reference to the element at key @a key
  15175. @pre The element with key @a key must exist. **This precondition is
  15176. enforced with an assertion.**
  15177. @throw type_error.305 if the JSON value is not an object; in that case,
  15178. using the [] operator with a key makes no sense.
  15179. @complexity Logarithmic in the size of the container.
  15180. @liveexample{The example below shows how object elements can be read using
  15181. the `[]` operator.,operatorarray__key_type_const}
  15182. @sa @ref at(const typename object_t::key_type&) for access by reference
  15183. with range checking
  15184. @sa @ref value() for access by value with a default value
  15185. @since version 1.0.0
  15186. */
  15187. const_reference operator[](const typename object_t::key_type& key) const
  15188. {
  15189. // const operator[] only works for objects
  15190. if (JSON_HEDLEY_LIKELY(is_object()))
  15191. {
  15192. assert(m_value.object->find(key) != m_value.object->end());
  15193. return m_value.object->find(key)->second;
  15194. }
  15195. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15196. }
  15197. /*!
  15198. @brief access specified object element
  15199. Returns a reference to the element at with specified key @a key.
  15200. @note If @a key is not found in the object, then it is silently added to
  15201. the object and filled with a `null` value to make `key` a valid reference.
  15202. In case the value was `null` before, it is converted to an object.
  15203. @param[in] key key of the element to access
  15204. @return reference to the element at key @a key
  15205. @throw type_error.305 if the JSON value is not an object or null; in that
  15206. cases, using the [] operator with a key makes no sense.
  15207. @complexity Logarithmic in the size of the container.
  15208. @liveexample{The example below shows how object elements can be read and
  15209. written using the `[]` operator.,operatorarray__key_type}
  15210. @sa @ref at(const typename object_t::key_type&) for access by reference
  15211. with range checking
  15212. @sa @ref value() for access by value with a default value
  15213. @since version 1.1.0
  15214. */
  15215. template<typename T>
  15216. JSON_HEDLEY_NON_NULL(2)
  15217. reference operator[](T* key)
  15218. {
  15219. // implicitly convert null to object
  15220. if (is_null())
  15221. {
  15222. m_type = value_t::object;
  15223. m_value = value_t::object;
  15224. assert_invariant();
  15225. }
  15226. // at only works for objects
  15227. if (JSON_HEDLEY_LIKELY(is_object()))
  15228. {
  15229. return m_value.object->operator[](key);
  15230. }
  15231. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15232. }
  15233. /*!
  15234. @brief read-only access specified object element
  15235. Returns a const reference to the element at with specified key @a key. No
  15236. bounds checking is performed.
  15237. @warning If the element with key @a key does not exist, the behavior is
  15238. undefined.
  15239. @param[in] key key of the element to access
  15240. @return const reference to the element at key @a key
  15241. @pre The element with key @a key must exist. **This precondition is
  15242. enforced with an assertion.**
  15243. @throw type_error.305 if the JSON value is not an object; in that case,
  15244. using the [] operator with a key makes no sense.
  15245. @complexity Logarithmic in the size of the container.
  15246. @liveexample{The example below shows how object elements can be read using
  15247. the `[]` operator.,operatorarray__key_type_const}
  15248. @sa @ref at(const typename object_t::key_type&) for access by reference
  15249. with range checking
  15250. @sa @ref value() for access by value with a default value
  15251. @since version 1.1.0
  15252. */
  15253. template<typename T>
  15254. JSON_HEDLEY_NON_NULL(2)
  15255. const_reference operator[](T* key) const
  15256. {
  15257. // at only works for objects
  15258. if (JSON_HEDLEY_LIKELY(is_object()))
  15259. {
  15260. assert(m_value.object->find(key) != m_value.object->end());
  15261. return m_value.object->find(key)->second;
  15262. }
  15263. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15264. }
  15265. /*!
  15266. @brief access specified object element with default value
  15267. Returns either a copy of an object's element at the specified key @a key
  15268. or a given default value if no element with key @a key exists.
  15269. The function is basically equivalent to executing
  15270. @code {.cpp}
  15271. try {
  15272. return at(key);
  15273. } catch(out_of_range) {
  15274. return default_value;
  15275. }
  15276. @endcode
  15277. @note Unlike @ref at(const typename object_t::key_type&), this function
  15278. does not throw if the given key @a key was not found.
  15279. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  15280. function does not implicitly add an element to the position defined by @a
  15281. key. This function is furthermore also applicable to const objects.
  15282. @param[in] key key of the element to access
  15283. @param[in] default_value the value to return if @a key is not found
  15284. @tparam ValueType type compatible to JSON values, for instance `int` for
  15285. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15286. JSON arrays. Note the type of the expected value at @a key and the default
  15287. value @a default_value must be compatible.
  15288. @return copy of the element at key @a key or @a default_value if @a key
  15289. is not found
  15290. @throw type_error.302 if @a default_value does not match the type of the
  15291. value at @a key
  15292. @throw type_error.306 if the JSON value is not an object; in that case,
  15293. using `value()` with a key makes no sense.
  15294. @complexity Logarithmic in the size of the container.
  15295. @liveexample{The example below shows how object elements can be queried
  15296. with a default value.,basic_json__value}
  15297. @sa @ref at(const typename object_t::key_type&) for access by reference
  15298. with range checking
  15299. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15300. access by reference
  15301. @since version 1.0.0
  15302. */
  15303. template<class ValueType, typename std::enable_if<
  15304. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15305. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  15306. {
  15307. // at only works for objects
  15308. if (JSON_HEDLEY_LIKELY(is_object()))
  15309. {
  15310. // if key is found, return value and given default value otherwise
  15311. const auto it = find(key);
  15312. if (it != end())
  15313. {
  15314. return *it;
  15315. }
  15316. return default_value;
  15317. }
  15318. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15319. }
  15320. /*!
  15321. @brief overload for a default value of type const char*
  15322. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  15323. */
  15324. string_t value(const typename object_t::key_type& key, const char* default_value) const
  15325. {
  15326. return value(key, string_t(default_value));
  15327. }
  15328. /*!
  15329. @brief access specified object element via JSON Pointer with default value
  15330. Returns either a copy of an object's element at the specified key @a key
  15331. or a given default value if no element with key @a key exists.
  15332. The function is basically equivalent to executing
  15333. @code {.cpp}
  15334. try {
  15335. return at(ptr);
  15336. } catch(out_of_range) {
  15337. return default_value;
  15338. }
  15339. @endcode
  15340. @note Unlike @ref at(const json_pointer&), this function does not throw
  15341. if the given key @a key was not found.
  15342. @param[in] ptr a JSON pointer to the element to access
  15343. @param[in] default_value the value to return if @a ptr found no value
  15344. @tparam ValueType type compatible to JSON values, for instance `int` for
  15345. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15346. JSON arrays. Note the type of the expected value at @a key and the default
  15347. value @a default_value must be compatible.
  15348. @return copy of the element at key @a key or @a default_value if @a key
  15349. is not found
  15350. @throw type_error.302 if @a default_value does not match the type of the
  15351. value at @a ptr
  15352. @throw type_error.306 if the JSON value is not an object; in that case,
  15353. using `value()` with a key makes no sense.
  15354. @complexity Logarithmic in the size of the container.
  15355. @liveexample{The example below shows how object elements can be queried
  15356. with a default value.,basic_json__value_ptr}
  15357. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  15358. @since version 2.0.2
  15359. */
  15360. template<class ValueType, typename std::enable_if<
  15361. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15362. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  15363. {
  15364. // at only works for objects
  15365. if (JSON_HEDLEY_LIKELY(is_object()))
  15366. {
  15367. // if pointer resolves a value, return it or use default value
  15368. JSON_TRY
  15369. {
  15370. return ptr.get_checked(this);
  15371. }
  15372. JSON_INTERNAL_CATCH (out_of_range&)
  15373. {
  15374. return default_value;
  15375. }
  15376. }
  15377. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15378. }
  15379. /*!
  15380. @brief overload for a default value of type const char*
  15381. @copydoc basic_json::value(const json_pointer&, ValueType) const
  15382. */
  15383. JSON_HEDLEY_NON_NULL(3)
  15384. string_t value(const json_pointer& ptr, const char* default_value) const
  15385. {
  15386. return value(ptr, string_t(default_value));
  15387. }
  15388. /*!
  15389. @brief access the first element
  15390. Returns a reference to the first element in the container. For a JSON
  15391. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  15392. @return In case of a structured type (array or object), a reference to the
  15393. first element is returned. In case of number, string, or boolean values, a
  15394. reference to the value is returned.
  15395. @complexity Constant.
  15396. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15397. or an empty array or object (undefined behavior, **guarded by
  15398. assertions**).
  15399. @post The JSON value remains unchanged.
  15400. @throw invalid_iterator.214 when called on `null` value
  15401. @liveexample{The following code shows an example for `front()`.,front}
  15402. @sa @ref back() -- access the last element
  15403. @since version 1.0.0
  15404. */
  15405. reference front()
  15406. {
  15407. return *begin();
  15408. }
  15409. /*!
  15410. @copydoc basic_json::front()
  15411. */
  15412. const_reference front() const
  15413. {
  15414. return *cbegin();
  15415. }
  15416. /*!
  15417. @brief access the last element
  15418. Returns a reference to the last element in the container. For a JSON
  15419. container `c`, the expression `c.back()` is equivalent to
  15420. @code {.cpp}
  15421. auto tmp = c.end();
  15422. --tmp;
  15423. return *tmp;
  15424. @endcode
  15425. @return In case of a structured type (array or object), a reference to the
  15426. last element is returned. In case of number, string, or boolean values, a
  15427. reference to the value is returned.
  15428. @complexity Constant.
  15429. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15430. or an empty array or object (undefined behavior, **guarded by
  15431. assertions**).
  15432. @post The JSON value remains unchanged.
  15433. @throw invalid_iterator.214 when called on a `null` value. See example
  15434. below.
  15435. @liveexample{The following code shows an example for `back()`.,back}
  15436. @sa @ref front() -- access the first element
  15437. @since version 1.0.0
  15438. */
  15439. reference back()
  15440. {
  15441. auto tmp = end();
  15442. --tmp;
  15443. return *tmp;
  15444. }
  15445. /*!
  15446. @copydoc basic_json::back()
  15447. */
  15448. const_reference back() const
  15449. {
  15450. auto tmp = cend();
  15451. --tmp;
  15452. return *tmp;
  15453. }
  15454. /*!
  15455. @brief remove element given an iterator
  15456. Removes the element specified by iterator @a pos. The iterator @a pos must
  15457. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  15458. but is not dereferenceable) cannot be used as a value for @a pos.
  15459. If called on a primitive type other than `null`, the resulting JSON value
  15460. will be `null`.
  15461. @param[in] pos iterator to the element to remove
  15462. @return Iterator following the last removed element. If the iterator @a
  15463. pos refers to the last element, the `end()` iterator is returned.
  15464. @tparam IteratorType an @ref iterator or @ref const_iterator
  15465. @post Invalidates iterators and references at or after the point of the
  15466. erase, including the `end()` iterator.
  15467. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15468. erase() with null"`
  15469. @throw invalid_iterator.202 if called on an iterator which does not belong
  15470. to the current JSON value; example: `"iterator does not fit current
  15471. value"`
  15472. @throw invalid_iterator.205 if called on a primitive type with invalid
  15473. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  15474. out of range"`
  15475. @complexity The complexity depends on the type:
  15476. - objects: amortized constant
  15477. - arrays: linear in distance between @a pos and the end of the container
  15478. - strings: linear in the length of the string
  15479. - other types: constant
  15480. @liveexample{The example shows the result of `erase()` for different JSON
  15481. types.,erase__IteratorType}
  15482. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15483. the given range
  15484. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15485. from an object at the given key
  15486. @sa @ref erase(const size_type) -- removes the element from an array at
  15487. the given index
  15488. @since version 1.0.0
  15489. */
  15490. template<class IteratorType, typename std::enable_if<
  15491. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15492. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15493. = 0>
  15494. IteratorType erase(IteratorType pos)
  15495. {
  15496. // make sure iterator fits the current value
  15497. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  15498. {
  15499. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15500. }
  15501. IteratorType result = end();
  15502. switch (m_type)
  15503. {
  15504. case value_t::boolean:
  15505. case value_t::number_float:
  15506. case value_t::number_integer:
  15507. case value_t::number_unsigned:
  15508. case value_t::string:
  15509. {
  15510. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  15511. {
  15512. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  15513. }
  15514. if (is_string())
  15515. {
  15516. AllocatorType<string_t> alloc;
  15517. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15518. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15519. m_value.string = nullptr;
  15520. }
  15521. m_type = value_t::null;
  15522. assert_invariant();
  15523. break;
  15524. }
  15525. case value_t::object:
  15526. {
  15527. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  15528. break;
  15529. }
  15530. case value_t::array:
  15531. {
  15532. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  15533. break;
  15534. }
  15535. default:
  15536. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15537. }
  15538. return result;
  15539. }
  15540. /*!
  15541. @brief remove elements given an iterator range
  15542. Removes the element specified by the range `[first; last)`. The iterator
  15543. @a first does not need to be dereferenceable if `first == last`: erasing
  15544. an empty range is a no-op.
  15545. If called on a primitive type other than `null`, the resulting JSON value
  15546. will be `null`.
  15547. @param[in] first iterator to the beginning of the range to remove
  15548. @param[in] last iterator past the end of the range to remove
  15549. @return Iterator following the last removed element. If the iterator @a
  15550. second refers to the last element, the `end()` iterator is returned.
  15551. @tparam IteratorType an @ref iterator or @ref const_iterator
  15552. @post Invalidates iterators and references at or after the point of the
  15553. erase, including the `end()` iterator.
  15554. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15555. erase() with null"`
  15556. @throw invalid_iterator.203 if called on iterators which does not belong
  15557. to the current JSON value; example: `"iterators do not fit current value"`
  15558. @throw invalid_iterator.204 if called on a primitive type with invalid
  15559. iterators (i.e., if `first != begin()` and `last != end()`); example:
  15560. `"iterators out of range"`
  15561. @complexity The complexity depends on the type:
  15562. - objects: `log(size()) + std::distance(first, last)`
  15563. - arrays: linear in the distance between @a first and @a last, plus linear
  15564. in the distance between @a last and end of the container
  15565. - strings: linear in the length of the string
  15566. - other types: constant
  15567. @liveexample{The example shows the result of `erase()` for different JSON
  15568. types.,erase__IteratorType_IteratorType}
  15569. @sa @ref erase(IteratorType) -- removes the element at a given position
  15570. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15571. from an object at the given key
  15572. @sa @ref erase(const size_type) -- removes the element from an array at
  15573. the given index
  15574. @since version 1.0.0
  15575. */
  15576. template<class IteratorType, typename std::enable_if<
  15577. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15578. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15579. = 0>
  15580. IteratorType erase(IteratorType first, IteratorType last)
  15581. {
  15582. // make sure iterator fits the current value
  15583. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  15584. {
  15585. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  15586. }
  15587. IteratorType result = end();
  15588. switch (m_type)
  15589. {
  15590. case value_t::boolean:
  15591. case value_t::number_float:
  15592. case value_t::number_integer:
  15593. case value_t::number_unsigned:
  15594. case value_t::string:
  15595. {
  15596. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  15597. or not last.m_it.primitive_iterator.is_end()))
  15598. {
  15599. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15600. }
  15601. if (is_string())
  15602. {
  15603. AllocatorType<string_t> alloc;
  15604. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15605. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15606. m_value.string = nullptr;
  15607. }
  15608. m_type = value_t::null;
  15609. assert_invariant();
  15610. break;
  15611. }
  15612. case value_t::object:
  15613. {
  15614. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  15615. last.m_it.object_iterator);
  15616. break;
  15617. }
  15618. case value_t::array:
  15619. {
  15620. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  15621. last.m_it.array_iterator);
  15622. break;
  15623. }
  15624. default:
  15625. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15626. }
  15627. return result;
  15628. }
  15629. /*!
  15630. @brief remove element from a JSON object given a key
  15631. Removes elements from a JSON object with the key value @a key.
  15632. @param[in] key value of the elements to remove
  15633. @return Number of elements removed. If @a ObjectType is the default
  15634. `std::map` type, the return value will always be `0` (@a key was not
  15635. found) or `1` (@a key was found).
  15636. @post References and iterators to the erased elements are invalidated.
  15637. Other references and iterators are not affected.
  15638. @throw type_error.307 when called on a type other than JSON object;
  15639. example: `"cannot use erase() with null"`
  15640. @complexity `log(size()) + count(key)`
  15641. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  15642. @sa @ref erase(IteratorType) -- removes the element at a given position
  15643. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15644. the given range
  15645. @sa @ref erase(const size_type) -- removes the element from an array at
  15646. the given index
  15647. @since version 1.0.0
  15648. */
  15649. size_type erase(const typename object_t::key_type& key)
  15650. {
  15651. // this erase only works for objects
  15652. if (JSON_HEDLEY_LIKELY(is_object()))
  15653. {
  15654. return m_value.object->erase(key);
  15655. }
  15656. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15657. }
  15658. /*!
  15659. @brief remove element from a JSON array given an index
  15660. Removes element from a JSON array at the index @a idx.
  15661. @param[in] idx index of the element to remove
  15662. @throw type_error.307 when called on a type other than JSON object;
  15663. example: `"cannot use erase() with null"`
  15664. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  15665. is out of range"`
  15666. @complexity Linear in distance between @a idx and the end of the container.
  15667. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  15668. @sa @ref erase(IteratorType) -- removes the element at a given position
  15669. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15670. the given range
  15671. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15672. from an object at the given key
  15673. @since version 1.0.0
  15674. */
  15675. void erase(const size_type idx)
  15676. {
  15677. // this erase only works for arrays
  15678. if (JSON_HEDLEY_LIKELY(is_array()))
  15679. {
  15680. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  15681. {
  15682. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  15683. }
  15684. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  15685. }
  15686. else
  15687. {
  15688. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15689. }
  15690. }
  15691. /// @}
  15692. ////////////
  15693. // lookup //
  15694. ////////////
  15695. /// @name lookup
  15696. /// @{
  15697. /*!
  15698. @brief find an element in a JSON object
  15699. Finds an element in a JSON object with key equivalent to @a key. If the
  15700. element is not found or the JSON value is not an object, end() is
  15701. returned.
  15702. @note This method always returns @ref end() when executed on a JSON type
  15703. that is not an object.
  15704. @param[in] key key value of the element to search for.
  15705. @return Iterator to an element with key equivalent to @a key. If no such
  15706. element is found or the JSON value is not an object, past-the-end (see
  15707. @ref end()) iterator is returned.
  15708. @complexity Logarithmic in the size of the JSON object.
  15709. @liveexample{The example shows how `find()` is used.,find__key_type}
  15710. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  15711. @since version 1.0.0
  15712. */
  15713. template<typename KeyT>
  15714. iterator find(KeyT&& key)
  15715. {
  15716. auto result = end();
  15717. if (is_object())
  15718. {
  15719. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15720. }
  15721. return result;
  15722. }
  15723. /*!
  15724. @brief find an element in a JSON object
  15725. @copydoc find(KeyT&&)
  15726. */
  15727. template<typename KeyT>
  15728. const_iterator find(KeyT&& key) const
  15729. {
  15730. auto result = cend();
  15731. if (is_object())
  15732. {
  15733. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15734. }
  15735. return result;
  15736. }
  15737. /*!
  15738. @brief returns the number of occurrences of a key in a JSON object
  15739. Returns the number of elements with key @a key. If ObjectType is the
  15740. default `std::map` type, the return value will always be `0` (@a key was
  15741. not found) or `1` (@a key was found).
  15742. @note This method always returns `0` when executed on a JSON type that is
  15743. not an object.
  15744. @param[in] key key value of the element to count
  15745. @return Number of elements with key @a key. If the JSON value is not an
  15746. object, the return value will be `0`.
  15747. @complexity Logarithmic in the size of the JSON object.
  15748. @liveexample{The example shows how `count()` is used.,count}
  15749. @since version 1.0.0
  15750. */
  15751. template<typename KeyT>
  15752. size_type count(KeyT&& key) const
  15753. {
  15754. // return 0 for all nonobject types
  15755. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  15756. }
  15757. /*!
  15758. @brief check the existence of an element in a JSON object
  15759. Check whether an element exists in a JSON object with key equivalent to
  15760. @a key. If the element is not found or the JSON value is not an object,
  15761. false is returned.
  15762. @note This method always returns false when executed on a JSON type
  15763. that is not an object.
  15764. @param[in] key key value to check its existence.
  15765. @return true if an element with specified @a key exists. If no such
  15766. element with such key is found or the JSON value is not an object,
  15767. false is returned.
  15768. @complexity Logarithmic in the size of the JSON object.
  15769. @liveexample{The following code shows an example for `contains()`.,contains}
  15770. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  15771. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  15772. @since version 3.6.0
  15773. */
  15774. template<typename KeyT, typename std::enable_if<
  15775. not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
  15776. bool contains(KeyT && key) const
  15777. {
  15778. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  15779. }
  15780. /*!
  15781. @brief check the existence of an element in a JSON object given a JSON pointer
  15782. Check whether the given JSON pointer @a ptr can be resolved in the current
  15783. JSON value.
  15784. @note This method can be executed on any JSON value type.
  15785. @param[in] ptr JSON pointer to check its existence.
  15786. @return true if the JSON pointer can be resolved to a stored value, false
  15787. otherwise.
  15788. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  15789. @throw parse_error.106 if an array index begins with '0'
  15790. @throw parse_error.109 if an array index was not a number
  15791. @complexity Logarithmic in the size of the JSON object.
  15792. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  15793. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  15794. @since version 3.7.0
  15795. */
  15796. bool contains(const json_pointer& ptr) const
  15797. {
  15798. return ptr.contains(this);
  15799. }
  15800. /// @}
  15801. ///////////////
  15802. // iterators //
  15803. ///////////////
  15804. /// @name iterators
  15805. /// @{
  15806. /*!
  15807. @brief returns an iterator to the first element
  15808. Returns an iterator to the first element.
  15809. @image html range-begin-end.svg "Illustration from cppreference.com"
  15810. @return iterator to the first element
  15811. @complexity Constant.
  15812. @requirement This function helps `basic_json` satisfying the
  15813. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15814. requirements:
  15815. - The complexity is constant.
  15816. @liveexample{The following code shows an example for `begin()`.,begin}
  15817. @sa @ref cbegin() -- returns a const iterator to the beginning
  15818. @sa @ref end() -- returns an iterator to the end
  15819. @sa @ref cend() -- returns a const iterator to the end
  15820. @since version 1.0.0
  15821. */
  15822. iterator begin() noexcept
  15823. {
  15824. iterator result(this);
  15825. result.set_begin();
  15826. return result;
  15827. }
  15828. /*!
  15829. @copydoc basic_json::cbegin()
  15830. */
  15831. const_iterator begin() const noexcept
  15832. {
  15833. return cbegin();
  15834. }
  15835. /*!
  15836. @brief returns a const iterator to the first element
  15837. Returns a const iterator to the first element.
  15838. @image html range-begin-end.svg "Illustration from cppreference.com"
  15839. @return const iterator to the first element
  15840. @complexity Constant.
  15841. @requirement This function helps `basic_json` satisfying the
  15842. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15843. requirements:
  15844. - The complexity is constant.
  15845. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  15846. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  15847. @sa @ref begin() -- returns an iterator to the beginning
  15848. @sa @ref end() -- returns an iterator to the end
  15849. @sa @ref cend() -- returns a const iterator to the end
  15850. @since version 1.0.0
  15851. */
  15852. const_iterator cbegin() const noexcept
  15853. {
  15854. const_iterator result(this);
  15855. result.set_begin();
  15856. return result;
  15857. }
  15858. /*!
  15859. @brief returns an iterator to one past the last element
  15860. Returns an iterator to one past the last element.
  15861. @image html range-begin-end.svg "Illustration from cppreference.com"
  15862. @return iterator one past the last element
  15863. @complexity Constant.
  15864. @requirement This function helps `basic_json` satisfying the
  15865. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15866. requirements:
  15867. - The complexity is constant.
  15868. @liveexample{The following code shows an example for `end()`.,end}
  15869. @sa @ref cend() -- returns a const iterator to the end
  15870. @sa @ref begin() -- returns an iterator to the beginning
  15871. @sa @ref cbegin() -- returns a const iterator to the beginning
  15872. @since version 1.0.0
  15873. */
  15874. iterator end() noexcept
  15875. {
  15876. iterator result(this);
  15877. result.set_end();
  15878. return result;
  15879. }
  15880. /*!
  15881. @copydoc basic_json::cend()
  15882. */
  15883. const_iterator end() const noexcept
  15884. {
  15885. return cend();
  15886. }
  15887. /*!
  15888. @brief returns a const iterator to one past the last element
  15889. Returns a const iterator to one past the last element.
  15890. @image html range-begin-end.svg "Illustration from cppreference.com"
  15891. @return const iterator one past the last element
  15892. @complexity Constant.
  15893. @requirement This function helps `basic_json` satisfying the
  15894. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15895. requirements:
  15896. - The complexity is constant.
  15897. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  15898. @liveexample{The following code shows an example for `cend()`.,cend}
  15899. @sa @ref end() -- returns an iterator to the end
  15900. @sa @ref begin() -- returns an iterator to the beginning
  15901. @sa @ref cbegin() -- returns a const iterator to the beginning
  15902. @since version 1.0.0
  15903. */
  15904. const_iterator cend() const noexcept
  15905. {
  15906. const_iterator result(this);
  15907. result.set_end();
  15908. return result;
  15909. }
  15910. /*!
  15911. @brief returns an iterator to the reverse-beginning
  15912. Returns an iterator to the reverse-beginning; that is, the last element.
  15913. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15914. @complexity Constant.
  15915. @requirement This function helps `basic_json` satisfying the
  15916. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15917. requirements:
  15918. - The complexity is constant.
  15919. - Has the semantics of `reverse_iterator(end())`.
  15920. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  15921. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15922. @sa @ref rend() -- returns a reverse iterator to the end
  15923. @sa @ref crend() -- returns a const reverse iterator to the end
  15924. @since version 1.0.0
  15925. */
  15926. reverse_iterator rbegin() noexcept
  15927. {
  15928. return reverse_iterator(end());
  15929. }
  15930. /*!
  15931. @copydoc basic_json::crbegin()
  15932. */
  15933. const_reverse_iterator rbegin() const noexcept
  15934. {
  15935. return crbegin();
  15936. }
  15937. /*!
  15938. @brief returns an iterator to the reverse-end
  15939. Returns an iterator to the reverse-end; that is, one before the first
  15940. element.
  15941. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15942. @complexity Constant.
  15943. @requirement This function helps `basic_json` satisfying the
  15944. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15945. requirements:
  15946. - The complexity is constant.
  15947. - Has the semantics of `reverse_iterator(begin())`.
  15948. @liveexample{The following code shows an example for `rend()`.,rend}
  15949. @sa @ref crend() -- returns a const reverse iterator to the end
  15950. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15951. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15952. @since version 1.0.0
  15953. */
  15954. reverse_iterator rend() noexcept
  15955. {
  15956. return reverse_iterator(begin());
  15957. }
  15958. /*!
  15959. @copydoc basic_json::crend()
  15960. */
  15961. const_reverse_iterator rend() const noexcept
  15962. {
  15963. return crend();
  15964. }
  15965. /*!
  15966. @brief returns a const reverse iterator to the last element
  15967. Returns a const iterator to the reverse-beginning; that is, the last
  15968. element.
  15969. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15970. @complexity Constant.
  15971. @requirement This function helps `basic_json` satisfying the
  15972. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15973. requirements:
  15974. - The complexity is constant.
  15975. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  15976. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  15977. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15978. @sa @ref rend() -- returns a reverse iterator to the end
  15979. @sa @ref crend() -- returns a const reverse iterator to the end
  15980. @since version 1.0.0
  15981. */
  15982. const_reverse_iterator crbegin() const noexcept
  15983. {
  15984. return const_reverse_iterator(cend());
  15985. }
  15986. /*!
  15987. @brief returns a const reverse iterator to one before the first
  15988. Returns a const reverse iterator to the reverse-end; that is, one before
  15989. the first element.
  15990. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15991. @complexity Constant.
  15992. @requirement This function helps `basic_json` satisfying the
  15993. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15994. requirements:
  15995. - The complexity is constant.
  15996. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  15997. @liveexample{The following code shows an example for `crend()`.,crend}
  15998. @sa @ref rend() -- returns a reverse iterator to the end
  15999. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  16000. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  16001. @since version 1.0.0
  16002. */
  16003. const_reverse_iterator crend() const noexcept
  16004. {
  16005. return const_reverse_iterator(cbegin());
  16006. }
  16007. public:
  16008. /*!
  16009. @brief wrapper to access iterator member functions in range-based for
  16010. This function allows to access @ref iterator::key() and @ref
  16011. iterator::value() during range-based for loops. In these loops, a
  16012. reference to the JSON values is returned, so there is no access to the
  16013. underlying iterator.
  16014. For loop without iterator_wrapper:
  16015. @code{cpp}
  16016. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  16017. {
  16018. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  16019. }
  16020. @endcode
  16021. Range-based for loop without iterator proxy:
  16022. @code{cpp}
  16023. for (auto it : j_object)
  16024. {
  16025. // "it" is of type json::reference and has no key() member
  16026. std::cout << "value: " << it << '\n';
  16027. }
  16028. @endcode
  16029. Range-based for loop with iterator proxy:
  16030. @code{cpp}
  16031. for (auto it : json::iterator_wrapper(j_object))
  16032. {
  16033. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  16034. }
  16035. @endcode
  16036. @note When iterating over an array, `key()` will return the index of the
  16037. element as string (see example).
  16038. @param[in] ref reference to a JSON value
  16039. @return iteration proxy object wrapping @a ref with an interface to use in
  16040. range-based for loops
  16041. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  16042. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16043. changes in the JSON value.
  16044. @complexity Constant.
  16045. @note The name of this function is not yet final and may change in the
  16046. future.
  16047. @deprecated This stream operator is deprecated and will be removed in
  16048. future 4.0.0 of the library. Please use @ref items() instead;
  16049. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  16050. */
  16051. JSON_HEDLEY_DEPRECATED(3.1.0)
  16052. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  16053. {
  16054. return ref.items();
  16055. }
  16056. /*!
  16057. @copydoc iterator_wrapper(reference)
  16058. */
  16059. JSON_HEDLEY_DEPRECATED(3.1.0)
  16060. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  16061. {
  16062. return ref.items();
  16063. }
  16064. /*!
  16065. @brief helper to access iterator member functions in range-based for
  16066. This function allows to access @ref iterator::key() and @ref
  16067. iterator::value() during range-based for loops. In these loops, a
  16068. reference to the JSON values is returned, so there is no access to the
  16069. underlying iterator.
  16070. For loop without `items()` function:
  16071. @code{cpp}
  16072. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  16073. {
  16074. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  16075. }
  16076. @endcode
  16077. Range-based for loop without `items()` function:
  16078. @code{cpp}
  16079. for (auto it : j_object)
  16080. {
  16081. // "it" is of type json::reference and has no key() member
  16082. std::cout << "value: " << it << '\n';
  16083. }
  16084. @endcode
  16085. Range-based for loop with `items()` function:
  16086. @code{cpp}
  16087. for (auto& el : j_object.items())
  16088. {
  16089. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  16090. }
  16091. @endcode
  16092. The `items()` function also allows to use
  16093. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  16094. (C++17):
  16095. @code{cpp}
  16096. for (auto& [key, val] : j_object.items())
  16097. {
  16098. std::cout << "key: " << key << ", value:" << val << '\n';
  16099. }
  16100. @endcode
  16101. @note When iterating over an array, `key()` will return the index of the
  16102. element as string (see example). For primitive types (e.g., numbers),
  16103. `key()` returns an empty string.
  16104. @return iteration proxy object wrapping @a ref with an interface to use in
  16105. range-based for loops
  16106. @liveexample{The following code shows how the function is used.,items}
  16107. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16108. changes in the JSON value.
  16109. @complexity Constant.
  16110. @since version 3.1.0, structured bindings support since 3.5.0.
  16111. */
  16112. iteration_proxy<iterator> items() noexcept
  16113. {
  16114. return iteration_proxy<iterator>(*this);
  16115. }
  16116. /*!
  16117. @copydoc items()
  16118. */
  16119. iteration_proxy<const_iterator> items() const noexcept
  16120. {
  16121. return iteration_proxy<const_iterator>(*this);
  16122. }
  16123. /// @}
  16124. //////////////
  16125. // capacity //
  16126. //////////////
  16127. /// @name capacity
  16128. /// @{
  16129. /*!
  16130. @brief checks whether the container is empty.
  16131. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  16132. @return The return value depends on the different types and is
  16133. defined as follows:
  16134. Value type | return value
  16135. ----------- | -------------
  16136. null | `true`
  16137. boolean | `false`
  16138. string | `false`
  16139. number | `false`
  16140. object | result of function `object_t::empty()`
  16141. array | result of function `array_t::empty()`
  16142. @liveexample{The following code uses `empty()` to check if a JSON
  16143. object contains any elements.,empty}
  16144. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16145. the Container concept; that is, their `empty()` functions have constant
  16146. complexity.
  16147. @iterators No changes.
  16148. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16149. @note This function does not return whether a string stored as JSON value
  16150. is empty - it returns whether the JSON container itself is empty which is
  16151. false in the case of a string.
  16152. @requirement This function helps `basic_json` satisfying the
  16153. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16154. requirements:
  16155. - The complexity is constant.
  16156. - Has the semantics of `begin() == end()`.
  16157. @sa @ref size() -- returns the number of elements
  16158. @since version 1.0.0
  16159. */
  16160. bool empty() const noexcept
  16161. {
  16162. switch (m_type)
  16163. {
  16164. case value_t::null:
  16165. {
  16166. // null values are empty
  16167. return true;
  16168. }
  16169. case value_t::array:
  16170. {
  16171. // delegate call to array_t::empty()
  16172. return m_value.array->empty();
  16173. }
  16174. case value_t::object:
  16175. {
  16176. // delegate call to object_t::empty()
  16177. return m_value.object->empty();
  16178. }
  16179. default:
  16180. {
  16181. // all other types are nonempty
  16182. return false;
  16183. }
  16184. }
  16185. }
  16186. /*!
  16187. @brief returns the number of elements
  16188. Returns the number of elements in a JSON value.
  16189. @return The return value depends on the different types and is
  16190. defined as follows:
  16191. Value type | return value
  16192. ----------- | -------------
  16193. null | `0`
  16194. boolean | `1`
  16195. string | `1`
  16196. number | `1`
  16197. object | result of function object_t::size()
  16198. array | result of function array_t::size()
  16199. @liveexample{The following code calls `size()` on the different value
  16200. types.,size}
  16201. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16202. the Container concept; that is, their size() functions have constant
  16203. complexity.
  16204. @iterators No changes.
  16205. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16206. @note This function does not return the length of a string stored as JSON
  16207. value - it returns the number of elements in the JSON value which is 1 in
  16208. the case of a string.
  16209. @requirement This function helps `basic_json` satisfying the
  16210. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16211. requirements:
  16212. - The complexity is constant.
  16213. - Has the semantics of `std::distance(begin(), end())`.
  16214. @sa @ref empty() -- checks whether the container is empty
  16215. @sa @ref max_size() -- returns the maximal number of elements
  16216. @since version 1.0.0
  16217. */
  16218. size_type size() const noexcept
  16219. {
  16220. switch (m_type)
  16221. {
  16222. case value_t::null:
  16223. {
  16224. // null values are empty
  16225. return 0;
  16226. }
  16227. case value_t::array:
  16228. {
  16229. // delegate call to array_t::size()
  16230. return m_value.array->size();
  16231. }
  16232. case value_t::object:
  16233. {
  16234. // delegate call to object_t::size()
  16235. return m_value.object->size();
  16236. }
  16237. default:
  16238. {
  16239. // all other types have size 1
  16240. return 1;
  16241. }
  16242. }
  16243. }
  16244. /*!
  16245. @brief returns the maximum possible number of elements
  16246. Returns the maximum number of elements a JSON value is able to hold due to
  16247. system or library implementation limitations, i.e. `std::distance(begin(),
  16248. end())` for the JSON value.
  16249. @return The return value depends on the different types and is
  16250. defined as follows:
  16251. Value type | return value
  16252. ----------- | -------------
  16253. null | `0` (same as `size()`)
  16254. boolean | `1` (same as `size()`)
  16255. string | `1` (same as `size()`)
  16256. number | `1` (same as `size()`)
  16257. object | result of function `object_t::max_size()`
  16258. array | result of function `array_t::max_size()`
  16259. @liveexample{The following code calls `max_size()` on the different value
  16260. types. Note the output is implementation specific.,max_size}
  16261. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16262. the Container concept; that is, their `max_size()` functions have constant
  16263. complexity.
  16264. @iterators No changes.
  16265. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16266. @requirement This function helps `basic_json` satisfying the
  16267. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16268. requirements:
  16269. - The complexity is constant.
  16270. - Has the semantics of returning `b.size()` where `b` is the largest
  16271. possible JSON value.
  16272. @sa @ref size() -- returns the number of elements
  16273. @since version 1.0.0
  16274. */
  16275. size_type max_size() const noexcept
  16276. {
  16277. switch (m_type)
  16278. {
  16279. case value_t::array:
  16280. {
  16281. // delegate call to array_t::max_size()
  16282. return m_value.array->max_size();
  16283. }
  16284. case value_t::object:
  16285. {
  16286. // delegate call to object_t::max_size()
  16287. return m_value.object->max_size();
  16288. }
  16289. default:
  16290. {
  16291. // all other types have max_size() == size()
  16292. return size();
  16293. }
  16294. }
  16295. }
  16296. /// @}
  16297. ///////////////
  16298. // modifiers //
  16299. ///////////////
  16300. /// @name modifiers
  16301. /// @{
  16302. /*!
  16303. @brief clears the contents
  16304. Clears the content of a JSON value and resets it to the default value as
  16305. if @ref basic_json(value_t) would have been called with the current value
  16306. type from @ref type():
  16307. Value type | initial value
  16308. ----------- | -------------
  16309. null | `null`
  16310. boolean | `false`
  16311. string | `""`
  16312. number | `0`
  16313. object | `{}`
  16314. array | `[]`
  16315. @post Has the same effect as calling
  16316. @code {.cpp}
  16317. *this = basic_json(type());
  16318. @endcode
  16319. @liveexample{The example below shows the effect of `clear()` to different
  16320. JSON types.,clear}
  16321. @complexity Linear in the size of the JSON value.
  16322. @iterators All iterators, pointers and references related to this container
  16323. are invalidated.
  16324. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16325. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  16326. same value than calling `clear()`
  16327. @since version 1.0.0
  16328. */
  16329. void clear() noexcept
  16330. {
  16331. switch (m_type)
  16332. {
  16333. case value_t::number_integer:
  16334. {
  16335. m_value.number_integer = 0;
  16336. break;
  16337. }
  16338. case value_t::number_unsigned:
  16339. {
  16340. m_value.number_unsigned = 0;
  16341. break;
  16342. }
  16343. case value_t::number_float:
  16344. {
  16345. m_value.number_float = 0.0;
  16346. break;
  16347. }
  16348. case value_t::boolean:
  16349. {
  16350. m_value.boolean = false;
  16351. break;
  16352. }
  16353. case value_t::string:
  16354. {
  16355. m_value.string->clear();
  16356. break;
  16357. }
  16358. case value_t::array:
  16359. {
  16360. m_value.array->clear();
  16361. break;
  16362. }
  16363. case value_t::object:
  16364. {
  16365. m_value.object->clear();
  16366. break;
  16367. }
  16368. default:
  16369. break;
  16370. }
  16371. }
  16372. /*!
  16373. @brief add an object to an array
  16374. Appends the given element @a val to the end of the JSON value. If the
  16375. function is called on a JSON null value, an empty array is created before
  16376. appending @a val.
  16377. @param[in] val the value to add to the JSON array
  16378. @throw type_error.308 when called on a type other than JSON array or
  16379. null; example: `"cannot use push_back() with number"`
  16380. @complexity Amortized constant.
  16381. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16382. add elements to a JSON array. Note how the `null` value was silently
  16383. converted to a JSON array.,push_back}
  16384. @since version 1.0.0
  16385. */
  16386. void push_back(basic_json&& val)
  16387. {
  16388. // push_back only works for null objects or arrays
  16389. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16390. {
  16391. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16392. }
  16393. // transform null object into an array
  16394. if (is_null())
  16395. {
  16396. m_type = value_t::array;
  16397. m_value = value_t::array;
  16398. assert_invariant();
  16399. }
  16400. // add element to array (move semantics)
  16401. m_value.array->push_back(std::move(val));
  16402. // invalidate object: mark it null so we do not call the destructor
  16403. // cppcheck-suppress accessMoved
  16404. val.m_type = value_t::null;
  16405. }
  16406. /*!
  16407. @brief add an object to an array
  16408. @copydoc push_back(basic_json&&)
  16409. */
  16410. reference operator+=(basic_json&& val)
  16411. {
  16412. push_back(std::move(val));
  16413. return *this;
  16414. }
  16415. /*!
  16416. @brief add an object to an array
  16417. @copydoc push_back(basic_json&&)
  16418. */
  16419. void push_back(const basic_json& val)
  16420. {
  16421. // push_back only works for null objects or arrays
  16422. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16423. {
  16424. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16425. }
  16426. // transform null object into an array
  16427. if (is_null())
  16428. {
  16429. m_type = value_t::array;
  16430. m_value = value_t::array;
  16431. assert_invariant();
  16432. }
  16433. // add element to array
  16434. m_value.array->push_back(val);
  16435. }
  16436. /*!
  16437. @brief add an object to an array
  16438. @copydoc push_back(basic_json&&)
  16439. */
  16440. reference operator+=(const basic_json& val)
  16441. {
  16442. push_back(val);
  16443. return *this;
  16444. }
  16445. /*!
  16446. @brief add an object to an object
  16447. Inserts the given element @a val to the JSON object. If the function is
  16448. called on a JSON null value, an empty object is created before inserting
  16449. @a val.
  16450. @param[in] val the value to add to the JSON object
  16451. @throw type_error.308 when called on a type other than JSON object or
  16452. null; example: `"cannot use push_back() with number"`
  16453. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16454. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16455. add elements to a JSON object. Note how the `null` value was silently
  16456. converted to a JSON object.,push_back__object_t__value}
  16457. @since version 1.0.0
  16458. */
  16459. void push_back(const typename object_t::value_type& val)
  16460. {
  16461. // push_back only works for null objects or objects
  16462. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16463. {
  16464. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16465. }
  16466. // transform null object into an object
  16467. if (is_null())
  16468. {
  16469. m_type = value_t::object;
  16470. m_value = value_t::object;
  16471. assert_invariant();
  16472. }
  16473. // add element to array
  16474. m_value.object->insert(val);
  16475. }
  16476. /*!
  16477. @brief add an object to an object
  16478. @copydoc push_back(const typename object_t::value_type&)
  16479. */
  16480. reference operator+=(const typename object_t::value_type& val)
  16481. {
  16482. push_back(val);
  16483. return *this;
  16484. }
  16485. /*!
  16486. @brief add an object to an object
  16487. This function allows to use `push_back` with an initializer list. In case
  16488. 1. the current value is an object,
  16489. 2. the initializer list @a init contains only two elements, and
  16490. 3. the first element of @a init is a string,
  16491. @a init is converted into an object element and added using
  16492. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  16493. is converted to a JSON value and added using @ref push_back(basic_json&&).
  16494. @param[in] init an initializer list
  16495. @complexity Linear in the size of the initializer list @a init.
  16496. @note This function is required to resolve an ambiguous overload error,
  16497. because pairs like `{"key", "value"}` can be both interpreted as
  16498. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  16499. https://github.com/nlohmann/json/issues/235 for more information.
  16500. @liveexample{The example shows how initializer lists are treated as
  16501. objects when possible.,push_back__initializer_list}
  16502. */
  16503. void push_back(initializer_list_t init)
  16504. {
  16505. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  16506. {
  16507. basic_json&& key = init.begin()->moved_or_copied();
  16508. push_back(typename object_t::value_type(
  16509. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  16510. }
  16511. else
  16512. {
  16513. push_back(basic_json(init));
  16514. }
  16515. }
  16516. /*!
  16517. @brief add an object to an object
  16518. @copydoc push_back(initializer_list_t)
  16519. */
  16520. reference operator+=(initializer_list_t init)
  16521. {
  16522. push_back(init);
  16523. return *this;
  16524. }
  16525. /*!
  16526. @brief add an object to an array
  16527. Creates a JSON value from the passed parameters @a args to the end of the
  16528. JSON value. If the function is called on a JSON null value, an empty array
  16529. is created before appending the value created from @a args.
  16530. @param[in] args arguments to forward to a constructor of @ref basic_json
  16531. @tparam Args compatible types to create a @ref basic_json object
  16532. @return reference to the inserted element
  16533. @throw type_error.311 when called on a type other than JSON array or
  16534. null; example: `"cannot use emplace_back() with number"`
  16535. @complexity Amortized constant.
  16536. @liveexample{The example shows how `push_back()` can be used to add
  16537. elements to a JSON array. Note how the `null` value was silently converted
  16538. to a JSON array.,emplace_back}
  16539. @since version 2.0.8, returns reference since 3.7.0
  16540. */
  16541. template<class... Args>
  16542. reference emplace_back(Args&& ... args)
  16543. {
  16544. // emplace_back only works for null objects or arrays
  16545. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16546. {
  16547. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  16548. }
  16549. // transform null object into an array
  16550. if (is_null())
  16551. {
  16552. m_type = value_t::array;
  16553. m_value = value_t::array;
  16554. assert_invariant();
  16555. }
  16556. // add element to array (perfect forwarding)
  16557. #ifdef JSON_HAS_CPP_17
  16558. return m_value.array->emplace_back(std::forward<Args>(args)...);
  16559. #else
  16560. m_value.array->emplace_back(std::forward<Args>(args)...);
  16561. return m_value.array->back();
  16562. #endif
  16563. }
  16564. /*!
  16565. @brief add an object to an object if key does not exist
  16566. Inserts a new element into a JSON object constructed in-place with the
  16567. given @a args if there is no element with the key in the container. If the
  16568. function is called on a JSON null value, an empty object is created before
  16569. appending the value created from @a args.
  16570. @param[in] args arguments to forward to a constructor of @ref basic_json
  16571. @tparam Args compatible types to create a @ref basic_json object
  16572. @return a pair consisting of an iterator to the inserted element, or the
  16573. already-existing element if no insertion happened, and a bool
  16574. denoting whether the insertion took place.
  16575. @throw type_error.311 when called on a type other than JSON object or
  16576. null; example: `"cannot use emplace() with number"`
  16577. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16578. @liveexample{The example shows how `emplace()` can be used to add elements
  16579. to a JSON object. Note how the `null` value was silently converted to a
  16580. JSON object. Further note how no value is added if there was already one
  16581. value stored with the same key.,emplace}
  16582. @since version 2.0.8
  16583. */
  16584. template<class... Args>
  16585. std::pair<iterator, bool> emplace(Args&& ... args)
  16586. {
  16587. // emplace only works for null objects or arrays
  16588. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16589. {
  16590. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  16591. }
  16592. // transform null object into an object
  16593. if (is_null())
  16594. {
  16595. m_type = value_t::object;
  16596. m_value = value_t::object;
  16597. assert_invariant();
  16598. }
  16599. // add element to array (perfect forwarding)
  16600. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  16601. // create result iterator and set iterator to the result of emplace
  16602. auto it = begin();
  16603. it.m_it.object_iterator = res.first;
  16604. // return pair of iterator and boolean
  16605. return {it, res.second};
  16606. }
  16607. /// Helper for insertion of an iterator
  16608. /// @note: This uses std::distance to support GCC 4.8,
  16609. /// see https://github.com/nlohmann/json/pull/1257
  16610. template<typename... Args>
  16611. iterator insert_iterator(const_iterator pos, Args&& ... args)
  16612. {
  16613. iterator result(this);
  16614. assert(m_value.array != nullptr);
  16615. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  16616. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  16617. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  16618. // This could have been written as:
  16619. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  16620. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  16621. return result;
  16622. }
  16623. /*!
  16624. @brief inserts element
  16625. Inserts element @a val before iterator @a pos.
  16626. @param[in] pos iterator before which the content will be inserted; may be
  16627. the end() iterator
  16628. @param[in] val element to insert
  16629. @return iterator pointing to the inserted @a val.
  16630. @throw type_error.309 if called on JSON values other than arrays;
  16631. example: `"cannot use insert() with string"`
  16632. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16633. example: `"iterator does not fit current value"`
  16634. @complexity Constant plus linear in the distance between @a pos and end of
  16635. the container.
  16636. @liveexample{The example shows how `insert()` is used.,insert}
  16637. @since version 1.0.0
  16638. */
  16639. iterator insert(const_iterator pos, const basic_json& val)
  16640. {
  16641. // insert only works for arrays
  16642. if (JSON_HEDLEY_LIKELY(is_array()))
  16643. {
  16644. // check if iterator pos fits to this JSON value
  16645. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16646. {
  16647. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16648. }
  16649. // insert to array and return iterator
  16650. return insert_iterator(pos, val);
  16651. }
  16652. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16653. }
  16654. /*!
  16655. @brief inserts element
  16656. @copydoc insert(const_iterator, const basic_json&)
  16657. */
  16658. iterator insert(const_iterator pos, basic_json&& val)
  16659. {
  16660. return insert(pos, val);
  16661. }
  16662. /*!
  16663. @brief inserts elements
  16664. Inserts @a cnt copies of @a val before iterator @a pos.
  16665. @param[in] pos iterator before which the content will be inserted; may be
  16666. the end() iterator
  16667. @param[in] cnt number of copies of @a val to insert
  16668. @param[in] val element to insert
  16669. @return iterator pointing to the first element inserted, or @a pos if
  16670. `cnt==0`
  16671. @throw type_error.309 if called on JSON values other than arrays; example:
  16672. `"cannot use insert() with string"`
  16673. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16674. example: `"iterator does not fit current value"`
  16675. @complexity Linear in @a cnt plus linear in the distance between @a pos
  16676. and end of the container.
  16677. @liveexample{The example shows how `insert()` is used.,insert__count}
  16678. @since version 1.0.0
  16679. */
  16680. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  16681. {
  16682. // insert only works for arrays
  16683. if (JSON_HEDLEY_LIKELY(is_array()))
  16684. {
  16685. // check if iterator pos fits to this JSON value
  16686. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16687. {
  16688. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16689. }
  16690. // insert to array and return iterator
  16691. return insert_iterator(pos, cnt, val);
  16692. }
  16693. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16694. }
  16695. /*!
  16696. @brief inserts elements
  16697. Inserts elements from range `[first, last)` before iterator @a pos.
  16698. @param[in] pos iterator before which the content will be inserted; may be
  16699. the end() iterator
  16700. @param[in] first begin of the range of elements to insert
  16701. @param[in] last end of the range of elements to insert
  16702. @throw type_error.309 if called on JSON values other than arrays; example:
  16703. `"cannot use insert() with string"`
  16704. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16705. example: `"iterator does not fit current value"`
  16706. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16707. same JSON value; example: `"iterators do not fit"`
  16708. @throw invalid_iterator.211 if @a first or @a last are iterators into
  16709. container for which insert is called; example: `"passed iterators may not
  16710. belong to container"`
  16711. @return iterator pointing to the first element inserted, or @a pos if
  16712. `first==last`
  16713. @complexity Linear in `std::distance(first, last)` plus linear in the
  16714. distance between @a pos and end of the container.
  16715. @liveexample{The example shows how `insert()` is used.,insert__range}
  16716. @since version 1.0.0
  16717. */
  16718. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  16719. {
  16720. // insert only works for arrays
  16721. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16722. {
  16723. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16724. }
  16725. // check if iterator pos fits to this JSON value
  16726. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16727. {
  16728. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16729. }
  16730. // check if range iterators belong to the same JSON object
  16731. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16732. {
  16733. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16734. }
  16735. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  16736. {
  16737. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  16738. }
  16739. // insert to array and return iterator
  16740. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  16741. }
  16742. /*!
  16743. @brief inserts elements
  16744. Inserts elements from initializer list @a ilist before iterator @a pos.
  16745. @param[in] pos iterator before which the content will be inserted; may be
  16746. the end() iterator
  16747. @param[in] ilist initializer list to insert the values from
  16748. @throw type_error.309 if called on JSON values other than arrays; example:
  16749. `"cannot use insert() with string"`
  16750. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16751. example: `"iterator does not fit current value"`
  16752. @return iterator pointing to the first element inserted, or @a pos if
  16753. `ilist` is empty
  16754. @complexity Linear in `ilist.size()` plus linear in the distance between
  16755. @a pos and end of the container.
  16756. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  16757. @since version 1.0.0
  16758. */
  16759. iterator insert(const_iterator pos, initializer_list_t ilist)
  16760. {
  16761. // insert only works for arrays
  16762. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16763. {
  16764. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16765. }
  16766. // check if iterator pos fits to this JSON value
  16767. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16768. {
  16769. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16770. }
  16771. // insert to array and return iterator
  16772. return insert_iterator(pos, ilist.begin(), ilist.end());
  16773. }
  16774. /*!
  16775. @brief inserts elements
  16776. Inserts elements from range `[first, last)`.
  16777. @param[in] first begin of the range of elements to insert
  16778. @param[in] last end of the range of elements to insert
  16779. @throw type_error.309 if called on JSON values other than objects; example:
  16780. `"cannot use insert() with string"`
  16781. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16782. point to an object; example: `"iterators first and last must point to
  16783. objects"`
  16784. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16785. same JSON value; example: `"iterators do not fit"`
  16786. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  16787. of elements to insert.
  16788. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  16789. @since version 3.0.0
  16790. */
  16791. void insert(const_iterator first, const_iterator last)
  16792. {
  16793. // insert only works for objects
  16794. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16795. {
  16796. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16797. }
  16798. // check if range iterators belong to the same JSON object
  16799. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16800. {
  16801. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16802. }
  16803. // passed iterators must belong to objects
  16804. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  16805. {
  16806. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16807. }
  16808. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  16809. }
  16810. /*!
  16811. @brief updates a JSON object from another object, overwriting existing keys
  16812. Inserts all values from JSON object @a j and overwrites existing keys.
  16813. @param[in] j JSON object to read values from
  16814. @throw type_error.312 if called on JSON values other than objects; example:
  16815. `"cannot use update() with string"`
  16816. @complexity O(N*log(size() + N)), where N is the number of elements to
  16817. insert.
  16818. @liveexample{The example shows how `update()` is used.,update}
  16819. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16820. @since version 3.0.0
  16821. */
  16822. void update(const_reference j)
  16823. {
  16824. // implicitly convert null value to an empty object
  16825. if (is_null())
  16826. {
  16827. m_type = value_t::object;
  16828. m_value.object = create<object_t>();
  16829. assert_invariant();
  16830. }
  16831. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16832. {
  16833. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16834. }
  16835. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  16836. {
  16837. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  16838. }
  16839. for (auto it = j.cbegin(); it != j.cend(); ++it)
  16840. {
  16841. m_value.object->operator[](it.key()) = it.value();
  16842. }
  16843. }
  16844. /*!
  16845. @brief updates a JSON object from another object, overwriting existing keys
  16846. Inserts all values from from range `[first, last)` and overwrites existing
  16847. keys.
  16848. @param[in] first begin of the range of elements to insert
  16849. @param[in] last end of the range of elements to insert
  16850. @throw type_error.312 if called on JSON values other than objects; example:
  16851. `"cannot use update() with string"`
  16852. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16853. point to an object; example: `"iterators first and last must point to
  16854. objects"`
  16855. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16856. same JSON value; example: `"iterators do not fit"`
  16857. @complexity O(N*log(size() + N)), where N is the number of elements to
  16858. insert.
  16859. @liveexample{The example shows how `update()` is used__range.,update}
  16860. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16861. @since version 3.0.0
  16862. */
  16863. void update(const_iterator first, const_iterator last)
  16864. {
  16865. // implicitly convert null value to an empty object
  16866. if (is_null())
  16867. {
  16868. m_type = value_t::object;
  16869. m_value.object = create<object_t>();
  16870. assert_invariant();
  16871. }
  16872. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16873. {
  16874. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16875. }
  16876. // check if range iterators belong to the same JSON object
  16877. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16878. {
  16879. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16880. }
  16881. // passed iterators must belong to objects
  16882. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  16883. or not last.m_object->is_object()))
  16884. {
  16885. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16886. }
  16887. for (auto it = first; it != last; ++it)
  16888. {
  16889. m_value.object->operator[](it.key()) = it.value();
  16890. }
  16891. }
  16892. /*!
  16893. @brief exchanges the values
  16894. Exchanges the contents of the JSON value with those of @a other. Does not
  16895. invoke any move, copy, or swap operations on individual elements. All
  16896. iterators and references remain valid. The past-the-end iterator is
  16897. invalidated.
  16898. @param[in,out] other JSON value to exchange the contents with
  16899. @complexity Constant.
  16900. @liveexample{The example below shows how JSON values can be swapped with
  16901. `swap()`.,swap__reference}
  16902. @since version 1.0.0
  16903. */
  16904. void swap(reference other) noexcept (
  16905. std::is_nothrow_move_constructible<value_t>::value and
  16906. std::is_nothrow_move_assignable<value_t>::value and
  16907. std::is_nothrow_move_constructible<json_value>::value and
  16908. std::is_nothrow_move_assignable<json_value>::value
  16909. )
  16910. {
  16911. std::swap(m_type, other.m_type);
  16912. std::swap(m_value, other.m_value);
  16913. assert_invariant();
  16914. }
  16915. /*!
  16916. @brief exchanges the values
  16917. Exchanges the contents of a JSON array with those of @a other. Does not
  16918. invoke any move, copy, or swap operations on individual elements. All
  16919. iterators and references remain valid. The past-the-end iterator is
  16920. invalidated.
  16921. @param[in,out] other array to exchange the contents with
  16922. @throw type_error.310 when JSON value is not an array; example: `"cannot
  16923. use swap() with string"`
  16924. @complexity Constant.
  16925. @liveexample{The example below shows how arrays can be swapped with
  16926. `swap()`.,swap__array_t}
  16927. @since version 1.0.0
  16928. */
  16929. void swap(array_t& other)
  16930. {
  16931. // swap only works for arrays
  16932. if (JSON_HEDLEY_LIKELY(is_array()))
  16933. {
  16934. std::swap(*(m_value.array), other);
  16935. }
  16936. else
  16937. {
  16938. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16939. }
  16940. }
  16941. /*!
  16942. @brief exchanges the values
  16943. Exchanges the contents of a JSON object with those of @a other. Does not
  16944. invoke any move, copy, or swap operations on individual elements. All
  16945. iterators and references remain valid. The past-the-end iterator is
  16946. invalidated.
  16947. @param[in,out] other object to exchange the contents with
  16948. @throw type_error.310 when JSON value is not an object; example:
  16949. `"cannot use swap() with string"`
  16950. @complexity Constant.
  16951. @liveexample{The example below shows how objects can be swapped with
  16952. `swap()`.,swap__object_t}
  16953. @since version 1.0.0
  16954. */
  16955. void swap(object_t& other)
  16956. {
  16957. // swap only works for objects
  16958. if (JSON_HEDLEY_LIKELY(is_object()))
  16959. {
  16960. std::swap(*(m_value.object), other);
  16961. }
  16962. else
  16963. {
  16964. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16965. }
  16966. }
  16967. /*!
  16968. @brief exchanges the values
  16969. Exchanges the contents of a JSON string with those of @a other. Does not
  16970. invoke any move, copy, or swap operations on individual elements. All
  16971. iterators and references remain valid. The past-the-end iterator is
  16972. invalidated.
  16973. @param[in,out] other string to exchange the contents with
  16974. @throw type_error.310 when JSON value is not a string; example: `"cannot
  16975. use swap() with boolean"`
  16976. @complexity Constant.
  16977. @liveexample{The example below shows how strings can be swapped with
  16978. `swap()`.,swap__string_t}
  16979. @since version 1.0.0
  16980. */
  16981. void swap(string_t& other)
  16982. {
  16983. // swap only works for strings
  16984. if (JSON_HEDLEY_LIKELY(is_string()))
  16985. {
  16986. std::swap(*(m_value.string), other);
  16987. }
  16988. else
  16989. {
  16990. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16991. }
  16992. }
  16993. /// @}
  16994. public:
  16995. //////////////////////////////////////////
  16996. // lexicographical comparison operators //
  16997. //////////////////////////////////////////
  16998. /// @name lexicographical comparison operators
  16999. /// @{
  17000. /*!
  17001. @brief comparison: equal
  17002. Compares two JSON values for equality according to the following rules:
  17003. - Two JSON values are equal if (1) they are from the same type and (2)
  17004. their stored values are the same according to their respective
  17005. `operator==`.
  17006. - Integer and floating-point numbers are automatically converted before
  17007. comparison. Note than two NaN values are always treated as unequal.
  17008. - Two JSON null values are equal.
  17009. @note Floating-point inside JSON values numbers are compared with
  17010. `json::number_float_t::operator==` which is `double::operator==` by
  17011. default. To compare floating-point while respecting an epsilon, an alternative
  17012. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  17013. could be used, for instance
  17014. @code {.cpp}
  17015. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  17016. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  17017. {
  17018. return std::abs(a - b) <= epsilon;
  17019. }
  17020. @endcode
  17021. @note NaN values never compare equal to themselves or to other NaN values.
  17022. @param[in] lhs first JSON value to consider
  17023. @param[in] rhs second JSON value to consider
  17024. @return whether the values @a lhs and @a rhs are equal
  17025. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17026. @complexity Linear.
  17027. @liveexample{The example demonstrates comparing several JSON
  17028. types.,operator__equal}
  17029. @since version 1.0.0
  17030. */
  17031. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  17032. {
  17033. const auto lhs_type = lhs.type();
  17034. const auto rhs_type = rhs.type();
  17035. if (lhs_type == rhs_type)
  17036. {
  17037. switch (lhs_type)
  17038. {
  17039. case value_t::array:
  17040. return *lhs.m_value.array == *rhs.m_value.array;
  17041. case value_t::object:
  17042. return *lhs.m_value.object == *rhs.m_value.object;
  17043. case value_t::null:
  17044. return true;
  17045. case value_t::string:
  17046. return *lhs.m_value.string == *rhs.m_value.string;
  17047. case value_t::boolean:
  17048. return lhs.m_value.boolean == rhs.m_value.boolean;
  17049. case value_t::number_integer:
  17050. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  17051. case value_t::number_unsigned:
  17052. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  17053. case value_t::number_float:
  17054. return lhs.m_value.number_float == rhs.m_value.number_float;
  17055. default:
  17056. return false;
  17057. }
  17058. }
  17059. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  17060. {
  17061. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  17062. }
  17063. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  17064. {
  17065. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  17066. }
  17067. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  17068. {
  17069. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  17070. }
  17071. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  17072. {
  17073. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17074. }
  17075. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  17076. {
  17077. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  17078. }
  17079. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  17080. {
  17081. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17082. }
  17083. return false;
  17084. }
  17085. /*!
  17086. @brief comparison: equal
  17087. @copydoc operator==(const_reference, const_reference)
  17088. */
  17089. template<typename ScalarType, typename std::enable_if<
  17090. std::is_scalar<ScalarType>::value, int>::type = 0>
  17091. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  17092. {
  17093. return lhs == basic_json(rhs);
  17094. }
  17095. /*!
  17096. @brief comparison: equal
  17097. @copydoc operator==(const_reference, const_reference)
  17098. */
  17099. template<typename ScalarType, typename std::enable_if<
  17100. std::is_scalar<ScalarType>::value, int>::type = 0>
  17101. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  17102. {
  17103. return basic_json(lhs) == rhs;
  17104. }
  17105. /*!
  17106. @brief comparison: not equal
  17107. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  17108. @param[in] lhs first JSON value to consider
  17109. @param[in] rhs second JSON value to consider
  17110. @return whether the values @a lhs and @a rhs are not equal
  17111. @complexity Linear.
  17112. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17113. @liveexample{The example demonstrates comparing several JSON
  17114. types.,operator__notequal}
  17115. @since version 1.0.0
  17116. */
  17117. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  17118. {
  17119. return not (lhs == rhs);
  17120. }
  17121. /*!
  17122. @brief comparison: not equal
  17123. @copydoc operator!=(const_reference, const_reference)
  17124. */
  17125. template<typename ScalarType, typename std::enable_if<
  17126. std::is_scalar<ScalarType>::value, int>::type = 0>
  17127. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  17128. {
  17129. return lhs != basic_json(rhs);
  17130. }
  17131. /*!
  17132. @brief comparison: not equal
  17133. @copydoc operator!=(const_reference, const_reference)
  17134. */
  17135. template<typename ScalarType, typename std::enable_if<
  17136. std::is_scalar<ScalarType>::value, int>::type = 0>
  17137. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  17138. {
  17139. return basic_json(lhs) != rhs;
  17140. }
  17141. /*!
  17142. @brief comparison: less than
  17143. Compares whether one JSON value @a lhs is less than another JSON value @a
  17144. rhs according to the following rules:
  17145. - If @a lhs and @a rhs have the same type, the values are compared using
  17146. the default `<` operator.
  17147. - Integer and floating-point numbers are automatically converted before
  17148. comparison
  17149. - In case @a lhs and @a rhs have different types, the values are ignored
  17150. and the order of the types is considered, see
  17151. @ref operator<(const value_t, const value_t).
  17152. @param[in] lhs first JSON value to consider
  17153. @param[in] rhs second JSON value to consider
  17154. @return whether @a lhs is less than @a rhs
  17155. @complexity Linear.
  17156. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17157. @liveexample{The example demonstrates comparing several JSON
  17158. types.,operator__less}
  17159. @since version 1.0.0
  17160. */
  17161. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  17162. {
  17163. const auto lhs_type = lhs.type();
  17164. const auto rhs_type = rhs.type();
  17165. if (lhs_type == rhs_type)
  17166. {
  17167. switch (lhs_type)
  17168. {
  17169. case value_t::array:
  17170. // note parentheses are necessary, see
  17171. // https://github.com/nlohmann/json/issues/1530
  17172. return (*lhs.m_value.array) < (*rhs.m_value.array);
  17173. case value_t::object:
  17174. return (*lhs.m_value.object) < (*rhs.m_value.object);
  17175. case value_t::null:
  17176. return false;
  17177. case value_t::string:
  17178. return (*lhs.m_value.string) < (*rhs.m_value.string);
  17179. case value_t::boolean:
  17180. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  17181. case value_t::number_integer:
  17182. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  17183. case value_t::number_unsigned:
  17184. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  17185. case value_t::number_float:
  17186. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  17187. default:
  17188. return false;
  17189. }
  17190. }
  17191. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  17192. {
  17193. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  17194. }
  17195. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  17196. {
  17197. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  17198. }
  17199. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  17200. {
  17201. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  17202. }
  17203. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  17204. {
  17205. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17206. }
  17207. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  17208. {
  17209. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17210. }
  17211. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  17212. {
  17213. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  17214. }
  17215. // We only reach this line if we cannot compare values. In that case,
  17216. // we compare types. Note we have to call the operator explicitly,
  17217. // because MSVC has problems otherwise.
  17218. return operator<(lhs_type, rhs_type);
  17219. }
  17220. /*!
  17221. @brief comparison: less than
  17222. @copydoc operator<(const_reference, const_reference)
  17223. */
  17224. template<typename ScalarType, typename std::enable_if<
  17225. std::is_scalar<ScalarType>::value, int>::type = 0>
  17226. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  17227. {
  17228. return lhs < basic_json(rhs);
  17229. }
  17230. /*!
  17231. @brief comparison: less than
  17232. @copydoc operator<(const_reference, const_reference)
  17233. */
  17234. template<typename ScalarType, typename std::enable_if<
  17235. std::is_scalar<ScalarType>::value, int>::type = 0>
  17236. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  17237. {
  17238. return basic_json(lhs) < rhs;
  17239. }
  17240. /*!
  17241. @brief comparison: less than or equal
  17242. Compares whether one JSON value @a lhs is less than or equal to another
  17243. JSON value by calculating `not (rhs < lhs)`.
  17244. @param[in] lhs first JSON value to consider
  17245. @param[in] rhs second JSON value to consider
  17246. @return whether @a lhs is less than or equal to @a rhs
  17247. @complexity Linear.
  17248. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17249. @liveexample{The example demonstrates comparing several JSON
  17250. types.,operator__greater}
  17251. @since version 1.0.0
  17252. */
  17253. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  17254. {
  17255. return not (rhs < lhs);
  17256. }
  17257. /*!
  17258. @brief comparison: less than or equal
  17259. @copydoc operator<=(const_reference, const_reference)
  17260. */
  17261. template<typename ScalarType, typename std::enable_if<
  17262. std::is_scalar<ScalarType>::value, int>::type = 0>
  17263. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  17264. {
  17265. return lhs <= basic_json(rhs);
  17266. }
  17267. /*!
  17268. @brief comparison: less than or equal
  17269. @copydoc operator<=(const_reference, const_reference)
  17270. */
  17271. template<typename ScalarType, typename std::enable_if<
  17272. std::is_scalar<ScalarType>::value, int>::type = 0>
  17273. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  17274. {
  17275. return basic_json(lhs) <= rhs;
  17276. }
  17277. /*!
  17278. @brief comparison: greater than
  17279. Compares whether one JSON value @a lhs is greater than another
  17280. JSON value by calculating `not (lhs <= rhs)`.
  17281. @param[in] lhs first JSON value to consider
  17282. @param[in] rhs second JSON value to consider
  17283. @return whether @a lhs is greater than to @a rhs
  17284. @complexity Linear.
  17285. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17286. @liveexample{The example demonstrates comparing several JSON
  17287. types.,operator__lessequal}
  17288. @since version 1.0.0
  17289. */
  17290. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  17291. {
  17292. return not (lhs <= rhs);
  17293. }
  17294. /*!
  17295. @brief comparison: greater than
  17296. @copydoc operator>(const_reference, const_reference)
  17297. */
  17298. template<typename ScalarType, typename std::enable_if<
  17299. std::is_scalar<ScalarType>::value, int>::type = 0>
  17300. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  17301. {
  17302. return lhs > basic_json(rhs);
  17303. }
  17304. /*!
  17305. @brief comparison: greater than
  17306. @copydoc operator>(const_reference, const_reference)
  17307. */
  17308. template<typename ScalarType, typename std::enable_if<
  17309. std::is_scalar<ScalarType>::value, int>::type = 0>
  17310. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  17311. {
  17312. return basic_json(lhs) > rhs;
  17313. }
  17314. /*!
  17315. @brief comparison: greater than or equal
  17316. Compares whether one JSON value @a lhs is greater than or equal to another
  17317. JSON value by calculating `not (lhs < rhs)`.
  17318. @param[in] lhs first JSON value to consider
  17319. @param[in] rhs second JSON value to consider
  17320. @return whether @a lhs is greater than or equal to @a rhs
  17321. @complexity Linear.
  17322. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17323. @liveexample{The example demonstrates comparing several JSON
  17324. types.,operator__greaterequal}
  17325. @since version 1.0.0
  17326. */
  17327. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  17328. {
  17329. return not (lhs < rhs);
  17330. }
  17331. /*!
  17332. @brief comparison: greater than or equal
  17333. @copydoc operator>=(const_reference, const_reference)
  17334. */
  17335. template<typename ScalarType, typename std::enable_if<
  17336. std::is_scalar<ScalarType>::value, int>::type = 0>
  17337. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  17338. {
  17339. return lhs >= basic_json(rhs);
  17340. }
  17341. /*!
  17342. @brief comparison: greater than or equal
  17343. @copydoc operator>=(const_reference, const_reference)
  17344. */
  17345. template<typename ScalarType, typename std::enable_if<
  17346. std::is_scalar<ScalarType>::value, int>::type = 0>
  17347. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  17348. {
  17349. return basic_json(lhs) >= rhs;
  17350. }
  17351. /// @}
  17352. ///////////////////
  17353. // serialization //
  17354. ///////////////////
  17355. /// @name serialization
  17356. /// @{
  17357. /*!
  17358. @brief serialize to stream
  17359. Serialize the given JSON value @a j to the output stream @a o. The JSON
  17360. value will be serialized using the @ref dump member function.
  17361. - The indentation of the output can be controlled with the member variable
  17362. `width` of the output stream @a o. For instance, using the manipulator
  17363. `std::setw(4)` on @a o sets the indentation level to `4` and the
  17364. serialization result is the same as calling `dump(4)`.
  17365. - The indentation character can be controlled with the member variable
  17366. `fill` of the output stream @a o. For instance, the manipulator
  17367. `std::setfill('\\t')` sets indentation to use a tab character rather than
  17368. the default space character.
  17369. @param[in,out] o stream to serialize to
  17370. @param[in] j JSON value to serialize
  17371. @return the stream @a o
  17372. @throw type_error.316 if a string stored inside the JSON value is not
  17373. UTF-8 encoded
  17374. @complexity Linear.
  17375. @liveexample{The example below shows the serialization with different
  17376. parameters to `width` to adjust the indentation level.,operator_serialize}
  17377. @since version 1.0.0; indentation character added in version 3.0.0
  17378. */
  17379. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  17380. {
  17381. // read width member and use it as indentation parameter if nonzero
  17382. const bool pretty_print = o.width() > 0;
  17383. const auto indentation = pretty_print ? o.width() : 0;
  17384. // reset width to 0 for subsequent calls to this stream
  17385. o.width(0);
  17386. // do the actual serialization
  17387. serializer s(detail::output_adapter<char>(o), o.fill());
  17388. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  17389. return o;
  17390. }
  17391. /*!
  17392. @brief serialize to stream
  17393. @deprecated This stream operator is deprecated and will be removed in
  17394. future 4.0.0 of the library. Please use
  17395. @ref operator<<(std::ostream&, const basic_json&)
  17396. instead; that is, replace calls like `j >> o;` with `o << j;`.
  17397. @since version 1.0.0; deprecated since version 3.0.0
  17398. */
  17399. JSON_HEDLEY_DEPRECATED(3.0.0)
  17400. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  17401. {
  17402. return o << j;
  17403. }
  17404. /// @}
  17405. /////////////////////
  17406. // deserialization //
  17407. /////////////////////
  17408. /// @name deserialization
  17409. /// @{
  17410. /*!
  17411. @brief deserialize from a compatible input
  17412. This function reads from a compatible input. Examples are:
  17413. - an array of 1-byte values
  17414. - strings with character/literal type with size of 1 byte
  17415. - input streams
  17416. - container with contiguous storage of 1-byte values. Compatible container
  17417. types include `std::vector`, `std::string`, `std::array`,
  17418. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17419. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17420. containers can be used as long as they implement random-access iterators
  17421. and a contiguous storage.
  17422. @pre Each element of the container has a size of 1 byte. Violating this
  17423. precondition yields undefined behavior. **This precondition is enforced
  17424. with a static assertion.**
  17425. @pre The container storage is contiguous. Violating this precondition
  17426. yields undefined behavior. **This precondition is enforced with an
  17427. assertion.**
  17428. @warning There is no way to enforce all preconditions at compile-time. If
  17429. the function is called with a noncompliant container and with
  17430. assertions switched off, the behavior is undefined and will most
  17431. likely yield segmentation violation.
  17432. @param[in] i input to read from
  17433. @param[in] cb a parser callback function of type @ref parser_callback_t
  17434. which is used to control the deserialization by filtering unwanted values
  17435. (optional)
  17436. @param[in] allow_exceptions whether to throw exceptions in case of a
  17437. parse error (optional, true by default)
  17438. @return deserialized JSON value; in case of a parse error and
  17439. @a allow_exceptions set to `false`, the return value will be
  17440. value_t::discarded.
  17441. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17442. of input; expected string literal""`
  17443. @throw parse_error.102 if to_unicode fails or surrogate error
  17444. @throw parse_error.103 if to_unicode fails
  17445. @complexity Linear in the length of the input. The parser is a predictive
  17446. LL(1) parser. The complexity can be higher if the parser callback function
  17447. @a cb has a super-linear complexity.
  17448. @note A UTF-8 byte order mark is silently ignored.
  17449. @liveexample{The example below demonstrates the `parse()` function reading
  17450. from an array.,parse__array__parser_callback_t}
  17451. @liveexample{The example below demonstrates the `parse()` function with
  17452. and without callback function.,parse__string__parser_callback_t}
  17453. @liveexample{The example below demonstrates the `parse()` function with
  17454. and without callback function.,parse__istream__parser_callback_t}
  17455. @liveexample{The example below demonstrates the `parse()` function reading
  17456. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  17457. @since version 2.0.3 (contiguous containers)
  17458. */
  17459. JSON_HEDLEY_WARN_UNUSED_RESULT
  17460. static basic_json parse(detail::input_adapter&& i,
  17461. const parser_callback_t cb = nullptr,
  17462. const bool allow_exceptions = true)
  17463. {
  17464. basic_json result;
  17465. parser(i, cb, allow_exceptions).parse(true, result);
  17466. return result;
  17467. }
  17468. static bool accept(detail::input_adapter&& i)
  17469. {
  17470. return parser(i).accept(true);
  17471. }
  17472. /*!
  17473. @brief generate SAX events
  17474. The SAX event lister must follow the interface of @ref json_sax.
  17475. This function reads from a compatible input. Examples are:
  17476. - an array of 1-byte values
  17477. - strings with character/literal type with size of 1 byte
  17478. - input streams
  17479. - container with contiguous storage of 1-byte values. Compatible container
  17480. types include `std::vector`, `std::string`, `std::array`,
  17481. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17482. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17483. containers can be used as long as they implement random-access iterators
  17484. and a contiguous storage.
  17485. @pre Each element of the container has a size of 1 byte. Violating this
  17486. precondition yields undefined behavior. **This precondition is enforced
  17487. with a static assertion.**
  17488. @pre The container storage is contiguous. Violating this precondition
  17489. yields undefined behavior. **This precondition is enforced with an
  17490. assertion.**
  17491. @warning There is no way to enforce all preconditions at compile-time. If
  17492. the function is called with a noncompliant container and with
  17493. assertions switched off, the behavior is undefined and will most
  17494. likely yield segmentation violation.
  17495. @param[in] i input to read from
  17496. @param[in,out] sax SAX event listener
  17497. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  17498. @param[in] strict whether the input has to be consumed completely
  17499. @return return value of the last processed SAX event
  17500. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17501. of input; expected string literal""`
  17502. @throw parse_error.102 if to_unicode fails or surrogate error
  17503. @throw parse_error.103 if to_unicode fails
  17504. @complexity Linear in the length of the input. The parser is a predictive
  17505. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  17506. a super-linear complexity.
  17507. @note A UTF-8 byte order mark is silently ignored.
  17508. @liveexample{The example below demonstrates the `sax_parse()` function
  17509. reading from string and processing the events with a user-defined SAX
  17510. event consumer.,sax_parse}
  17511. @since version 3.2.0
  17512. */
  17513. template <typename SAX>
  17514. JSON_HEDLEY_NON_NULL(2)
  17515. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  17516. input_format_t format = input_format_t::json,
  17517. const bool strict = true)
  17518. {
  17519. assert(sax);
  17520. return format == input_format_t::json
  17521. ? parser(std::move(i)).sax_parse(sax, strict)
  17522. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  17523. }
  17524. /*!
  17525. @brief deserialize from an iterator range with contiguous storage
  17526. This function reads from an iterator range of a container with contiguous
  17527. storage of 1-byte values. Compatible container types include
  17528. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  17529. `std::initializer_list`. Furthermore, C-style arrays can be used with
  17530. `std::begin()`/`std::end()`. User-defined containers can be used as long
  17531. as they implement random-access iterators and a contiguous storage.
  17532. @pre The iterator range is contiguous. Violating this precondition yields
  17533. undefined behavior. **This precondition is enforced with an assertion.**
  17534. @pre Each element in the range has a size of 1 byte. Violating this
  17535. precondition yields undefined behavior. **This precondition is enforced
  17536. with a static assertion.**
  17537. @warning There is no way to enforce all preconditions at compile-time. If
  17538. the function is called with noncompliant iterators and with
  17539. assertions switched off, the behavior is undefined and will most
  17540. likely yield segmentation violation.
  17541. @tparam IteratorType iterator of container with contiguous storage
  17542. @param[in] first begin of the range to parse (included)
  17543. @param[in] last end of the range to parse (excluded)
  17544. @param[in] cb a parser callback function of type @ref parser_callback_t
  17545. which is used to control the deserialization by filtering unwanted values
  17546. (optional)
  17547. @param[in] allow_exceptions whether to throw exceptions in case of a
  17548. parse error (optional, true by default)
  17549. @return deserialized JSON value; in case of a parse error and
  17550. @a allow_exceptions set to `false`, the return value will be
  17551. value_t::discarded.
  17552. @throw parse_error.101 in case of an unexpected token
  17553. @throw parse_error.102 if to_unicode fails or surrogate error
  17554. @throw parse_error.103 if to_unicode fails
  17555. @complexity Linear in the length of the input. The parser is a predictive
  17556. LL(1) parser. The complexity can be higher if the parser callback function
  17557. @a cb has a super-linear complexity.
  17558. @note A UTF-8 byte order mark is silently ignored.
  17559. @liveexample{The example below demonstrates the `parse()` function reading
  17560. from an iterator range.,parse__iteratortype__parser_callback_t}
  17561. @since version 2.0.3
  17562. */
  17563. template<class IteratorType, typename std::enable_if<
  17564. std::is_base_of<
  17565. std::random_access_iterator_tag,
  17566. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17567. static basic_json parse(IteratorType first, IteratorType last,
  17568. const parser_callback_t cb = nullptr,
  17569. const bool allow_exceptions = true)
  17570. {
  17571. basic_json result;
  17572. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  17573. return result;
  17574. }
  17575. template<class IteratorType, typename std::enable_if<
  17576. std::is_base_of<
  17577. std::random_access_iterator_tag,
  17578. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17579. static bool accept(IteratorType first, IteratorType last)
  17580. {
  17581. return parser(detail::input_adapter(first, last)).accept(true);
  17582. }
  17583. template<class IteratorType, class SAX, typename std::enable_if<
  17584. std::is_base_of<
  17585. std::random_access_iterator_tag,
  17586. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17587. JSON_HEDLEY_NON_NULL(3)
  17588. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  17589. {
  17590. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  17591. }
  17592. /*!
  17593. @brief deserialize from stream
  17594. @deprecated This stream operator is deprecated and will be removed in
  17595. version 4.0.0 of the library. Please use
  17596. @ref operator>>(std::istream&, basic_json&)
  17597. instead; that is, replace calls like `j << i;` with `i >> j;`.
  17598. @since version 1.0.0; deprecated since version 3.0.0
  17599. */
  17600. JSON_HEDLEY_DEPRECATED(3.0.0)
  17601. friend std::istream& operator<<(basic_json& j, std::istream& i)
  17602. {
  17603. return operator>>(i, j);
  17604. }
  17605. /*!
  17606. @brief deserialize from stream
  17607. Deserializes an input stream to a JSON value.
  17608. @param[in,out] i input stream to read a serialized JSON value from
  17609. @param[in,out] j JSON value to write the deserialized input to
  17610. @throw parse_error.101 in case of an unexpected token
  17611. @throw parse_error.102 if to_unicode fails or surrogate error
  17612. @throw parse_error.103 if to_unicode fails
  17613. @complexity Linear in the length of the input. The parser is a predictive
  17614. LL(1) parser.
  17615. @note A UTF-8 byte order mark is silently ignored.
  17616. @liveexample{The example below shows how a JSON value is constructed by
  17617. reading a serialization from a stream.,operator_deserialize}
  17618. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  17619. parser callback function to filter values while parsing
  17620. @since version 1.0.0
  17621. */
  17622. friend std::istream& operator>>(std::istream& i, basic_json& j)
  17623. {
  17624. parser(detail::input_adapter(i)).parse(false, j);
  17625. return i;
  17626. }
  17627. /// @}
  17628. ///////////////////////////
  17629. // convenience functions //
  17630. ///////////////////////////
  17631. /*!
  17632. @brief return the type as string
  17633. Returns the type name as string to be used in error messages - usually to
  17634. indicate that a function was called on a wrong JSON type.
  17635. @return a string representation of a the @a m_type member:
  17636. Value type | return value
  17637. ----------- | -------------
  17638. null | `"null"`
  17639. boolean | `"boolean"`
  17640. string | `"string"`
  17641. number | `"number"` (for all number types)
  17642. object | `"object"`
  17643. array | `"array"`
  17644. discarded | `"discarded"`
  17645. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17646. @complexity Constant.
  17647. @liveexample{The following code exemplifies `type_name()` for all JSON
  17648. types.,type_name}
  17649. @sa @ref type() -- return the type of the JSON value
  17650. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  17651. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  17652. since 3.0.0
  17653. */
  17654. JSON_HEDLEY_RETURNS_NON_NULL
  17655. const char* type_name() const noexcept
  17656. {
  17657. {
  17658. switch (m_type)
  17659. {
  17660. case value_t::null:
  17661. return "null";
  17662. case value_t::object:
  17663. return "object";
  17664. case value_t::array:
  17665. return "array";
  17666. case value_t::string:
  17667. return "string";
  17668. case value_t::boolean:
  17669. return "boolean";
  17670. case value_t::discarded:
  17671. return "discarded";
  17672. default:
  17673. return "number";
  17674. }
  17675. }
  17676. }
  17677. private:
  17678. //////////////////////
  17679. // member variables //
  17680. //////////////////////
  17681. /// the type of the current element
  17682. value_t m_type = value_t::null;
  17683. /// the value of the current element
  17684. json_value m_value = {};
  17685. //////////////////////////////////////////
  17686. // binary serialization/deserialization //
  17687. //////////////////////////////////////////
  17688. /// @name binary serialization/deserialization support
  17689. /// @{
  17690. public:
  17691. /*!
  17692. @brief create a CBOR serialization of a given JSON value
  17693. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  17694. Binary Object Representation) serialization format. CBOR is a binary
  17695. serialization format which aims to be more compact than JSON itself, yet
  17696. more efficient to parse.
  17697. The library uses the following mapping from JSON values types to
  17698. CBOR types according to the CBOR specification (RFC 7049):
  17699. JSON value type | value/range | CBOR type | first byte
  17700. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  17701. null | `null` | Null | 0xF6
  17702. boolean | `true` | True | 0xF5
  17703. boolean | `false` | False | 0xF4
  17704. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  17705. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  17706. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  17707. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  17708. number_integer | -24..-1 | Negative integer | 0x20..0x37
  17709. number_integer | 0..23 | Integer | 0x00..0x17
  17710. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17711. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17712. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17713. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17714. number_unsigned | 0..23 | Integer | 0x00..0x17
  17715. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17716. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17717. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17718. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17719. number_float | *any value* | Double-Precision Float | 0xFB
  17720. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  17721. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  17722. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  17723. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  17724. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  17725. array | *size*: 0..23 | array | 0x80..0x97
  17726. array | *size*: 23..255 | array (1 byte follow) | 0x98
  17727. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  17728. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  17729. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  17730. object | *size*: 0..23 | map | 0xA0..0xB7
  17731. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  17732. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  17733. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  17734. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  17735. @note The mapping is **complete** in the sense that any JSON value type
  17736. can be converted to a CBOR value.
  17737. @note If NaN or Infinity are stored inside a JSON number, they are
  17738. serialized properly. This behavior differs from the @ref dump()
  17739. function which serializes NaN or Infinity to `null`.
  17740. @note The following CBOR types are not used in the conversion:
  17741. - byte strings (0x40..0x5F)
  17742. - UTF-8 strings terminated by "break" (0x7F)
  17743. - arrays terminated by "break" (0x9F)
  17744. - maps terminated by "break" (0xBF)
  17745. - date/time (0xC0..0xC1)
  17746. - bignum (0xC2..0xC3)
  17747. - decimal fraction (0xC4)
  17748. - bigfloat (0xC5)
  17749. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  17750. - expected conversions (0xD5..0xD7)
  17751. - simple values (0xE0..0xF3, 0xF8)
  17752. - undefined (0xF7)
  17753. - half and single-precision floats (0xF9-0xFA)
  17754. - break (0xFF)
  17755. @param[in] j JSON value to serialize
  17756. @return MessagePack serialization as byte vector
  17757. @complexity Linear in the size of the JSON value @a j.
  17758. @liveexample{The example shows the serialization of a JSON value to a byte
  17759. vector in CBOR format.,to_cbor}
  17760. @sa http://cbor.io
  17761. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  17762. analogous deserialization
  17763. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17764. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17765. related UBJSON format
  17766. @since version 2.0.9
  17767. */
  17768. static std::vector<uint8_t> to_cbor(const basic_json& j)
  17769. {
  17770. std::vector<uint8_t> result;
  17771. to_cbor(j, result);
  17772. return result;
  17773. }
  17774. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  17775. {
  17776. binary_writer<uint8_t>(o).write_cbor(j);
  17777. }
  17778. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  17779. {
  17780. binary_writer<char>(o).write_cbor(j);
  17781. }
  17782. /*!
  17783. @brief create a MessagePack serialization of a given JSON value
  17784. Serializes a given JSON value @a j to a byte vector using the MessagePack
  17785. serialization format. MessagePack is a binary serialization format which
  17786. aims to be more compact than JSON itself, yet more efficient to parse.
  17787. The library uses the following mapping from JSON values types to
  17788. MessagePack types according to the MessagePack specification:
  17789. JSON value type | value/range | MessagePack type | first byte
  17790. --------------- | --------------------------------- | ---------------- | ----------
  17791. null | `null` | nil | 0xC0
  17792. boolean | `true` | true | 0xC3
  17793. boolean | `false` | false | 0xC2
  17794. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  17795. number_integer | -2147483648..-32769 | int32 | 0xD2
  17796. number_integer | -32768..-129 | int16 | 0xD1
  17797. number_integer | -128..-33 | int8 | 0xD0
  17798. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  17799. number_integer | 0..127 | positive fixint | 0x00..0x7F
  17800. number_integer | 128..255 | uint 8 | 0xCC
  17801. number_integer | 256..65535 | uint 16 | 0xCD
  17802. number_integer | 65536..4294967295 | uint 32 | 0xCE
  17803. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17804. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  17805. number_unsigned | 128..255 | uint 8 | 0xCC
  17806. number_unsigned | 256..65535 | uint 16 | 0xCD
  17807. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  17808. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17809. number_float | *any value* | float 64 | 0xCB
  17810. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  17811. string | *length*: 32..255 | str 8 | 0xD9
  17812. string | *length*: 256..65535 | str 16 | 0xDA
  17813. string | *length*: 65536..4294967295 | str 32 | 0xDB
  17814. array | *size*: 0..15 | fixarray | 0x90..0x9F
  17815. array | *size*: 16..65535 | array 16 | 0xDC
  17816. array | *size*: 65536..4294967295 | array 32 | 0xDD
  17817. object | *size*: 0..15 | fix map | 0x80..0x8F
  17818. object | *size*: 16..65535 | map 16 | 0xDE
  17819. object | *size*: 65536..4294967295 | map 32 | 0xDF
  17820. @note The mapping is **complete** in the sense that any JSON value type
  17821. can be converted to a MessagePack value.
  17822. @note The following values can **not** be converted to a MessagePack value:
  17823. - strings with more than 4294967295 bytes
  17824. - arrays with more than 4294967295 elements
  17825. - objects with more than 4294967295 elements
  17826. @note The following MessagePack types are not used in the conversion:
  17827. - bin 8 - bin 32 (0xC4..0xC6)
  17828. - ext 8 - ext 32 (0xC7..0xC9)
  17829. - float 32 (0xCA)
  17830. - fixext 1 - fixext 16 (0xD4..0xD8)
  17831. @note Any MessagePack output created @ref to_msgpack can be successfully
  17832. parsed by @ref from_msgpack.
  17833. @note If NaN or Infinity are stored inside a JSON number, they are
  17834. serialized properly. This behavior differs from the @ref dump()
  17835. function which serializes NaN or Infinity to `null`.
  17836. @param[in] j JSON value to serialize
  17837. @return MessagePack serialization as byte vector
  17838. @complexity Linear in the size of the JSON value @a j.
  17839. @liveexample{The example shows the serialization of a JSON value to a byte
  17840. vector in MessagePack format.,to_msgpack}
  17841. @sa http://msgpack.org
  17842. @sa @ref from_msgpack for the analogous deserialization
  17843. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17844. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17845. related UBJSON format
  17846. @since version 2.0.9
  17847. */
  17848. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  17849. {
  17850. std::vector<uint8_t> result;
  17851. to_msgpack(j, result);
  17852. return result;
  17853. }
  17854. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  17855. {
  17856. binary_writer<uint8_t>(o).write_msgpack(j);
  17857. }
  17858. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  17859. {
  17860. binary_writer<char>(o).write_msgpack(j);
  17861. }
  17862. /*!
  17863. @brief create a UBJSON serialization of a given JSON value
  17864. Serializes a given JSON value @a j to a byte vector using the UBJSON
  17865. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  17866. than JSON itself, yet more efficient to parse.
  17867. The library uses the following mapping from JSON values types to
  17868. UBJSON types according to the UBJSON specification:
  17869. JSON value type | value/range | UBJSON type | marker
  17870. --------------- | --------------------------------- | ----------- | ------
  17871. null | `null` | null | `Z`
  17872. boolean | `true` | true | `T`
  17873. boolean | `false` | false | `F`
  17874. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  17875. number_integer | -2147483648..-32769 | int32 | `l`
  17876. number_integer | -32768..-129 | int16 | `I`
  17877. number_integer | -128..127 | int8 | `i`
  17878. number_integer | 128..255 | uint8 | `U`
  17879. number_integer | 256..32767 | int16 | `I`
  17880. number_integer | 32768..2147483647 | int32 | `l`
  17881. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  17882. number_unsigned | 0..127 | int8 | `i`
  17883. number_unsigned | 128..255 | uint8 | `U`
  17884. number_unsigned | 256..32767 | int16 | `I`
  17885. number_unsigned | 32768..2147483647 | int32 | `l`
  17886. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  17887. number_float | *any value* | float64 | `D`
  17888. string | *with shortest length indicator* | string | `S`
  17889. array | *see notes on optimized format* | array | `[`
  17890. object | *see notes on optimized format* | map | `{`
  17891. @note The mapping is **complete** in the sense that any JSON value type
  17892. can be converted to a UBJSON value.
  17893. @note The following values can **not** be converted to a UBJSON value:
  17894. - strings with more than 9223372036854775807 bytes (theoretical)
  17895. - unsigned integer numbers above 9223372036854775807
  17896. @note The following markers are not used in the conversion:
  17897. - `Z`: no-op values are not created.
  17898. - `C`: single-byte strings are serialized with `S` markers.
  17899. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  17900. by @ref from_ubjson.
  17901. @note If NaN or Infinity are stored inside a JSON number, they are
  17902. serialized properly. This behavior differs from the @ref dump()
  17903. function which serializes NaN or Infinity to `null`.
  17904. @note The optimized formats for containers are supported: Parameter
  17905. @a use_size adds size information to the beginning of a container and
  17906. removes the closing marker. Parameter @a use_type further checks
  17907. whether all elements of a container have the same type and adds the
  17908. type marker to the beginning of the container. The @a use_type
  17909. parameter must only be used together with @a use_size = true. Note
  17910. that @a use_size = true alone may result in larger representations -
  17911. the benefit of this parameter is that the receiving side is
  17912. immediately informed on the number of elements of the container.
  17913. @param[in] j JSON value to serialize
  17914. @param[in] use_size whether to add size annotations to container types
  17915. @param[in] use_type whether to add type annotations to container types
  17916. (must be combined with @a use_size = true)
  17917. @return UBJSON serialization as byte vector
  17918. @complexity Linear in the size of the JSON value @a j.
  17919. @liveexample{The example shows the serialization of a JSON value to a byte
  17920. vector in UBJSON format.,to_ubjson}
  17921. @sa http://ubjson.org
  17922. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  17923. analogous deserialization
  17924. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17925. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17926. @since version 3.1.0
  17927. */
  17928. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  17929. const bool use_size = false,
  17930. const bool use_type = false)
  17931. {
  17932. std::vector<uint8_t> result;
  17933. to_ubjson(j, result, use_size, use_type);
  17934. return result;
  17935. }
  17936. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  17937. const bool use_size = false, const bool use_type = false)
  17938. {
  17939. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  17940. }
  17941. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  17942. const bool use_size = false, const bool use_type = false)
  17943. {
  17944. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  17945. }
  17946. /*!
  17947. @brief Serializes the given JSON object `j` to BSON and returns a vector
  17948. containing the corresponding BSON-representation.
  17949. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  17950. stored as a single entity (a so-called document).
  17951. The library uses the following mapping from JSON values types to BSON types:
  17952. JSON value type | value/range | BSON type | marker
  17953. --------------- | --------------------------------- | ----------- | ------
  17954. null | `null` | null | 0x0A
  17955. boolean | `true`, `false` | boolean | 0x08
  17956. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  17957. number_integer | -2147483648..2147483647 | int32 | 0x10
  17958. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  17959. number_unsigned | 0..2147483647 | int32 | 0x10
  17960. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  17961. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  17962. number_float | *any value* | double | 0x01
  17963. string | *any value* | string | 0x02
  17964. array | *any value* | document | 0x04
  17965. object | *any value* | document | 0x03
  17966. @warning The mapping is **incomplete**, since only JSON-objects (and things
  17967. contained therein) can be serialized to BSON.
  17968. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  17969. and the keys may not contain U+0000, since they are serialized a
  17970. zero-terminated c-strings.
  17971. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  17972. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  17973. @throw type_error.317 if `!j.is_object()`
  17974. @pre The input `j` is required to be an object: `j.is_object() == true`.
  17975. @note Any BSON output created via @ref to_bson can be successfully parsed
  17976. by @ref from_bson.
  17977. @param[in] j JSON value to serialize
  17978. @return BSON serialization as byte vector
  17979. @complexity Linear in the size of the JSON value @a j.
  17980. @liveexample{The example shows the serialization of a JSON value to a byte
  17981. vector in BSON format.,to_bson}
  17982. @sa http://bsonspec.org/spec.html
  17983. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  17984. analogous deserialization
  17985. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17986. related UBJSON format
  17987. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  17988. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17989. */
  17990. static std::vector<uint8_t> to_bson(const basic_json& j)
  17991. {
  17992. std::vector<uint8_t> result;
  17993. to_bson(j, result);
  17994. return result;
  17995. }
  17996. /*!
  17997. @brief Serializes the given JSON object `j` to BSON and forwards the
  17998. corresponding BSON-representation to the given output_adapter `o`.
  17999. @param j The JSON object to convert to BSON.
  18000. @param o The output adapter that receives the binary BSON representation.
  18001. @pre The input `j` shall be an object: `j.is_object() == true`
  18002. @sa @ref to_bson(const basic_json&)
  18003. */
  18004. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  18005. {
  18006. binary_writer<uint8_t>(o).write_bson(j);
  18007. }
  18008. /*!
  18009. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  18010. */
  18011. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  18012. {
  18013. binary_writer<char>(o).write_bson(j);
  18014. }
  18015. /*!
  18016. @brief create a JSON value from an input in CBOR format
  18017. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  18018. Binary Object Representation) serialization format.
  18019. The library maps CBOR types to JSON value types as follows:
  18020. CBOR type | JSON value type | first byte
  18021. ---------------------- | --------------- | ----------
  18022. Integer | number_unsigned | 0x00..0x17
  18023. Unsigned integer | number_unsigned | 0x18
  18024. Unsigned integer | number_unsigned | 0x19
  18025. Unsigned integer | number_unsigned | 0x1A
  18026. Unsigned integer | number_unsigned | 0x1B
  18027. Negative integer | number_integer | 0x20..0x37
  18028. Negative integer | number_integer | 0x38
  18029. Negative integer | number_integer | 0x39
  18030. Negative integer | number_integer | 0x3A
  18031. Negative integer | number_integer | 0x3B
  18032. Negative integer | number_integer | 0x40..0x57
  18033. UTF-8 string | string | 0x60..0x77
  18034. UTF-8 string | string | 0x78
  18035. UTF-8 string | string | 0x79
  18036. UTF-8 string | string | 0x7A
  18037. UTF-8 string | string | 0x7B
  18038. UTF-8 string | string | 0x7F
  18039. array | array | 0x80..0x97
  18040. array | array | 0x98
  18041. array | array | 0x99
  18042. array | array | 0x9A
  18043. array | array | 0x9B
  18044. array | array | 0x9F
  18045. map | object | 0xA0..0xB7
  18046. map | object | 0xB8
  18047. map | object | 0xB9
  18048. map | object | 0xBA
  18049. map | object | 0xBB
  18050. map | object | 0xBF
  18051. False | `false` | 0xF4
  18052. True | `true` | 0xF5
  18053. Null | `null` | 0xF6
  18054. Half-Precision Float | number_float | 0xF9
  18055. Single-Precision Float | number_float | 0xFA
  18056. Double-Precision Float | number_float | 0xFB
  18057. @warning The mapping is **incomplete** in the sense that not all CBOR
  18058. types can be converted to a JSON value. The following CBOR types
  18059. are not supported and will yield parse errors (parse_error.112):
  18060. - byte strings (0x40..0x5F)
  18061. - date/time (0xC0..0xC1)
  18062. - bignum (0xC2..0xC3)
  18063. - decimal fraction (0xC4)
  18064. - bigfloat (0xC5)
  18065. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  18066. - expected conversions (0xD5..0xD7)
  18067. - simple values (0xE0..0xF3, 0xF8)
  18068. - undefined (0xF7)
  18069. @warning CBOR allows map keys of any type, whereas JSON only allows
  18070. strings as keys in object values. Therefore, CBOR maps with keys
  18071. other than UTF-8 strings are rejected (parse_error.113).
  18072. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  18073. @ref from_cbor.
  18074. @param[in] i an input in CBOR format convertible to an input adapter
  18075. @param[in] strict whether to expect the input to be consumed until EOF
  18076. (true by default)
  18077. @param[in] allow_exceptions whether to throw exceptions in case of a
  18078. parse error (optional, true by default)
  18079. @return deserialized JSON value; in case of a parse error and
  18080. @a allow_exceptions set to `false`, the return value will be
  18081. value_t::discarded.
  18082. @throw parse_error.110 if the given input ends prematurely or the end of
  18083. file was not reached when @a strict was set to true
  18084. @throw parse_error.112 if unsupported features from CBOR were
  18085. used in the given input @a v or if the input is not valid CBOR
  18086. @throw parse_error.113 if a string was expected as map key, but not found
  18087. @complexity Linear in the size of the input @a i.
  18088. @liveexample{The example shows the deserialization of a byte vector in CBOR
  18089. format to a JSON value.,from_cbor}
  18090. @sa http://cbor.io
  18091. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  18092. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  18093. related MessagePack format
  18094. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  18095. related UBJSON format
  18096. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  18097. consume input adapters, removed start_index parameter, and added
  18098. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  18099. since 3.2.0
  18100. */
  18101. JSON_HEDLEY_WARN_UNUSED_RESULT
  18102. static basic_json from_cbor(detail::input_adapter&& i,
  18103. const bool strict = true,
  18104. const bool allow_exceptions = true)
  18105. {
  18106. basic_json result;
  18107. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18108. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  18109. return res ? result : basic_json(value_t::discarded);
  18110. }
  18111. /*!
  18112. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  18113. */
  18114. template<typename A1, typename A2,
  18115. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18116. JSON_HEDLEY_WARN_UNUSED_RESULT
  18117. static basic_json from_cbor(A1 && a1, A2 && a2,
  18118. const bool strict = true,
  18119. const bool allow_exceptions = true)
  18120. {
  18121. basic_json result;
  18122. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18123. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  18124. return res ? result : basic_json(value_t::discarded);
  18125. }
  18126. /*!
  18127. @brief create a JSON value from an input in MessagePack format
  18128. Deserializes a given input @a i to a JSON value using the MessagePack
  18129. serialization format.
  18130. The library maps MessagePack types to JSON value types as follows:
  18131. MessagePack type | JSON value type | first byte
  18132. ---------------- | --------------- | ----------
  18133. positive fixint | number_unsigned | 0x00..0x7F
  18134. fixmap | object | 0x80..0x8F
  18135. fixarray | array | 0x90..0x9F
  18136. fixstr | string | 0xA0..0xBF
  18137. nil | `null` | 0xC0
  18138. false | `false` | 0xC2
  18139. true | `true` | 0xC3
  18140. float 32 | number_float | 0xCA
  18141. float 64 | number_float | 0xCB
  18142. uint 8 | number_unsigned | 0xCC
  18143. uint 16 | number_unsigned | 0xCD
  18144. uint 32 | number_unsigned | 0xCE
  18145. uint 64 | number_unsigned | 0xCF
  18146. int 8 | number_integer | 0xD0
  18147. int 16 | number_integer | 0xD1
  18148. int 32 | number_integer | 0xD2
  18149. int 64 | number_integer | 0xD3
  18150. str 8 | string | 0xD9
  18151. str 16 | string | 0xDA
  18152. str 32 | string | 0xDB
  18153. array 16 | array | 0xDC
  18154. array 32 | array | 0xDD
  18155. map 16 | object | 0xDE
  18156. map 32 | object | 0xDF
  18157. negative fixint | number_integer | 0xE0-0xFF
  18158. @warning The mapping is **incomplete** in the sense that not all
  18159. MessagePack types can be converted to a JSON value. The following
  18160. MessagePack types are not supported and will yield parse errors:
  18161. - bin 8 - bin 32 (0xC4..0xC6)
  18162. - ext 8 - ext 32 (0xC7..0xC9)
  18163. - fixext 1 - fixext 16 (0xD4..0xD8)
  18164. @note Any MessagePack output created @ref to_msgpack can be successfully
  18165. parsed by @ref from_msgpack.
  18166. @param[in] i an input in MessagePack format convertible to an input
  18167. adapter
  18168. @param[in] strict whether to expect the input to be consumed until EOF
  18169. (true by default)
  18170. @param[in] allow_exceptions whether to throw exceptions in case of a
  18171. parse error (optional, true by default)
  18172. @return deserialized JSON value; in case of a parse error and
  18173. @a allow_exceptions set to `false`, the return value will be
  18174. value_t::discarded.
  18175. @throw parse_error.110 if the given input ends prematurely or the end of
  18176. file was not reached when @a strict was set to true
  18177. @throw parse_error.112 if unsupported features from MessagePack were
  18178. used in the given input @a i or if the input is not valid MessagePack
  18179. @throw parse_error.113 if a string was expected as map key, but not found
  18180. @complexity Linear in the size of the input @a i.
  18181. @liveexample{The example shows the deserialization of a byte vector in
  18182. MessagePack format to a JSON value.,from_msgpack}
  18183. @sa http://msgpack.org
  18184. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  18185. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18186. related CBOR format
  18187. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  18188. the related UBJSON format
  18189. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18190. the related BSON format
  18191. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  18192. consume input adapters, removed start_index parameter, and added
  18193. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  18194. since 3.2.0
  18195. */
  18196. JSON_HEDLEY_WARN_UNUSED_RESULT
  18197. static basic_json from_msgpack(detail::input_adapter&& i,
  18198. const bool strict = true,
  18199. const bool allow_exceptions = true)
  18200. {
  18201. basic_json result;
  18202. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18203. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18204. return res ? result : basic_json(value_t::discarded);
  18205. }
  18206. /*!
  18207. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  18208. */
  18209. template<typename A1, typename A2,
  18210. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18211. JSON_HEDLEY_WARN_UNUSED_RESULT
  18212. static basic_json from_msgpack(A1 && a1, A2 && a2,
  18213. const bool strict = true,
  18214. const bool allow_exceptions = true)
  18215. {
  18216. basic_json result;
  18217. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18218. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  18219. return res ? result : basic_json(value_t::discarded);
  18220. }
  18221. /*!
  18222. @brief create a JSON value from an input in UBJSON format
  18223. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  18224. Binary JSON) serialization format.
  18225. The library maps UBJSON types to JSON value types as follows:
  18226. UBJSON type | JSON value type | marker
  18227. ----------- | --------------------------------------- | ------
  18228. no-op | *no value, next value is read* | `N`
  18229. null | `null` | `Z`
  18230. false | `false` | `F`
  18231. true | `true` | `T`
  18232. float32 | number_float | `d`
  18233. float64 | number_float | `D`
  18234. uint8 | number_unsigned | `U`
  18235. int8 | number_integer | `i`
  18236. int16 | number_integer | `I`
  18237. int32 | number_integer | `l`
  18238. int64 | number_integer | `L`
  18239. string | string | `S`
  18240. char | string | `C`
  18241. array | array (optimized values are supported) | `[`
  18242. object | object (optimized values are supported) | `{`
  18243. @note The mapping is **complete** in the sense that any UBJSON value can
  18244. be converted to a JSON value.
  18245. @param[in] i an input in UBJSON format convertible to an input adapter
  18246. @param[in] strict whether to expect the input to be consumed until EOF
  18247. (true by default)
  18248. @param[in] allow_exceptions whether to throw exceptions in case of a
  18249. parse error (optional, true by default)
  18250. @return deserialized JSON value; in case of a parse error and
  18251. @a allow_exceptions set to `false`, the return value will be
  18252. value_t::discarded.
  18253. @throw parse_error.110 if the given input ends prematurely or the end of
  18254. file was not reached when @a strict was set to true
  18255. @throw parse_error.112 if a parse error occurs
  18256. @throw parse_error.113 if a string could not be parsed successfully
  18257. @complexity Linear in the size of the input @a i.
  18258. @liveexample{The example shows the deserialization of a byte vector in
  18259. UBJSON format to a JSON value.,from_ubjson}
  18260. @sa http://ubjson.org
  18261. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  18262. analogous serialization
  18263. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18264. related CBOR format
  18265. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18266. the related MessagePack format
  18267. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18268. the related BSON format
  18269. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  18270. */
  18271. JSON_HEDLEY_WARN_UNUSED_RESULT
  18272. static basic_json from_ubjson(detail::input_adapter&& i,
  18273. const bool strict = true,
  18274. const bool allow_exceptions = true)
  18275. {
  18276. basic_json result;
  18277. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18278. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18279. return res ? result : basic_json(value_t::discarded);
  18280. }
  18281. /*!
  18282. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  18283. */
  18284. template<typename A1, typename A2,
  18285. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18286. JSON_HEDLEY_WARN_UNUSED_RESULT
  18287. static basic_json from_ubjson(A1 && a1, A2 && a2,
  18288. const bool strict = true,
  18289. const bool allow_exceptions = true)
  18290. {
  18291. basic_json result;
  18292. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18293. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  18294. return res ? result : basic_json(value_t::discarded);
  18295. }
  18296. /*!
  18297. @brief Create a JSON value from an input in BSON format
  18298. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  18299. serialization format.
  18300. The library maps BSON record types to JSON value types as follows:
  18301. BSON type | BSON marker byte | JSON value type
  18302. --------------- | ---------------- | ---------------------------
  18303. double | 0x01 | number_float
  18304. string | 0x02 | string
  18305. document | 0x03 | object
  18306. array | 0x04 | array
  18307. binary | 0x05 | still unsupported
  18308. undefined | 0x06 | still unsupported
  18309. ObjectId | 0x07 | still unsupported
  18310. boolean | 0x08 | boolean
  18311. UTC Date-Time | 0x09 | still unsupported
  18312. null | 0x0A | null
  18313. Regular Expr. | 0x0B | still unsupported
  18314. DB Pointer | 0x0C | still unsupported
  18315. JavaScript Code | 0x0D | still unsupported
  18316. Symbol | 0x0E | still unsupported
  18317. JavaScript Code | 0x0F | still unsupported
  18318. int32 | 0x10 | number_integer
  18319. Timestamp | 0x11 | still unsupported
  18320. 128-bit decimal float | 0x13 | still unsupported
  18321. Max Key | 0x7F | still unsupported
  18322. Min Key | 0xFF | still unsupported
  18323. @warning The mapping is **incomplete**. The unsupported mappings
  18324. are indicated in the table above.
  18325. @param[in] i an input in BSON format convertible to an input adapter
  18326. @param[in] strict whether to expect the input to be consumed until EOF
  18327. (true by default)
  18328. @param[in] allow_exceptions whether to throw exceptions in case of a
  18329. parse error (optional, true by default)
  18330. @return deserialized JSON value; in case of a parse error and
  18331. @a allow_exceptions set to `false`, the return value will be
  18332. value_t::discarded.
  18333. @throw parse_error.114 if an unsupported BSON record type is encountered
  18334. @complexity Linear in the size of the input @a i.
  18335. @liveexample{The example shows the deserialization of a byte vector in
  18336. BSON format to a JSON value.,from_bson}
  18337. @sa http://bsonspec.org/spec.html
  18338. @sa @ref to_bson(const basic_json&) for the analogous serialization
  18339. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18340. related CBOR format
  18341. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18342. the related MessagePack format
  18343. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  18344. related UBJSON format
  18345. */
  18346. JSON_HEDLEY_WARN_UNUSED_RESULT
  18347. static basic_json from_bson(detail::input_adapter&& i,
  18348. const bool strict = true,
  18349. const bool allow_exceptions = true)
  18350. {
  18351. basic_json result;
  18352. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18353. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  18354. return res ? result : basic_json(value_t::discarded);
  18355. }
  18356. /*!
  18357. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  18358. */
  18359. template<typename A1, typename A2,
  18360. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18361. JSON_HEDLEY_WARN_UNUSED_RESULT
  18362. static basic_json from_bson(A1 && a1, A2 && a2,
  18363. const bool strict = true,
  18364. const bool allow_exceptions = true)
  18365. {
  18366. basic_json result;
  18367. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18368. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  18369. return res ? result : basic_json(value_t::discarded);
  18370. }
  18371. /// @}
  18372. //////////////////////////
  18373. // JSON Pointer support //
  18374. //////////////////////////
  18375. /// @name JSON Pointer functions
  18376. /// @{
  18377. /*!
  18378. @brief access specified element via JSON Pointer
  18379. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18380. No bound checking is performed. Similar to @ref operator[](const typename
  18381. object_t::key_type&), `null` values are created in arrays and objects if
  18382. necessary.
  18383. In particular:
  18384. - If the JSON pointer points to an object key that does not exist, it
  18385. is created an filled with a `null` value before a reference to it
  18386. is returned.
  18387. - If the JSON pointer points to an array index that does not exist, it
  18388. is created an filled with a `null` value before a reference to it
  18389. is returned. All indices between the current maximum and the given
  18390. index are also filled with `null`.
  18391. - The special value `-` is treated as a synonym for the index past the
  18392. end.
  18393. @param[in] ptr a JSON pointer
  18394. @return reference to the element pointed to by @a ptr
  18395. @complexity Constant.
  18396. @throw parse_error.106 if an array index begins with '0'
  18397. @throw parse_error.109 if an array index was not a number
  18398. @throw out_of_range.404 if the JSON pointer can not be resolved
  18399. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  18400. @since version 2.0.0
  18401. */
  18402. reference operator[](const json_pointer& ptr)
  18403. {
  18404. return ptr.get_unchecked(this);
  18405. }
  18406. /*!
  18407. @brief access specified element via JSON Pointer
  18408. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18409. No bound checking is performed. The function does not change the JSON
  18410. value; no `null` values are created. In particular, the the special value
  18411. `-` yields an exception.
  18412. @param[in] ptr JSON pointer to the desired element
  18413. @return const reference to the element pointed to by @a ptr
  18414. @complexity Constant.
  18415. @throw parse_error.106 if an array index begins with '0'
  18416. @throw parse_error.109 if an array index was not a number
  18417. @throw out_of_range.402 if the array index '-' is used
  18418. @throw out_of_range.404 if the JSON pointer can not be resolved
  18419. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  18420. @since version 2.0.0
  18421. */
  18422. const_reference operator[](const json_pointer& ptr) const
  18423. {
  18424. return ptr.get_unchecked(this);
  18425. }
  18426. /*!
  18427. @brief access specified element via JSON Pointer
  18428. Returns a reference to the element at with specified JSON pointer @a ptr,
  18429. with bounds checking.
  18430. @param[in] ptr JSON pointer to the desired element
  18431. @return reference to the element pointed to by @a ptr
  18432. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18433. begins with '0'. See example below.
  18434. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18435. is not a number. See example below.
  18436. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18437. is out of range. See example below.
  18438. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18439. pointer @a ptr. As `at` provides checked access (and no elements are
  18440. implicitly inserted), the index '-' is always invalid. See example below.
  18441. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18442. which cannot be found. See example below.
  18443. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18444. See example below.
  18445. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18446. changes in the JSON value.
  18447. @complexity Constant.
  18448. @since version 2.0.0
  18449. @liveexample{The behavior is shown in the example.,at_json_pointer}
  18450. */
  18451. reference at(const json_pointer& ptr)
  18452. {
  18453. return ptr.get_checked(this);
  18454. }
  18455. /*!
  18456. @brief access specified element via JSON Pointer
  18457. Returns a const reference to the element at with specified JSON pointer @a
  18458. ptr, with bounds checking.
  18459. @param[in] ptr JSON pointer to the desired element
  18460. @return reference to the element pointed to by @a ptr
  18461. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18462. begins with '0'. See example below.
  18463. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18464. is not a number. See example below.
  18465. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18466. is out of range. See example below.
  18467. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18468. pointer @a ptr. As `at` provides checked access (and no elements are
  18469. implicitly inserted), the index '-' is always invalid. See example below.
  18470. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18471. which cannot be found. See example below.
  18472. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18473. See example below.
  18474. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18475. changes in the JSON value.
  18476. @complexity Constant.
  18477. @since version 2.0.0
  18478. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  18479. */
  18480. const_reference at(const json_pointer& ptr) const
  18481. {
  18482. return ptr.get_checked(this);
  18483. }
  18484. /*!
  18485. @brief return flattened JSON value
  18486. The function creates a JSON object whose keys are JSON pointers (see [RFC
  18487. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  18488. primitive. The original JSON value can be restored using the @ref
  18489. unflatten() function.
  18490. @return an object that maps JSON pointers to primitive values
  18491. @note Empty objects and arrays are flattened to `null` and will not be
  18492. reconstructed correctly by the @ref unflatten() function.
  18493. @complexity Linear in the size the JSON value.
  18494. @liveexample{The following code shows how a JSON object is flattened to an
  18495. object whose keys consist of JSON pointers.,flatten}
  18496. @sa @ref unflatten() for the reverse function
  18497. @since version 2.0.0
  18498. */
  18499. basic_json flatten() const
  18500. {
  18501. basic_json result(value_t::object);
  18502. json_pointer::flatten("", *this, result);
  18503. return result;
  18504. }
  18505. /*!
  18506. @brief unflatten a previously flattened JSON value
  18507. The function restores the arbitrary nesting of a JSON value that has been
  18508. flattened before using the @ref flatten() function. The JSON value must
  18509. meet certain constraints:
  18510. 1. The value must be an object.
  18511. 2. The keys must be JSON pointers (see
  18512. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  18513. 3. The mapped values must be primitive JSON types.
  18514. @return the original JSON from a flattened version
  18515. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  18516. values and can not unflattened to their original type. Apart from
  18517. this example, for a JSON value `j`, the following is always true:
  18518. `j == j.flatten().unflatten()`.
  18519. @complexity Linear in the size the JSON value.
  18520. @throw type_error.314 if value is not an object
  18521. @throw type_error.315 if object values are not primitive
  18522. @liveexample{The following code shows how a flattened JSON object is
  18523. unflattened into the original nested JSON object.,unflatten}
  18524. @sa @ref flatten() for the reverse function
  18525. @since version 2.0.0
  18526. */
  18527. basic_json unflatten() const
  18528. {
  18529. return json_pointer::unflatten(*this);
  18530. }
  18531. /// @}
  18532. //////////////////////////
  18533. // JSON Patch functions //
  18534. //////////////////////////
  18535. /// @name JSON Patch functions
  18536. /// @{
  18537. /*!
  18538. @brief applies a JSON patch
  18539. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  18540. expressing a sequence of operations to apply to a JSON) document. With
  18541. this function, a JSON Patch is applied to the current JSON value by
  18542. executing all operations from the patch.
  18543. @param[in] json_patch JSON patch document
  18544. @return patched document
  18545. @note The application of a patch is atomic: Either all operations succeed
  18546. and the patched document is returned or an exception is thrown. In
  18547. any case, the original value is not changed: the patch is applied
  18548. to a copy of the value.
  18549. @throw parse_error.104 if the JSON patch does not consist of an array of
  18550. objects
  18551. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  18552. attributes are missing); example: `"operation add must have member path"`
  18553. @throw out_of_range.401 if an array index is out of range.
  18554. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  18555. resolved successfully in the current JSON value; example: `"key baz not
  18556. found"`
  18557. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  18558. "move")
  18559. @throw other_error.501 if "test" operation was unsuccessful
  18560. @complexity Linear in the size of the JSON value and the length of the
  18561. JSON patch. As usually only a fraction of the JSON value is affected by
  18562. the patch, the complexity can usually be neglected.
  18563. @liveexample{The following code shows how a JSON patch is applied to a
  18564. value.,patch}
  18565. @sa @ref diff -- create a JSON patch by comparing two JSON values
  18566. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18567. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  18568. @since version 2.0.0
  18569. */
  18570. basic_json patch(const basic_json& json_patch) const
  18571. {
  18572. // make a working copy to apply the patch to
  18573. basic_json result = *this;
  18574. // the valid JSON Patch operations
  18575. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  18576. const auto get_op = [](const std::string & op)
  18577. {
  18578. if (op == "add")
  18579. {
  18580. return patch_operations::add;
  18581. }
  18582. if (op == "remove")
  18583. {
  18584. return patch_operations::remove;
  18585. }
  18586. if (op == "replace")
  18587. {
  18588. return patch_operations::replace;
  18589. }
  18590. if (op == "move")
  18591. {
  18592. return patch_operations::move;
  18593. }
  18594. if (op == "copy")
  18595. {
  18596. return patch_operations::copy;
  18597. }
  18598. if (op == "test")
  18599. {
  18600. return patch_operations::test;
  18601. }
  18602. return patch_operations::invalid;
  18603. };
  18604. // wrapper for "add" operation; add value at ptr
  18605. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  18606. {
  18607. // adding to the root of the target document means replacing it
  18608. if (ptr.empty())
  18609. {
  18610. result = val;
  18611. return;
  18612. }
  18613. // make sure the top element of the pointer exists
  18614. json_pointer top_pointer = ptr.top();
  18615. if (top_pointer != ptr)
  18616. {
  18617. result.at(top_pointer);
  18618. }
  18619. // get reference to parent of JSON pointer ptr
  18620. const auto last_path = ptr.back();
  18621. ptr.pop_back();
  18622. basic_json& parent = result[ptr];
  18623. switch (parent.m_type)
  18624. {
  18625. case value_t::null:
  18626. case value_t::object:
  18627. {
  18628. // use operator[] to add value
  18629. parent[last_path] = val;
  18630. break;
  18631. }
  18632. case value_t::array:
  18633. {
  18634. if (last_path == "-")
  18635. {
  18636. // special case: append to back
  18637. parent.push_back(val);
  18638. }
  18639. else
  18640. {
  18641. const auto idx = json_pointer::array_index(last_path);
  18642. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  18643. {
  18644. // avoid undefined behavior
  18645. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  18646. }
  18647. // default case: insert add offset
  18648. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  18649. }
  18650. break;
  18651. }
  18652. // if there exists a parent it cannot be primitive
  18653. default: // LCOV_EXCL_LINE
  18654. assert(false); // LCOV_EXCL_LINE
  18655. }
  18656. };
  18657. // wrapper for "remove" operation; remove value at ptr
  18658. const auto operation_remove = [&result](json_pointer & ptr)
  18659. {
  18660. // get reference to parent of JSON pointer ptr
  18661. const auto last_path = ptr.back();
  18662. ptr.pop_back();
  18663. basic_json& parent = result.at(ptr);
  18664. // remove child
  18665. if (parent.is_object())
  18666. {
  18667. // perform range check
  18668. auto it = parent.find(last_path);
  18669. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  18670. {
  18671. parent.erase(it);
  18672. }
  18673. else
  18674. {
  18675. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  18676. }
  18677. }
  18678. else if (parent.is_array())
  18679. {
  18680. // note erase performs range check
  18681. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  18682. }
  18683. };
  18684. // type check: top level value must be an array
  18685. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  18686. {
  18687. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18688. }
  18689. // iterate and apply the operations
  18690. for (const auto& val : json_patch)
  18691. {
  18692. // wrapper to get a value for an operation
  18693. const auto get_value = [&val](const std::string & op,
  18694. const std::string & member,
  18695. bool string_type) -> basic_json &
  18696. {
  18697. // find value
  18698. auto it = val.m_value.object->find(member);
  18699. // context-sensitive error message
  18700. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  18701. // check if desired value is present
  18702. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  18703. {
  18704. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  18705. }
  18706. // check if result is of type string
  18707. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  18708. {
  18709. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  18710. }
  18711. // no error: return value
  18712. return it->second;
  18713. };
  18714. // type check: every element of the array must be an object
  18715. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  18716. {
  18717. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18718. }
  18719. // collect mandatory members
  18720. const std::string op = get_value("op", "op", true);
  18721. const std::string path = get_value(op, "path", true);
  18722. json_pointer ptr(path);
  18723. switch (get_op(op))
  18724. {
  18725. case patch_operations::add:
  18726. {
  18727. operation_add(ptr, get_value("add", "value", false));
  18728. break;
  18729. }
  18730. case patch_operations::remove:
  18731. {
  18732. operation_remove(ptr);
  18733. break;
  18734. }
  18735. case patch_operations::replace:
  18736. {
  18737. // the "path" location must exist - use at()
  18738. result.at(ptr) = get_value("replace", "value", false);
  18739. break;
  18740. }
  18741. case patch_operations::move:
  18742. {
  18743. const std::string from_path = get_value("move", "from", true);
  18744. json_pointer from_ptr(from_path);
  18745. // the "from" location must exist - use at()
  18746. basic_json v = result.at(from_ptr);
  18747. // The move operation is functionally identical to a
  18748. // "remove" operation on the "from" location, followed
  18749. // immediately by an "add" operation at the target
  18750. // location with the value that was just removed.
  18751. operation_remove(from_ptr);
  18752. operation_add(ptr, v);
  18753. break;
  18754. }
  18755. case patch_operations::copy:
  18756. {
  18757. const std::string from_path = get_value("copy", "from", true);
  18758. const json_pointer from_ptr(from_path);
  18759. // the "from" location must exist - use at()
  18760. basic_json v = result.at(from_ptr);
  18761. // The copy is functionally identical to an "add"
  18762. // operation at the target location using the value
  18763. // specified in the "from" member.
  18764. operation_add(ptr, v);
  18765. break;
  18766. }
  18767. case patch_operations::test:
  18768. {
  18769. bool success = false;
  18770. JSON_TRY
  18771. {
  18772. // check if "value" matches the one at "path"
  18773. // the "path" location must exist - use at()
  18774. success = (result.at(ptr) == get_value("test", "value", false));
  18775. }
  18776. JSON_INTERNAL_CATCH (out_of_range&)
  18777. {
  18778. // ignore out of range errors: success remains false
  18779. }
  18780. // throw an exception if test fails
  18781. if (JSON_HEDLEY_UNLIKELY(not success))
  18782. {
  18783. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  18784. }
  18785. break;
  18786. }
  18787. default:
  18788. {
  18789. // op must be "add", "remove", "replace", "move", "copy", or
  18790. // "test"
  18791. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  18792. }
  18793. }
  18794. }
  18795. return result;
  18796. }
  18797. /*!
  18798. @brief creates a diff as a JSON patch
  18799. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  18800. be changed into the value @a target by calling @ref patch function.
  18801. @invariant For two JSON values @a source and @a target, the following code
  18802. yields always `true`:
  18803. @code {.cpp}
  18804. source.patch(diff(source, target)) == target;
  18805. @endcode
  18806. @note Currently, only `remove`, `add`, and `replace` operations are
  18807. generated.
  18808. @param[in] source JSON value to compare from
  18809. @param[in] target JSON value to compare against
  18810. @param[in] path helper value to create JSON pointers
  18811. @return a JSON patch to convert the @a source to @a target
  18812. @complexity Linear in the lengths of @a source and @a target.
  18813. @liveexample{The following code shows how a JSON patch is created as a
  18814. diff for two JSON values.,diff}
  18815. @sa @ref patch -- apply a JSON patch
  18816. @sa @ref merge_patch -- apply a JSON Merge Patch
  18817. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18818. @since version 2.0.0
  18819. */
  18820. JSON_HEDLEY_WARN_UNUSED_RESULT
  18821. static basic_json diff(const basic_json& source, const basic_json& target,
  18822. const std::string& path = "")
  18823. {
  18824. // the patch
  18825. basic_json result(value_t::array);
  18826. // if the values are the same, return empty patch
  18827. if (source == target)
  18828. {
  18829. return result;
  18830. }
  18831. if (source.type() != target.type())
  18832. {
  18833. // different types: replace value
  18834. result.push_back(
  18835. {
  18836. {"op", "replace"}, {"path", path}, {"value", target}
  18837. });
  18838. return result;
  18839. }
  18840. switch (source.type())
  18841. {
  18842. case value_t::array:
  18843. {
  18844. // first pass: traverse common elements
  18845. std::size_t i = 0;
  18846. while (i < source.size() and i < target.size())
  18847. {
  18848. // recursive call to compare array values at index i
  18849. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  18850. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18851. ++i;
  18852. }
  18853. // i now reached the end of at least one array
  18854. // in a second pass, traverse the remaining elements
  18855. // remove my remaining elements
  18856. const auto end_index = static_cast<difference_type>(result.size());
  18857. while (i < source.size())
  18858. {
  18859. // add operations in reverse order to avoid invalid
  18860. // indices
  18861. result.insert(result.begin() + end_index, object(
  18862. {
  18863. {"op", "remove"},
  18864. {"path", path + "/" + std::to_string(i)}
  18865. }));
  18866. ++i;
  18867. }
  18868. // add other remaining elements
  18869. while (i < target.size())
  18870. {
  18871. result.push_back(
  18872. {
  18873. {"op", "add"},
  18874. {"path", path + "/" + std::to_string(i)},
  18875. {"value", target[i]}
  18876. });
  18877. ++i;
  18878. }
  18879. break;
  18880. }
  18881. case value_t::object:
  18882. {
  18883. // first pass: traverse this object's elements
  18884. for (auto it = source.cbegin(); it != source.cend(); ++it)
  18885. {
  18886. // escape the key name to be used in a JSON patch
  18887. const auto key = json_pointer::escape(it.key());
  18888. if (target.find(it.key()) != target.end())
  18889. {
  18890. // recursive call to compare object values at key it
  18891. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  18892. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18893. }
  18894. else
  18895. {
  18896. // found a key that is not in o -> remove it
  18897. result.push_back(object(
  18898. {
  18899. {"op", "remove"}, {"path", path + "/" + key}
  18900. }));
  18901. }
  18902. }
  18903. // second pass: traverse other object's elements
  18904. for (auto it = target.cbegin(); it != target.cend(); ++it)
  18905. {
  18906. if (source.find(it.key()) == source.end())
  18907. {
  18908. // found a key that is not in this -> add it
  18909. const auto key = json_pointer::escape(it.key());
  18910. result.push_back(
  18911. {
  18912. {"op", "add"}, {"path", path + "/" + key},
  18913. {"value", it.value()}
  18914. });
  18915. }
  18916. }
  18917. break;
  18918. }
  18919. default:
  18920. {
  18921. // both primitive type: replace value
  18922. result.push_back(
  18923. {
  18924. {"op", "replace"}, {"path", path}, {"value", target}
  18925. });
  18926. break;
  18927. }
  18928. }
  18929. return result;
  18930. }
  18931. /// @}
  18932. ////////////////////////////////
  18933. // JSON Merge Patch functions //
  18934. ////////////////////////////////
  18935. /// @name JSON Merge Patch functions
  18936. /// @{
  18937. /*!
  18938. @brief applies a JSON Merge Patch
  18939. The merge patch format is primarily intended for use with the HTTP PATCH
  18940. method as a means of describing a set of modifications to a target
  18941. resource's content. This function applies a merge patch to the current
  18942. JSON value.
  18943. The function implements the following algorithm from Section 2 of
  18944. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  18945. ```
  18946. define MergePatch(Target, Patch):
  18947. if Patch is an Object:
  18948. if Target is not an Object:
  18949. Target = {} // Ignore the contents and set it to an empty Object
  18950. for each Name/Value pair in Patch:
  18951. if Value is null:
  18952. if Name exists in Target:
  18953. remove the Name/Value pair from Target
  18954. else:
  18955. Target[Name] = MergePatch(Target[Name], Value)
  18956. return Target
  18957. else:
  18958. return Patch
  18959. ```
  18960. Thereby, `Target` is the current object; that is, the patch is applied to
  18961. the current value.
  18962. @param[in] apply_patch the patch to apply
  18963. @complexity Linear in the lengths of @a patch.
  18964. @liveexample{The following code shows how a JSON Merge Patch is applied to
  18965. a JSON document.,merge_patch}
  18966. @sa @ref patch -- apply a JSON patch
  18967. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  18968. @since version 3.0.0
  18969. */
  18970. void merge_patch(const basic_json& apply_patch)
  18971. {
  18972. if (apply_patch.is_object())
  18973. {
  18974. if (not is_object())
  18975. {
  18976. *this = object();
  18977. }
  18978. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  18979. {
  18980. if (it.value().is_null())
  18981. {
  18982. erase(it.key());
  18983. }
  18984. else
  18985. {
  18986. operator[](it.key()).merge_patch(it.value());
  18987. }
  18988. }
  18989. }
  18990. else
  18991. {
  18992. *this = apply_patch;
  18993. }
  18994. }
  18995. /// @}
  18996. };
  18997. /*!
  18998. @brief user-defined to_string function for JSON values
  18999. This function implements a user-defined to_string for JSON objects.
  19000. @param[in] j a JSON object
  19001. @return a std::string object
  19002. */
  19003. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19004. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  19005. {
  19006. return j.dump();
  19007. }
  19008. } // namespace nlohmann
  19009. ///////////////////////
  19010. // nonmember support //
  19011. ///////////////////////
  19012. // specialization of std::swap, and std::hash
  19013. namespace std
  19014. {
  19015. /// hash value for JSON objects
  19016. template<>
  19017. struct hash<nlohmann::json>
  19018. {
  19019. /*!
  19020. @brief return a hash value for a JSON object
  19021. @since version 1.0.0
  19022. */
  19023. std::size_t operator()(const nlohmann::json& j) const
  19024. {
  19025. // a naive hashing via the string representation
  19026. const auto& h = hash<nlohmann::json::string_t>();
  19027. return h(j.dump());
  19028. }
  19029. };
  19030. /// specialization for std::less<value_t>
  19031. /// @note: do not remove the space after '<',
  19032. /// see https://github.com/nlohmann/json/pull/679
  19033. template<>
  19034. struct less< ::nlohmann::detail::value_t>
  19035. {
  19036. /*!
  19037. @brief compare two value_t enum values
  19038. @since version 3.0.0
  19039. */
  19040. bool operator()(nlohmann::detail::value_t lhs,
  19041. nlohmann::detail::value_t rhs) const noexcept
  19042. {
  19043. return nlohmann::detail::operator<(lhs, rhs);
  19044. }
  19045. };
  19046. /*!
  19047. @brief exchanges the values of two JSON objects
  19048. @since version 1.0.0
  19049. */
  19050. template<>
  19051. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  19052. is_nothrow_move_constructible<nlohmann::json>::value and
  19053. is_nothrow_move_assignable<nlohmann::json>::value
  19054. )
  19055. {
  19056. j1.swap(j2);
  19057. }
  19058. } // namespace std
  19059. /*!
  19060. @brief user-defined string literal for JSON values
  19061. This operator implements a user-defined string literal for JSON objects. It
  19062. can be used by adding `"_json"` to a string literal and returns a JSON object
  19063. if no parse error occurred.
  19064. @param[in] s a string representation of a JSON object
  19065. @param[in] n the length of string @a s
  19066. @return a JSON object
  19067. @since version 1.0.0
  19068. */
  19069. JSON_HEDLEY_NON_NULL(1)
  19070. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  19071. {
  19072. return nlohmann::json::parse(s, s + n);
  19073. }
  19074. /*!
  19075. @brief user-defined string literal for JSON pointer
  19076. This operator implements a user-defined string literal for JSON Pointers. It
  19077. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  19078. object if no parse error occurred.
  19079. @param[in] s a string representation of a JSON Pointer
  19080. @param[in] n the length of string @a s
  19081. @return a JSON pointer object
  19082. @since version 2.0.0
  19083. */
  19084. JSON_HEDLEY_NON_NULL(1)
  19085. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  19086. {
  19087. return nlohmann::json::json_pointer(std::string(s, n));
  19088. }
  19089. // #include <nlohmann/detail/macro_unscope.hpp>
  19090. // restore GCC/clang diagnostic settings
  19091. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  19092. #pragma GCC diagnostic pop
  19093. #endif
  19094. #if defined(__clang__)
  19095. #pragma GCC diagnostic pop
  19096. #endif
  19097. // clean up
  19098. #undef JSON_INTERNAL_CATCH
  19099. #undef JSON_CATCH
  19100. #undef JSON_THROW
  19101. #undef JSON_TRY
  19102. #undef JSON_HAS_CPP_14
  19103. #undef JSON_HAS_CPP_17
  19104. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19105. #undef NLOHMANN_BASIC_JSON_TPL
  19106. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  19107. #undef JSON_HEDLEY_ALWAYS_INLINE
  19108. #undef JSON_HEDLEY_ARM_VERSION
  19109. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  19110. #undef JSON_HEDLEY_ARRAY_PARAM
  19111. #undef JSON_HEDLEY_ASSUME
  19112. #undef JSON_HEDLEY_BEGIN_C_DECLS
  19113. #undef JSON_HEDLEY_C_DECL
  19114. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  19115. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  19116. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  19117. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  19118. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  19119. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  19120. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  19121. #undef JSON_HEDLEY_COMPCERT_VERSION
  19122. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  19123. #undef JSON_HEDLEY_CONCAT
  19124. #undef JSON_HEDLEY_CONCAT_EX
  19125. #undef JSON_HEDLEY_CONST
  19126. #undef JSON_HEDLEY_CONST_CAST
  19127. #undef JSON_HEDLEY_CONSTEXPR
  19128. #undef JSON_HEDLEY_CPP_CAST
  19129. #undef JSON_HEDLEY_CRAY_VERSION
  19130. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  19131. #undef JSON_HEDLEY_DEPRECATED
  19132. #undef JSON_HEDLEY_DEPRECATED_FOR
  19133. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  19134. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  19135. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  19136. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  19137. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  19138. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  19139. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  19140. #undef JSON_HEDLEY_DMC_VERSION
  19141. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  19142. #undef JSON_HEDLEY_EMPTY_BASES
  19143. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  19144. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  19145. #undef JSON_HEDLEY_END_C_DECLS
  19146. #undef JSON_HEDLEY_FALL_THROUGH
  19147. #undef JSON_HEDLEY_FLAGS
  19148. #undef JSON_HEDLEY_FLAGS_CAST
  19149. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  19150. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  19151. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  19152. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  19153. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  19154. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  19155. #undef JSON_HEDLEY_GCC_HAS_WARNING
  19156. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  19157. #undef JSON_HEDLEY_GCC_VERSION
  19158. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  19159. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  19160. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  19161. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  19162. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  19163. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  19164. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  19165. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  19166. #undef JSON_HEDLEY_GNUC_VERSION
  19167. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  19168. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  19169. #undef JSON_HEDLEY_HAS_BUILTIN
  19170. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  19171. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  19172. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  19173. #undef JSON_HEDLEY_HAS_EXTENSION
  19174. #undef JSON_HEDLEY_HAS_FEATURE
  19175. #undef JSON_HEDLEY_HAS_WARNING
  19176. #undef JSON_HEDLEY_IAR_VERSION
  19177. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  19178. #undef JSON_HEDLEY_IBM_VERSION
  19179. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  19180. #undef JSON_HEDLEY_IMPORT
  19181. #undef JSON_HEDLEY_INLINE
  19182. #undef JSON_HEDLEY_INTEL_VERSION
  19183. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  19184. #undef JSON_HEDLEY_IS_CONSTANT
  19185. #undef JSON_HEDLEY_IS_CONSTEXPR_
  19186. #undef JSON_HEDLEY_LIKELY
  19187. #undef JSON_HEDLEY_MALLOC
  19188. #undef JSON_HEDLEY_MESSAGE
  19189. #undef JSON_HEDLEY_MSVC_VERSION
  19190. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  19191. #undef JSON_HEDLEY_NEVER_INLINE
  19192. #undef JSON_HEDLEY_NO_ESCAPE
  19193. #undef JSON_HEDLEY_NON_NULL
  19194. #undef JSON_HEDLEY_NO_RETURN
  19195. #undef JSON_HEDLEY_NO_THROW
  19196. #undef JSON_HEDLEY_NULL
  19197. #undef JSON_HEDLEY_PELLES_VERSION
  19198. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  19199. #undef JSON_HEDLEY_PGI_VERSION
  19200. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  19201. #undef JSON_HEDLEY_PREDICT
  19202. #undef JSON_HEDLEY_PRINTF_FORMAT
  19203. #undef JSON_HEDLEY_PRIVATE
  19204. #undef JSON_HEDLEY_PUBLIC
  19205. #undef JSON_HEDLEY_PURE
  19206. #undef JSON_HEDLEY_REINTERPRET_CAST
  19207. #undef JSON_HEDLEY_REQUIRE
  19208. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  19209. #undef JSON_HEDLEY_REQUIRE_MSG
  19210. #undef JSON_HEDLEY_RESTRICT
  19211. #undef JSON_HEDLEY_RETURNS_NON_NULL
  19212. #undef JSON_HEDLEY_SENTINEL
  19213. #undef JSON_HEDLEY_STATIC_ASSERT
  19214. #undef JSON_HEDLEY_STATIC_CAST
  19215. #undef JSON_HEDLEY_STRINGIFY
  19216. #undef JSON_HEDLEY_STRINGIFY_EX
  19217. #undef JSON_HEDLEY_SUNPRO_VERSION
  19218. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  19219. #undef JSON_HEDLEY_TINYC_VERSION
  19220. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  19221. #undef JSON_HEDLEY_TI_VERSION
  19222. #undef JSON_HEDLEY_TI_VERSION_CHECK
  19223. #undef JSON_HEDLEY_UNAVAILABLE
  19224. #undef JSON_HEDLEY_UNLIKELY
  19225. #undef JSON_HEDLEY_UNPREDICTABLE
  19226. #undef JSON_HEDLEY_UNREACHABLE
  19227. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  19228. #undef JSON_HEDLEY_VERSION
  19229. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  19230. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  19231. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  19232. #undef JSON_HEDLEY_VERSION_ENCODE
  19233. #undef JSON_HEDLEY_WARNING
  19234. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  19235. #endif // INCLUDE_NLOHMANN_JSON_HPP_