json.hpp 582 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.1.2
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>.
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. SOFTWARE.
  23. */
  24. #ifndef NLOHMANN_JSON_HPP
  25. #define NLOHMANN_JSON_HPP
  26. #define NLOHMANN_JSON_VERSION_MAJOR 3
  27. #define NLOHMANN_JSON_VERSION_MINOR 1
  28. #define NLOHMANN_JSON_VERSION_PATCH 2
  29. #include <algorithm> // all_of, find, for_each
  30. #include <cassert> // assert
  31. #include <ciso646> // and, not, or
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <functional> // hash, less
  34. #include <initializer_list> // initializer_list
  35. #include <iosfwd> // istream, ostream
  36. #include <iterator> // iterator_traits, random_access_iterator_tag
  37. #include <numeric> // accumulate
  38. #include <string> // string, stoi, to_string
  39. #include <utility> // declval, forward, move, pair, swap
  40. // #include <nlohmann/json_fwd.hpp>
  41. #ifndef NLOHMANN_JSON_FWD_HPP
  42. #define NLOHMANN_JSON_FWD_HPP
  43. #include <cstdint> // int64_t, uint64_t
  44. #include <map> // map
  45. #include <memory> // allocator
  46. #include <string> // string
  47. #include <vector> // vector
  48. /*!
  49. @brief namespace for Niels Lohmann
  50. @see https://github.com/nlohmann
  51. @since version 1.0.0
  52. */
  53. namespace nlohmann
  54. {
  55. /*!
  56. @brief default JSONSerializer template argument
  57. This serializer ignores the template arguments and uses ADL
  58. ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
  59. for serialization.
  60. */
  61. template<typename = void, typename = void>
  62. struct adl_serializer;
  63. template<template<typename U, typename V, typename... Args> class ObjectType =
  64. std::map,
  65. template<typename U, typename... Args> class ArrayType = std::vector,
  66. class StringType = std::string, class BooleanType = bool,
  67. class NumberIntegerType = std::int64_t,
  68. class NumberUnsignedType = std::uint64_t,
  69. class NumberFloatType = double,
  70. template<typename U> class AllocatorType = std::allocator,
  71. template<typename T, typename SFINAE = void> class JSONSerializer =
  72. adl_serializer>
  73. class basic_json;
  74. /*!
  75. @brief JSON Pointer
  76. A JSON pointer defines a string syntax for identifying a specific value
  77. within a JSON document. It can be used with functions `at` and
  78. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  79. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  80. @since version 2.0.0
  81. */
  82. template<typename BasicJsonType>
  83. class json_pointer;
  84. /*!
  85. @brief default JSON class
  86. This type is the default specialization of the @ref basic_json class which
  87. uses the standard template types.
  88. @since version 1.0.0
  89. */
  90. using json = basic_json<>;
  91. }
  92. #endif
  93. // #include <nlohmann/detail/macro_scope.hpp>
  94. // This file contains all internal macro definitions
  95. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  96. // exclude unsupported compilers
  97. #if defined(__clang__)
  98. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  99. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  100. #endif
  101. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  102. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
  103. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  104. #endif
  105. #endif
  106. // disable float-equal warnings on GCC/clang
  107. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  108. #pragma GCC diagnostic push
  109. #pragma GCC diagnostic ignored "-Wfloat-equal"
  110. #endif
  111. // disable documentation warnings on clang
  112. #if defined(__clang__)
  113. #pragma GCC diagnostic push
  114. #pragma GCC diagnostic ignored "-Wdocumentation"
  115. #endif
  116. // allow for portable deprecation warnings
  117. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  118. #define JSON_DEPRECATED __attribute__((deprecated))
  119. #elif defined(_MSC_VER)
  120. #define JSON_DEPRECATED __declspec(deprecated)
  121. #else
  122. #define JSON_DEPRECATED
  123. #endif
  124. // allow to disable exceptions
  125. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  126. #define JSON_THROW(exception) throw exception
  127. #define JSON_TRY try
  128. #define JSON_CATCH(exception) catch(exception)
  129. #else
  130. #define JSON_THROW(exception) std::abort()
  131. #define JSON_TRY if(true)
  132. #define JSON_CATCH(exception) if(false)
  133. #endif
  134. // override exception macros
  135. #if defined(JSON_THROW_USER)
  136. #undef JSON_THROW
  137. #define JSON_THROW JSON_THROW_USER
  138. #endif
  139. #if defined(JSON_TRY_USER)
  140. #undef JSON_TRY
  141. #define JSON_TRY JSON_TRY_USER
  142. #endif
  143. #if defined(JSON_CATCH_USER)
  144. #undef JSON_CATCH
  145. #define JSON_CATCH JSON_CATCH_USER
  146. #endif
  147. // manual branch prediction
  148. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  149. #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
  150. #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
  151. #else
  152. #define JSON_LIKELY(x) x
  153. #define JSON_UNLIKELY(x) x
  154. #endif
  155. // C++ language standard detection
  156. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  157. #define JSON_HAS_CPP_17
  158. #define JSON_HAS_CPP_14
  159. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  160. #define JSON_HAS_CPP_14
  161. #endif
  162. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  163. // may be removed in the future once the class is split.
  164. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  165. template<template<typename, typename, typename...> class ObjectType, \
  166. template<typename, typename...> class ArrayType, \
  167. class StringType, class BooleanType, class NumberIntegerType, \
  168. class NumberUnsignedType, class NumberFloatType, \
  169. template<typename> class AllocatorType, \
  170. template<typename, typename = void> class JSONSerializer>
  171. #define NLOHMANN_BASIC_JSON_TPL \
  172. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  173. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  174. AllocatorType, JSONSerializer>
  175. /*!
  176. @brief Helper to determine whether there's a key_type for T.
  177. This helper is used to tell associative containers apart from other containers
  178. such as sequence containers. For instance, `std::map` passes the test as it
  179. contains a `mapped_type`, whereas `std::vector` fails the test.
  180. @sa http://stackoverflow.com/a/7728728/266378
  181. @since version 1.0.0, overworked in version 2.0.6
  182. */
  183. #define NLOHMANN_JSON_HAS_HELPER(type) \
  184. template<typename T> struct has_##type { \
  185. private: \
  186. template<typename U, typename = typename U::type> \
  187. static int detect(U &&); \
  188. static void detect(...); \
  189. public: \
  190. static constexpr bool value = \
  191. std::is_integral<decltype(detect(std::declval<T>()))>::value; \
  192. }
  193. // #include <nlohmann/detail/meta.hpp>
  194. #include <ciso646> // not
  195. #include <cstddef> // size_t
  196. #include <limits> // numeric_limits
  197. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  198. #include <utility> // declval
  199. // #include <nlohmann/json_fwd.hpp>
  200. // #include <nlohmann/detail/macro_scope.hpp>
  201. namespace nlohmann
  202. {
  203. /*!
  204. @brief detail namespace with internal helper functions
  205. This namespace collects functions that should not be exposed,
  206. implementations of some @ref basic_json methods, and meta-programming helpers.
  207. @since version 2.1.0
  208. */
  209. namespace detail
  210. {
  211. /////////////
  212. // helpers //
  213. /////////////
  214. template<typename> struct is_basic_json : std::false_type {};
  215. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  216. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  217. // alias templates to reduce boilerplate
  218. template<bool B, typename T = void>
  219. using enable_if_t = typename std::enable_if<B, T>::type;
  220. template<typename T>
  221. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  222. // implementation of C++14 index_sequence and affiliates
  223. // source: https://stackoverflow.com/a/32223343
  224. template<std::size_t... Ints>
  225. struct index_sequence
  226. {
  227. using type = index_sequence;
  228. using value_type = std::size_t;
  229. static constexpr std::size_t size() noexcept
  230. {
  231. return sizeof...(Ints);
  232. }
  233. };
  234. template<class Sequence1, class Sequence2>
  235. struct merge_and_renumber;
  236. template<std::size_t... I1, std::size_t... I2>
  237. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  238. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  239. template<std::size_t N>
  240. struct make_index_sequence
  241. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  242. typename make_index_sequence < N - N / 2 >::type > {};
  243. template<> struct make_index_sequence<0> : index_sequence<> {};
  244. template<> struct make_index_sequence<1> : index_sequence<0> {};
  245. template<typename... Ts>
  246. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  247. /*
  248. Implementation of two C++17 constructs: conjunction, negation. This is needed
  249. to avoid evaluating all the traits in a condition
  250. For example: not std::is_same<void, T>::value and has_value_type<T>::value
  251. will not compile when T = void (on MSVC at least). Whereas
  252. conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
  253. stop evaluating if negation<...>::value == false
  254. Please note that those constructs must be used with caution, since symbols can
  255. become very long quickly (which can slow down compilation and cause MSVC
  256. internal compiler errors). Only use it when you have to (see example ahead).
  257. */
  258. template<class...> struct conjunction : std::true_type {};
  259. template<class B1> struct conjunction<B1> : B1 {};
  260. template<class B1, class... Bn>
  261. struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  262. template<class B> struct negation : std::integral_constant<bool, not B::value> {};
  263. // dispatch utility (taken from ranges-v3)
  264. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  265. template<> struct priority_tag<0> {};
  266. ////////////////////////
  267. // has_/is_ functions //
  268. ////////////////////////
  269. // source: https://stackoverflow.com/a/37193089/4116453
  270. template <typename T, typename = void>
  271. struct is_complete_type : std::false_type {};
  272. template <typename T>
  273. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  274. NLOHMANN_JSON_HAS_HELPER(mapped_type);
  275. NLOHMANN_JSON_HAS_HELPER(key_type);
  276. NLOHMANN_JSON_HAS_HELPER(value_type);
  277. NLOHMANN_JSON_HAS_HELPER(iterator);
  278. template<bool B, class RealType, class CompatibleObjectType>
  279. struct is_compatible_object_type_impl : std::false_type {};
  280. template<class RealType, class CompatibleObjectType>
  281. struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
  282. {
  283. static constexpr auto value =
  284. std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
  285. std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
  286. };
  287. template<class BasicJsonType, class CompatibleObjectType>
  288. struct is_compatible_object_type
  289. {
  290. static auto constexpr value = is_compatible_object_type_impl <
  291. conjunction<negation<std::is_same<void, CompatibleObjectType>>,
  292. has_mapped_type<CompatibleObjectType>,
  293. has_key_type<CompatibleObjectType>>::value,
  294. typename BasicJsonType::object_t, CompatibleObjectType >::value;
  295. };
  296. template<typename BasicJsonType, typename T>
  297. struct is_basic_json_nested_type
  298. {
  299. static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
  300. std::is_same<T, typename BasicJsonType::const_iterator>::value or
  301. std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
  302. std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
  303. };
  304. template<class BasicJsonType, class CompatibleArrayType>
  305. struct is_compatible_array_type
  306. {
  307. static auto constexpr value =
  308. conjunction<negation<std::is_same<void, CompatibleArrayType>>,
  309. negation<is_compatible_object_type<
  310. BasicJsonType, CompatibleArrayType>>,
  311. negation<std::is_constructible<typename BasicJsonType::string_t,
  312. CompatibleArrayType>>,
  313. negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
  314. has_value_type<CompatibleArrayType>,
  315. has_iterator<CompatibleArrayType>>::value;
  316. };
  317. template<bool, typename, typename>
  318. struct is_compatible_integer_type_impl : std::false_type {};
  319. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  320. struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
  321. {
  322. // is there an assert somewhere on overflows?
  323. using RealLimits = std::numeric_limits<RealIntegerType>;
  324. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  325. static constexpr auto value =
  326. std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
  327. CompatibleLimits::is_integer and
  328. RealLimits::is_signed == CompatibleLimits::is_signed;
  329. };
  330. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  331. struct is_compatible_integer_type
  332. {
  333. static constexpr auto value =
  334. is_compatible_integer_type_impl <
  335. std::is_integral<CompatibleNumberIntegerType>::value and
  336. not std::is_same<bool, CompatibleNumberIntegerType>::value,
  337. RealIntegerType, CompatibleNumberIntegerType > ::value;
  338. };
  339. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  340. template<typename BasicJsonType, typename T>
  341. struct has_from_json
  342. {
  343. private:
  344. // also check the return type of from_json
  345. template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
  346. std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
  347. static int detect(U&&);
  348. static void detect(...);
  349. public:
  350. static constexpr bool value = std::is_integral<decltype(
  351. detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  352. };
  353. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  354. // this overload is used for non-default-constructible user-defined-types
  355. template<typename BasicJsonType, typename T>
  356. struct has_non_default_from_json
  357. {
  358. private:
  359. template <
  360. typename U,
  361. typename = enable_if_t<std::is_same<
  362. T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
  363. static int detect(U&&);
  364. static void detect(...);
  365. public:
  366. static constexpr bool value = std::is_integral<decltype(detect(
  367. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  368. };
  369. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  370. template<typename BasicJsonType, typename T>
  371. struct has_to_json
  372. {
  373. private:
  374. template<typename U, typename = decltype(uncvref_t<U>::to_json(
  375. std::declval<BasicJsonType&>(), std::declval<T>()))>
  376. static int detect(U&&);
  377. static void detect(...);
  378. public:
  379. static constexpr bool value = std::is_integral<decltype(detect(
  380. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  381. };
  382. template <typename BasicJsonType, typename CompatibleCompleteType>
  383. struct is_compatible_complete_type
  384. {
  385. static constexpr bool value =
  386. not std::is_base_of<std::istream, CompatibleCompleteType>::value and
  387. not is_basic_json<CompatibleCompleteType>::value and
  388. not is_basic_json_nested_type<BasicJsonType, CompatibleCompleteType>::value and
  389. has_to_json<BasicJsonType, CompatibleCompleteType>::value;
  390. };
  391. template <typename BasicJsonType, typename CompatibleType>
  392. struct is_compatible_type
  393. : conjunction<is_complete_type<CompatibleType>,
  394. is_compatible_complete_type<BasicJsonType, CompatibleType>>
  395. {
  396. };
  397. // taken from ranges-v3
  398. template<typename T>
  399. struct static_const
  400. {
  401. static constexpr T value{};
  402. };
  403. template<typename T>
  404. constexpr T static_const<T>::value;
  405. }
  406. }
  407. // #include <nlohmann/detail/exceptions.hpp>
  408. #include <exception> // exception
  409. #include <stdexcept> // runtime_error
  410. #include <string> // to_string
  411. namespace nlohmann
  412. {
  413. namespace detail
  414. {
  415. ////////////////
  416. // exceptions //
  417. ////////////////
  418. /*!
  419. @brief general exception of the @ref basic_json class
  420. This class is an extension of `std::exception` objects with a member @a id for
  421. exception ids. It is used as the base class for all exceptions thrown by the
  422. @ref basic_json class. This class can hence be used as "wildcard" to catch
  423. exceptions.
  424. Subclasses:
  425. - @ref parse_error for exceptions indicating a parse error
  426. - @ref invalid_iterator for exceptions indicating errors with iterators
  427. - @ref type_error for exceptions indicating executing a member function with
  428. a wrong type
  429. - @ref out_of_range for exceptions indicating access out of the defined range
  430. - @ref other_error for exceptions indicating other library errors
  431. @internal
  432. @note To have nothrow-copy-constructible exceptions, we internally use
  433. `std::runtime_error` which can cope with arbitrary-length error messages.
  434. Intermediate strings are built with static functions and then passed to
  435. the actual constructor.
  436. @endinternal
  437. @liveexample{The following code shows how arbitrary library exceptions can be
  438. caught.,exception}
  439. @since version 3.0.0
  440. */
  441. class exception : public std::exception
  442. {
  443. public:
  444. /// returns the explanatory string
  445. const char* what() const noexcept override
  446. {
  447. return m.what();
  448. }
  449. /// the id of the exception
  450. const int id;
  451. protected:
  452. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  453. static std::string name(const std::string& ename, int id_)
  454. {
  455. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  456. }
  457. private:
  458. /// an exception object as storage for error messages
  459. std::runtime_error m;
  460. };
  461. /*!
  462. @brief exception indicating a parse error
  463. This exception is thrown by the library when a parse error occurs. Parse errors
  464. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  465. as when using JSON Patch.
  466. Member @a byte holds the byte index of the last read character in the input
  467. file.
  468. Exceptions have ids 1xx.
  469. name / id | example message | description
  470. ------------------------------ | --------------- | -------------------------
  471. 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.
  472. 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.
  473. 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.
  474. 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.
  475. 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.
  476. 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`.
  477. 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.
  478. 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.
  479. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  480. 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.
  481. 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.
  482. 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.
  483. @note For an input with n bytes, 1 is the index of the first character and n+1
  484. is the index of the terminating null byte or the end of file. This also
  485. holds true when reading a byte vector (CBOR or MessagePack).
  486. @liveexample{The following code shows how a `parse_error` exception can be
  487. caught.,parse_error}
  488. @sa @ref exception for the base class of the library exceptions
  489. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  490. @sa @ref type_error for exceptions indicating executing a member function with
  491. a wrong type
  492. @sa @ref out_of_range for exceptions indicating access out of the defined range
  493. @sa @ref other_error for exceptions indicating other library errors
  494. @since version 3.0.0
  495. */
  496. class parse_error : public exception
  497. {
  498. public:
  499. /*!
  500. @brief create a parse error exception
  501. @param[in] id_ the id of the exception
  502. @param[in] byte_ the byte index where the error occurred (or 0 if the
  503. position cannot be determined)
  504. @param[in] what_arg the explanatory string
  505. @return parse_error object
  506. */
  507. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  508. {
  509. std::string w = exception::name("parse_error", id_) + "parse error" +
  510. (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
  511. ": " + what_arg;
  512. return parse_error(id_, byte_, w.c_str());
  513. }
  514. /*!
  515. @brief byte index of the parse error
  516. The byte index of the last read character in the input file.
  517. @note For an input with n bytes, 1 is the index of the first character and
  518. n+1 is the index of the terminating null byte or the end of file.
  519. This also holds true when reading a byte vector (CBOR or MessagePack).
  520. */
  521. const std::size_t byte;
  522. private:
  523. parse_error(int id_, std::size_t byte_, const char* what_arg)
  524. : exception(id_, what_arg), byte(byte_) {}
  525. };
  526. /*!
  527. @brief exception indicating errors with iterators
  528. This exception is thrown if iterators passed to a library function do not match
  529. the expected semantics.
  530. Exceptions have ids 2xx.
  531. name / id | example message | description
  532. ----------------------------------- | --------------- | -------------------------
  533. 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.
  534. 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.
  535. 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.
  536. 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.
  537. 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.
  538. 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.
  539. 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.
  540. 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.
  541. 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.
  542. 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.
  543. 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.
  544. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  545. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  546. 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().
  547. @liveexample{The following code shows how an `invalid_iterator` exception can be
  548. caught.,invalid_iterator}
  549. @sa @ref exception for the base class of the library exceptions
  550. @sa @ref parse_error for exceptions indicating a parse error
  551. @sa @ref type_error for exceptions indicating executing a member function with
  552. a wrong type
  553. @sa @ref out_of_range for exceptions indicating access out of the defined range
  554. @sa @ref other_error for exceptions indicating other library errors
  555. @since version 3.0.0
  556. */
  557. class invalid_iterator : public exception
  558. {
  559. public:
  560. static invalid_iterator create(int id_, const std::string& what_arg)
  561. {
  562. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  563. return invalid_iterator(id_, w.c_str());
  564. }
  565. private:
  566. invalid_iterator(int id_, const char* what_arg)
  567. : exception(id_, what_arg) {}
  568. };
  569. /*!
  570. @brief exception indicating executing a member function with a wrong type
  571. This exception is thrown in case of a type error; that is, a library function is
  572. executed on a JSON value whose type does not match the expected semantics.
  573. Exceptions have ids 3xx.
  574. name / id | example message | description
  575. ----------------------------- | --------------- | -------------------------
  576. 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.
  577. 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.
  578. 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&.
  579. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  580. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  581. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  582. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  583. 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.
  584. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  585. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  586. 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.
  587. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  588. 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.
  589. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  590. 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.
  591. 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. |
  592. @liveexample{The following code shows how a `type_error` exception can be
  593. caught.,type_error}
  594. @sa @ref exception for the base class of the library exceptions
  595. @sa @ref parse_error for exceptions indicating a parse error
  596. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  597. @sa @ref out_of_range for exceptions indicating access out of the defined range
  598. @sa @ref other_error for exceptions indicating other library errors
  599. @since version 3.0.0
  600. */
  601. class type_error : public exception
  602. {
  603. public:
  604. static type_error create(int id_, const std::string& what_arg)
  605. {
  606. std::string w = exception::name("type_error", id_) + what_arg;
  607. return type_error(id_, w.c_str());
  608. }
  609. private:
  610. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  611. };
  612. /*!
  613. @brief exception indicating access out of the defined range
  614. This exception is thrown in case a library function is called on an input
  615. parameter that exceeds the expected range, for instance in case of array
  616. indices or nonexisting object keys.
  617. Exceptions have ids 4xx.
  618. name / id | example message | description
  619. ------------------------------- | --------------- | -------------------------
  620. 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.
  621. 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.
  622. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  623. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  624. 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.
  625. 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.
  626. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON only supports integers numbers up to 9223372036854775807. |
  627. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  628. @liveexample{The following code shows how an `out_of_range` exception can be
  629. caught.,out_of_range}
  630. @sa @ref exception for the base class of the library exceptions
  631. @sa @ref parse_error for exceptions indicating a parse error
  632. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  633. @sa @ref type_error for exceptions indicating executing a member function with
  634. a wrong type
  635. @sa @ref other_error for exceptions indicating other library errors
  636. @since version 3.0.0
  637. */
  638. class out_of_range : public exception
  639. {
  640. public:
  641. static out_of_range create(int id_, const std::string& what_arg)
  642. {
  643. std::string w = exception::name("out_of_range", id_) + what_arg;
  644. return out_of_range(id_, w.c_str());
  645. }
  646. private:
  647. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  648. };
  649. /*!
  650. @brief exception indicating other library errors
  651. This exception is thrown in case of errors that cannot be classified with the
  652. other exception types.
  653. Exceptions have ids 5xx.
  654. name / id | example message | description
  655. ------------------------------ | --------------- | -------------------------
  656. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  657. @sa @ref exception for the base class of the library exceptions
  658. @sa @ref parse_error for exceptions indicating a parse error
  659. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  660. @sa @ref type_error for exceptions indicating executing a member function with
  661. a wrong type
  662. @sa @ref out_of_range for exceptions indicating access out of the defined range
  663. @liveexample{The following code shows how an `other_error` exception can be
  664. caught.,other_error}
  665. @since version 3.0.0
  666. */
  667. class other_error : public exception
  668. {
  669. public:
  670. static other_error create(int id_, const std::string& what_arg)
  671. {
  672. std::string w = exception::name("other_error", id_) + what_arg;
  673. return other_error(id_, w.c_str());
  674. }
  675. private:
  676. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  677. };
  678. }
  679. }
  680. // #include <nlohmann/detail/value_t.hpp>
  681. #include <array> // array
  682. #include <ciso646> // and
  683. #include <cstddef> // size_t
  684. #include <cstdint> // uint8_t
  685. namespace nlohmann
  686. {
  687. namespace detail
  688. {
  689. ///////////////////////////
  690. // JSON type enumeration //
  691. ///////////////////////////
  692. /*!
  693. @brief the JSON type enumeration
  694. This enumeration collects the different JSON types. It is internally used to
  695. distinguish the stored values, and the functions @ref basic_json::is_null(),
  696. @ref basic_json::is_object(), @ref basic_json::is_array(),
  697. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  698. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  699. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  700. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  701. @ref basic_json::is_structured() rely on it.
  702. @note There are three enumeration entries (number_integer, number_unsigned, and
  703. number_float), because the library distinguishes these three types for numbers:
  704. @ref basic_json::number_unsigned_t is used for unsigned integers,
  705. @ref basic_json::number_integer_t is used for signed integers, and
  706. @ref basic_json::number_float_t is used for floating-point numbers or to
  707. approximate integers which do not fit in the limits of their respective type.
  708. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  709. value with the default value for a given type
  710. @since version 1.0.0
  711. */
  712. enum class value_t : std::uint8_t
  713. {
  714. null, ///< null value
  715. object, ///< object (unordered set of name/value pairs)
  716. array, ///< array (ordered collection of values)
  717. string, ///< string value
  718. boolean, ///< boolean value
  719. number_integer, ///< number value (signed integer)
  720. number_unsigned, ///< number value (unsigned integer)
  721. number_float, ///< number value (floating-point)
  722. discarded ///< discarded by the the parser callback function
  723. };
  724. /*!
  725. @brief comparison operator for JSON types
  726. Returns an ordering that is similar to Python:
  727. - order: null < boolean < number < object < array < string
  728. - furthermore, each type is not smaller than itself
  729. - discarded values are not comparable
  730. @since version 1.0.0
  731. */
  732. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  733. {
  734. static constexpr std::array<std::uint8_t, 8> order = {{
  735. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  736. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  737. }
  738. };
  739. const auto l_index = static_cast<std::size_t>(lhs);
  740. const auto r_index = static_cast<std::size_t>(rhs);
  741. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  742. }
  743. }
  744. }
  745. // #include <nlohmann/detail/conversions/from_json.hpp>
  746. #include <algorithm> // transform
  747. #include <array> // array
  748. #include <ciso646> // and, not
  749. #include <forward_list> // forward_list
  750. #include <iterator> // inserter, front_inserter, end
  751. #include <string> // string
  752. #include <tuple> // tuple, make_tuple
  753. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  754. #include <utility> // pair, declval
  755. #include <valarray> // valarray
  756. // #include <nlohmann/detail/exceptions.hpp>
  757. // #include <nlohmann/detail/macro_scope.hpp>
  758. // #include <nlohmann/detail/meta.hpp>
  759. // #include <nlohmann/detail/value_t.hpp>
  760. namespace nlohmann
  761. {
  762. namespace detail
  763. {
  764. // overloads for basic_json template parameters
  765. template<typename BasicJsonType, typename ArithmeticType,
  766. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  767. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  768. int> = 0>
  769. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  770. {
  771. switch (static_cast<value_t>(j))
  772. {
  773. case value_t::number_unsigned:
  774. {
  775. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  776. break;
  777. }
  778. case value_t::number_integer:
  779. {
  780. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  781. break;
  782. }
  783. case value_t::number_float:
  784. {
  785. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  786. break;
  787. }
  788. default:
  789. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  790. }
  791. }
  792. template<typename BasicJsonType>
  793. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  794. {
  795. if (JSON_UNLIKELY(not j.is_boolean()))
  796. {
  797. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  798. }
  799. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  800. }
  801. template<typename BasicJsonType>
  802. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  803. {
  804. if (JSON_UNLIKELY(not j.is_string()))
  805. {
  806. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  807. }
  808. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  809. }
  810. template<typename BasicJsonType>
  811. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  812. {
  813. get_arithmetic_value(j, val);
  814. }
  815. template<typename BasicJsonType>
  816. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  817. {
  818. get_arithmetic_value(j, val);
  819. }
  820. template<typename BasicJsonType>
  821. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  822. {
  823. get_arithmetic_value(j, val);
  824. }
  825. template<typename BasicJsonType, typename EnumType,
  826. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  827. void from_json(const BasicJsonType& j, EnumType& e)
  828. {
  829. typename std::underlying_type<EnumType>::type val;
  830. get_arithmetic_value(j, val);
  831. e = static_cast<EnumType>(val);
  832. }
  833. template<typename BasicJsonType>
  834. void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
  835. {
  836. if (JSON_UNLIKELY(not j.is_array()))
  837. {
  838. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  839. }
  840. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  841. }
  842. // forward_list doesn't have an insert method
  843. template<typename BasicJsonType, typename T, typename Allocator,
  844. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  845. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  846. {
  847. if (JSON_UNLIKELY(not j.is_array()))
  848. {
  849. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  850. }
  851. std::transform(j.rbegin(), j.rend(),
  852. std::front_inserter(l), [](const BasicJsonType & i)
  853. {
  854. return i.template get<T>();
  855. });
  856. }
  857. // valarray doesn't have an insert method
  858. template<typename BasicJsonType, typename T,
  859. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  860. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  861. {
  862. if (JSON_UNLIKELY(not j.is_array()))
  863. {
  864. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  865. }
  866. l.resize(j.size());
  867. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  868. }
  869. template<typename BasicJsonType, typename CompatibleArrayType>
  870. void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
  871. {
  872. using std::end;
  873. std::transform(j.begin(), j.end(),
  874. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  875. {
  876. // get<BasicJsonType>() returns *this, this won't call a from_json
  877. // method when value_type is BasicJsonType
  878. return i.template get<typename CompatibleArrayType::value_type>();
  879. });
  880. }
  881. template<typename BasicJsonType, typename CompatibleArrayType>
  882. auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
  883. -> decltype(
  884. arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
  885. void())
  886. {
  887. using std::end;
  888. arr.reserve(j.size());
  889. std::transform(j.begin(), j.end(),
  890. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  891. {
  892. // get<BasicJsonType>() returns *this, this won't call a from_json
  893. // method when value_type is BasicJsonType
  894. return i.template get<typename CompatibleArrayType::value_type>();
  895. });
  896. }
  897. template<typename BasicJsonType, typename T, std::size_t N>
  898. void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
  899. {
  900. for (std::size_t i = 0; i < N; ++i)
  901. {
  902. arr[i] = j.at(i).template get<T>();
  903. }
  904. }
  905. template <
  906. typename BasicJsonType, typename CompatibleArrayType,
  907. enable_if_t <
  908. is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
  909. not std::is_same<typename BasicJsonType::array_t,
  910. CompatibleArrayType>::value and
  911. std::is_constructible <
  912. BasicJsonType, typename CompatibleArrayType::value_type >::value,
  913. int > = 0 >
  914. void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
  915. {
  916. if (JSON_UNLIKELY(not j.is_array()))
  917. {
  918. JSON_THROW(type_error::create(302, "type must be array, but is " +
  919. std::string(j.type_name())));
  920. }
  921. from_json_array_impl(j, arr, priority_tag<2> {});
  922. }
  923. template<typename BasicJsonType, typename CompatibleObjectType,
  924. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  925. void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
  926. {
  927. if (JSON_UNLIKELY(not j.is_object()))
  928. {
  929. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  930. }
  931. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  932. using value_type = typename CompatibleObjectType::value_type;
  933. std::transform(
  934. inner_object->begin(), inner_object->end(),
  935. std::inserter(obj, obj.begin()),
  936. [](typename BasicJsonType::object_t::value_type const & p)
  937. {
  938. return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
  939. });
  940. }
  941. // overload for arithmetic types, not chosen for basic_json template arguments
  942. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  943. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  944. // an arithmetic type?
  945. template<typename BasicJsonType, typename ArithmeticType,
  946. enable_if_t <
  947. std::is_arithmetic<ArithmeticType>::value and
  948. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  949. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  950. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  951. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  952. int> = 0>
  953. void from_json(const BasicJsonType& j, ArithmeticType& val)
  954. {
  955. switch (static_cast<value_t>(j))
  956. {
  957. case value_t::number_unsigned:
  958. {
  959. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  960. break;
  961. }
  962. case value_t::number_integer:
  963. {
  964. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  965. break;
  966. }
  967. case value_t::number_float:
  968. {
  969. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  970. break;
  971. }
  972. case value_t::boolean:
  973. {
  974. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  975. break;
  976. }
  977. default:
  978. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  979. }
  980. }
  981. template<typename BasicJsonType, typename A1, typename A2>
  982. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  983. {
  984. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  985. }
  986. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  987. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
  988. {
  989. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  990. }
  991. template<typename BasicJsonType, typename... Args>
  992. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  993. {
  994. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  995. }
  996. struct from_json_fn
  997. {
  998. private:
  999. template<typename BasicJsonType, typename T>
  1000. auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
  1001. noexcept(noexcept(from_json(j, val)))
  1002. -> decltype(from_json(j, val), void())
  1003. {
  1004. return from_json(j, val);
  1005. }
  1006. template<typename BasicJsonType, typename T>
  1007. void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1008. {
  1009. static_assert(sizeof(BasicJsonType) == 0,
  1010. "could not find from_json() method in T's namespace");
  1011. #ifdef _MSC_VER
  1012. // MSVC does not show a stacktrace for the above assert
  1013. using decayed = uncvref_t<T>;
  1014. static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
  1015. "forcing MSVC stacktrace to show which T we're talking about.");
  1016. #endif
  1017. }
  1018. public:
  1019. template<typename BasicJsonType, typename T>
  1020. void operator()(const BasicJsonType& j, T& val) const
  1021. noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
  1022. {
  1023. return call(j, val, priority_tag<1> {});
  1024. }
  1025. };
  1026. }
  1027. /// namespace to hold default `from_json` function
  1028. /// to see why this is required:
  1029. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  1030. namespace
  1031. {
  1032. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  1033. }
  1034. }
  1035. // #include <nlohmann/detail/conversions/to_json.hpp>
  1036. #include <ciso646> // or, and, not
  1037. #include <iterator> // begin, end
  1038. #include <tuple> // tuple, get
  1039. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  1040. #include <utility> // move, forward, declval, pair
  1041. #include <valarray> // valarray
  1042. #include <vector> // vector
  1043. // #include <nlohmann/detail/meta.hpp>
  1044. // #include <nlohmann/detail/value_t.hpp>
  1045. namespace nlohmann
  1046. {
  1047. namespace detail
  1048. {
  1049. //////////////////
  1050. // constructors //
  1051. //////////////////
  1052. template<value_t> struct external_constructor;
  1053. template<>
  1054. struct external_constructor<value_t::boolean>
  1055. {
  1056. template<typename BasicJsonType>
  1057. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  1058. {
  1059. j.m_type = value_t::boolean;
  1060. j.m_value = b;
  1061. j.assert_invariant();
  1062. }
  1063. };
  1064. template<>
  1065. struct external_constructor<value_t::string>
  1066. {
  1067. template<typename BasicJsonType>
  1068. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  1069. {
  1070. j.m_type = value_t::string;
  1071. j.m_value = s;
  1072. j.assert_invariant();
  1073. }
  1074. template<typename BasicJsonType>
  1075. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1076. {
  1077. j.m_type = value_t::string;
  1078. j.m_value = std::move(s);
  1079. j.assert_invariant();
  1080. }
  1081. };
  1082. template<>
  1083. struct external_constructor<value_t::number_float>
  1084. {
  1085. template<typename BasicJsonType>
  1086. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  1087. {
  1088. j.m_type = value_t::number_float;
  1089. j.m_value = val;
  1090. j.assert_invariant();
  1091. }
  1092. };
  1093. template<>
  1094. struct external_constructor<value_t::number_unsigned>
  1095. {
  1096. template<typename BasicJsonType>
  1097. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  1098. {
  1099. j.m_type = value_t::number_unsigned;
  1100. j.m_value = val;
  1101. j.assert_invariant();
  1102. }
  1103. };
  1104. template<>
  1105. struct external_constructor<value_t::number_integer>
  1106. {
  1107. template<typename BasicJsonType>
  1108. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  1109. {
  1110. j.m_type = value_t::number_integer;
  1111. j.m_value = val;
  1112. j.assert_invariant();
  1113. }
  1114. };
  1115. template<>
  1116. struct external_constructor<value_t::array>
  1117. {
  1118. template<typename BasicJsonType>
  1119. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  1120. {
  1121. j.m_type = value_t::array;
  1122. j.m_value = arr;
  1123. j.assert_invariant();
  1124. }
  1125. template<typename BasicJsonType>
  1126. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1127. {
  1128. j.m_type = value_t::array;
  1129. j.m_value = std::move(arr);
  1130. j.assert_invariant();
  1131. }
  1132. template<typename BasicJsonType, typename CompatibleArrayType,
  1133. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  1134. int> = 0>
  1135. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  1136. {
  1137. using std::begin;
  1138. using std::end;
  1139. j.m_type = value_t::array;
  1140. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  1141. j.assert_invariant();
  1142. }
  1143. template<typename BasicJsonType>
  1144. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  1145. {
  1146. j.m_type = value_t::array;
  1147. j.m_value = value_t::array;
  1148. j.m_value.array->reserve(arr.size());
  1149. for (const bool x : arr)
  1150. {
  1151. j.m_value.array->push_back(x);
  1152. }
  1153. j.assert_invariant();
  1154. }
  1155. template<typename BasicJsonType, typename T,
  1156. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1157. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  1158. {
  1159. j.m_type = value_t::array;
  1160. j.m_value = value_t::array;
  1161. j.m_value.array->resize(arr.size());
  1162. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  1163. j.assert_invariant();
  1164. }
  1165. };
  1166. template<>
  1167. struct external_constructor<value_t::object>
  1168. {
  1169. template<typename BasicJsonType>
  1170. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  1171. {
  1172. j.m_type = value_t::object;
  1173. j.m_value = obj;
  1174. j.assert_invariant();
  1175. }
  1176. template<typename BasicJsonType>
  1177. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1178. {
  1179. j.m_type = value_t::object;
  1180. j.m_value = std::move(obj);
  1181. j.assert_invariant();
  1182. }
  1183. template<typename BasicJsonType, typename CompatibleObjectType,
  1184. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  1185. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  1186. {
  1187. using std::begin;
  1188. using std::end;
  1189. j.m_type = value_t::object;
  1190. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  1191. j.assert_invariant();
  1192. }
  1193. };
  1194. /////////////
  1195. // to_json //
  1196. /////////////
  1197. template<typename BasicJsonType, typename T,
  1198. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  1199. void to_json(BasicJsonType& j, T b) noexcept
  1200. {
  1201. external_constructor<value_t::boolean>::construct(j, b);
  1202. }
  1203. template<typename BasicJsonType, typename CompatibleString,
  1204. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  1205. void to_json(BasicJsonType& j, const CompatibleString& s)
  1206. {
  1207. external_constructor<value_t::string>::construct(j, s);
  1208. }
  1209. template<typename BasicJsonType>
  1210. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1211. {
  1212. external_constructor<value_t::string>::construct(j, std::move(s));
  1213. }
  1214. template<typename BasicJsonType, typename FloatType,
  1215. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  1216. void to_json(BasicJsonType& j, FloatType val) noexcept
  1217. {
  1218. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  1219. }
  1220. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  1221. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  1222. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  1223. {
  1224. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  1225. }
  1226. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  1227. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  1228. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  1229. {
  1230. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  1231. }
  1232. template<typename BasicJsonType, typename EnumType,
  1233. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1234. void to_json(BasicJsonType& j, EnumType e) noexcept
  1235. {
  1236. using underlying_type = typename std::underlying_type<EnumType>::type;
  1237. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  1238. }
  1239. template<typename BasicJsonType>
  1240. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  1241. {
  1242. external_constructor<value_t::array>::construct(j, e);
  1243. }
  1244. template<typename BasicJsonType, typename CompatibleArrayType,
  1245. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
  1246. std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
  1247. int> = 0>
  1248. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  1249. {
  1250. external_constructor<value_t::array>::construct(j, arr);
  1251. }
  1252. template<typename BasicJsonType, typename T,
  1253. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1254. void to_json(BasicJsonType& j, std::valarray<T> arr)
  1255. {
  1256. external_constructor<value_t::array>::construct(j, std::move(arr));
  1257. }
  1258. template<typename BasicJsonType>
  1259. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1260. {
  1261. external_constructor<value_t::array>::construct(j, std::move(arr));
  1262. }
  1263. template<typename BasicJsonType, typename CompatibleObjectType,
  1264. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  1265. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  1266. {
  1267. external_constructor<value_t::object>::construct(j, obj);
  1268. }
  1269. template<typename BasicJsonType>
  1270. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1271. {
  1272. external_constructor<value_t::object>::construct(j, std::move(obj));
  1273. }
  1274. template<typename BasicJsonType, typename T, std::size_t N,
  1275. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
  1276. void to_json(BasicJsonType& j, T (&arr)[N])
  1277. {
  1278. external_constructor<value_t::array>::construct(j, arr);
  1279. }
  1280. template<typename BasicJsonType, typename... Args>
  1281. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  1282. {
  1283. j = {p.first, p.second};
  1284. }
  1285. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1286. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
  1287. {
  1288. j = {std::get<Idx>(t)...};
  1289. }
  1290. template<typename BasicJsonType, typename... Args>
  1291. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  1292. {
  1293. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1294. }
  1295. struct to_json_fn
  1296. {
  1297. private:
  1298. template<typename BasicJsonType, typename T>
  1299. auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1300. -> decltype(to_json(j, std::forward<T>(val)), void())
  1301. {
  1302. return to_json(j, std::forward<T>(val));
  1303. }
  1304. template<typename BasicJsonType, typename T>
  1305. void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1306. {
  1307. static_assert(sizeof(BasicJsonType) == 0,
  1308. "could not find to_json() method in T's namespace");
  1309. #ifdef _MSC_VER
  1310. // MSVC does not show a stacktrace for the above assert
  1311. using decayed = uncvref_t<T>;
  1312. static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
  1313. "forcing MSVC stacktrace to show which T we're talking about.");
  1314. #endif
  1315. }
  1316. public:
  1317. template<typename BasicJsonType, typename T>
  1318. void operator()(BasicJsonType& j, T&& val) const
  1319. noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
  1320. {
  1321. return call(j, std::forward<T>(val), priority_tag<1> {});
  1322. }
  1323. };
  1324. }
  1325. /// namespace to hold default `to_json` function
  1326. namespace
  1327. {
  1328. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  1329. }
  1330. }
  1331. // #include <nlohmann/detail/input/input_adapters.hpp>
  1332. #include <algorithm> // min
  1333. #include <array> // array
  1334. #include <cassert> // assert
  1335. #include <cstddef> // size_t
  1336. #include <cstring> // strlen
  1337. #include <ios> // streamsize, streamoff, streampos
  1338. #include <istream> // istream
  1339. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  1340. #include <memory> // shared_ptr, make_shared, addressof
  1341. #include <numeric> // accumulate
  1342. #include <string> // string, char_traits
  1343. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  1344. #include <utility> // pair, declval
  1345. // #include <nlohmann/detail/macro_scope.hpp>
  1346. namespace nlohmann
  1347. {
  1348. namespace detail
  1349. {
  1350. ////////////////////
  1351. // input adapters //
  1352. ////////////////////
  1353. /*!
  1354. @brief abstract input adapter interface
  1355. Produces a stream of std::char_traits<char>::int_type characters from a
  1356. std::istream, a buffer, or some other input type. Accepts the return of exactly
  1357. one non-EOF character for future input. The int_type characters returned
  1358. consist of all valid char values as positive values (typically unsigned char),
  1359. plus an EOF value outside that range, specified by the value of the function
  1360. std::char_traits<char>::eof(). This value is typically -1, but could be any
  1361. arbitrary value which is not a valid char value.
  1362. */
  1363. struct input_adapter_protocol
  1364. {
  1365. /// get a character [0,255] or std::char_traits<char>::eof().
  1366. virtual std::char_traits<char>::int_type get_character() = 0;
  1367. /// restore the last non-eof() character to input
  1368. virtual void unget_character() = 0;
  1369. virtual ~input_adapter_protocol() = default;
  1370. };
  1371. /// a type to simplify interfaces
  1372. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1373. /*!
  1374. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  1375. beginning of input. Does not support changing the underlying std::streambuf
  1376. in mid-input. Maintains underlying std::istream and std::streambuf to support
  1377. subsequent use of standard std::istream operations to process any input
  1378. characters following those used in parsing the JSON input. Clears the
  1379. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  1380. subsequent call for input from the std::istream.
  1381. */
  1382. class input_stream_adapter : public input_adapter_protocol
  1383. {
  1384. public:
  1385. ~input_stream_adapter() override
  1386. {
  1387. // clear stream flags; we use underlying streambuf I/O, do not
  1388. // maintain ifstream flags
  1389. is.clear();
  1390. }
  1391. explicit input_stream_adapter(std::istream& i)
  1392. : is(i), sb(*i.rdbuf())
  1393. {
  1394. // skip byte order mark
  1395. std::char_traits<char>::int_type c;
  1396. if ((c = get_character()) == 0xEF)
  1397. {
  1398. if ((c = get_character()) == 0xBB)
  1399. {
  1400. if ((c = get_character()) == 0xBF)
  1401. {
  1402. return; // Ignore BOM
  1403. }
  1404. else if (c != std::char_traits<char>::eof())
  1405. {
  1406. is.unget();
  1407. }
  1408. is.putback('\xBB');
  1409. }
  1410. else if (c != std::char_traits<char>::eof())
  1411. {
  1412. is.unget();
  1413. }
  1414. is.putback('\xEF');
  1415. }
  1416. else if (c != std::char_traits<char>::eof())
  1417. {
  1418. is.unget(); // no byte order mark; process as usual
  1419. }
  1420. }
  1421. // delete because of pointer members
  1422. input_stream_adapter(const input_stream_adapter&) = delete;
  1423. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  1424. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  1425. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  1426. // end up as the same value, eg. 0xFFFFFFFF.
  1427. std::char_traits<char>::int_type get_character() override
  1428. {
  1429. return sb.sbumpc();
  1430. }
  1431. void unget_character() override
  1432. {
  1433. sb.sungetc(); // is.unget() avoided for performance
  1434. }
  1435. private:
  1436. /// the associated input stream
  1437. std::istream& is;
  1438. std::streambuf& sb;
  1439. };
  1440. /// input adapter for buffer input
  1441. class input_buffer_adapter : public input_adapter_protocol
  1442. {
  1443. public:
  1444. input_buffer_adapter(const char* b, const std::size_t l)
  1445. : cursor(b), limit(b + l), start(b)
  1446. {
  1447. // skip byte order mark
  1448. if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
  1449. {
  1450. cursor += 3;
  1451. }
  1452. }
  1453. // delete because of pointer members
  1454. input_buffer_adapter(const input_buffer_adapter&) = delete;
  1455. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  1456. std::char_traits<char>::int_type get_character() noexcept override
  1457. {
  1458. if (JSON_LIKELY(cursor < limit))
  1459. {
  1460. return std::char_traits<char>::to_int_type(*(cursor++));
  1461. }
  1462. return std::char_traits<char>::eof();
  1463. }
  1464. void unget_character() noexcept override
  1465. {
  1466. if (JSON_LIKELY(cursor > start))
  1467. {
  1468. --cursor;
  1469. }
  1470. }
  1471. private:
  1472. /// pointer to the current character
  1473. const char* cursor;
  1474. /// pointer past the last character
  1475. const char* limit;
  1476. /// pointer to the first character
  1477. const char* start;
  1478. };
  1479. class input_adapter
  1480. {
  1481. public:
  1482. // native support
  1483. /// input adapter for input stream
  1484. input_adapter(std::istream& i)
  1485. : ia(std::make_shared<input_stream_adapter>(i)) {}
  1486. /// input adapter for input stream
  1487. input_adapter(std::istream&& i)
  1488. : ia(std::make_shared<input_stream_adapter>(i)) {}
  1489. /// input adapter for buffer
  1490. template<typename CharT,
  1491. typename std::enable_if<
  1492. std::is_pointer<CharT>::value and
  1493. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  1494. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1495. int>::type = 0>
  1496. input_adapter(CharT b, std::size_t l)
  1497. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  1498. // derived support
  1499. /// input adapter for string literal
  1500. template<typename CharT,
  1501. typename std::enable_if<
  1502. std::is_pointer<CharT>::value and
  1503. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  1504. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1505. int>::type = 0>
  1506. input_adapter(CharT b)
  1507. : input_adapter(reinterpret_cast<const char*>(b),
  1508. std::strlen(reinterpret_cast<const char*>(b))) {}
  1509. /// input adapter for iterator range with contiguous storage
  1510. template<class IteratorType,
  1511. typename std::enable_if<
  1512. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  1513. int>::type = 0>
  1514. input_adapter(IteratorType first, IteratorType last)
  1515. {
  1516. // assertion to check that the iterator range is indeed contiguous,
  1517. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  1518. assert(std::accumulate(
  1519. first, last, std::pair<bool, int>(true, 0),
  1520. [&first](std::pair<bool, int> res, decltype(*first) val)
  1521. {
  1522. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  1523. return res;
  1524. }).first);
  1525. // assertion to check that each element is 1 byte long
  1526. static_assert(
  1527. sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  1528. "each element in the iterator range must have the size of 1 byte");
  1529. const auto len = static_cast<size_t>(std::distance(first, last));
  1530. if (JSON_LIKELY(len > 0))
  1531. {
  1532. // there is at least one element: use the address of first
  1533. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  1534. }
  1535. else
  1536. {
  1537. // the address of first cannot be used: use nullptr
  1538. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  1539. }
  1540. }
  1541. /// input adapter for array
  1542. template<class T, std::size_t N>
  1543. input_adapter(T (&array)[N])
  1544. : input_adapter(std::begin(array), std::end(array)) {}
  1545. /// input adapter for contiguous container
  1546. template<class ContiguousContainer, typename
  1547. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  1548. std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  1549. int>::type = 0>
  1550. input_adapter(const ContiguousContainer& c)
  1551. : input_adapter(std::begin(c), std::end(c)) {}
  1552. operator input_adapter_t()
  1553. {
  1554. return ia;
  1555. }
  1556. private:
  1557. /// the actual adapter
  1558. input_adapter_t ia = nullptr;
  1559. };
  1560. }
  1561. }
  1562. // #include <nlohmann/detail/input/lexer.hpp>
  1563. #include <clocale> // localeconv
  1564. #include <cstddef> // size_t
  1565. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  1566. #include <initializer_list> // initializer_list
  1567. #include <ios> // hex, uppercase
  1568. #include <iomanip> // setw, setfill
  1569. #include <sstream> // stringstream
  1570. #include <string> // char_traits, string
  1571. #include <vector> // vector
  1572. // #include <nlohmann/detail/macro_scope.hpp>
  1573. // #include <nlohmann/detail/input/input_adapters.hpp>
  1574. namespace nlohmann
  1575. {
  1576. namespace detail
  1577. {
  1578. ///////////
  1579. // lexer //
  1580. ///////////
  1581. /*!
  1582. @brief lexical analysis
  1583. This class organizes the lexical analysis during JSON deserialization.
  1584. */
  1585. template<typename BasicJsonType>
  1586. class lexer
  1587. {
  1588. using number_integer_t = typename BasicJsonType::number_integer_t;
  1589. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  1590. using number_float_t = typename BasicJsonType::number_float_t;
  1591. using string_t = typename BasicJsonType::string_t;
  1592. public:
  1593. /// token types for the parser
  1594. enum class token_type
  1595. {
  1596. uninitialized, ///< indicating the scanner is uninitialized
  1597. literal_true, ///< the `true` literal
  1598. literal_false, ///< the `false` literal
  1599. literal_null, ///< the `null` literal
  1600. value_string, ///< a string -- use get_string() for actual value
  1601. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  1602. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  1603. value_float, ///< an floating point number -- use get_number_float() for actual value
  1604. begin_array, ///< the character for array begin `[`
  1605. begin_object, ///< the character for object begin `{`
  1606. end_array, ///< the character for array end `]`
  1607. end_object, ///< the character for object end `}`
  1608. name_separator, ///< the name separator `:`
  1609. value_separator, ///< the value separator `,`
  1610. parse_error, ///< indicating a parse error
  1611. end_of_input, ///< indicating the end of the input buffer
  1612. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  1613. };
  1614. /// return name of values of type token_type (only used for errors)
  1615. static const char* token_type_name(const token_type t) noexcept
  1616. {
  1617. switch (t)
  1618. {
  1619. case token_type::uninitialized:
  1620. return "<uninitialized>";
  1621. case token_type::literal_true:
  1622. return "true literal";
  1623. case token_type::literal_false:
  1624. return "false literal";
  1625. case token_type::literal_null:
  1626. return "null literal";
  1627. case token_type::value_string:
  1628. return "string literal";
  1629. case lexer::token_type::value_unsigned:
  1630. case lexer::token_type::value_integer:
  1631. case lexer::token_type::value_float:
  1632. return "number literal";
  1633. case token_type::begin_array:
  1634. return "'['";
  1635. case token_type::begin_object:
  1636. return "'{'";
  1637. case token_type::end_array:
  1638. return "']'";
  1639. case token_type::end_object:
  1640. return "'}'";
  1641. case token_type::name_separator:
  1642. return "':'";
  1643. case token_type::value_separator:
  1644. return "','";
  1645. case token_type::parse_error:
  1646. return "<parse error>";
  1647. case token_type::end_of_input:
  1648. return "end of input";
  1649. case token_type::literal_or_value:
  1650. return "'[', '{', or a literal";
  1651. default: // catch non-enum values
  1652. return "unknown token"; // LCOV_EXCL_LINE
  1653. }
  1654. }
  1655. explicit lexer(detail::input_adapter_t adapter)
  1656. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  1657. // delete because of pointer members
  1658. lexer(const lexer&) = delete;
  1659. lexer& operator=(lexer&) = delete;
  1660. private:
  1661. /////////////////////
  1662. // locales
  1663. /////////////////////
  1664. /// return the locale-dependent decimal point
  1665. static char get_decimal_point() noexcept
  1666. {
  1667. const auto loc = localeconv();
  1668. assert(loc != nullptr);
  1669. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  1670. }
  1671. /////////////////////
  1672. // scan functions
  1673. /////////////////////
  1674. /*!
  1675. @brief get codepoint from 4 hex characters following `\u`
  1676. For input "\u c1 c2 c3 c4" the codepoint is:
  1677. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  1678. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  1679. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  1680. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  1681. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  1682. between the ASCII value of the character and the desired integer value.
  1683. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  1684. non-hex character)
  1685. */
  1686. int get_codepoint()
  1687. {
  1688. // this function only makes sense after reading `\u`
  1689. assert(current == 'u');
  1690. int codepoint = 0;
  1691. const auto factors = { 12, 8, 4, 0 };
  1692. for (const auto factor : factors)
  1693. {
  1694. get();
  1695. if (current >= '0' and current <= '9')
  1696. {
  1697. codepoint += ((current - 0x30) << factor);
  1698. }
  1699. else if (current >= 'A' and current <= 'F')
  1700. {
  1701. codepoint += ((current - 0x37) << factor);
  1702. }
  1703. else if (current >= 'a' and current <= 'f')
  1704. {
  1705. codepoint += ((current - 0x57) << factor);
  1706. }
  1707. else
  1708. {
  1709. return -1;
  1710. }
  1711. }
  1712. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  1713. return codepoint;
  1714. }
  1715. /*!
  1716. @brief check if the next byte(s) are inside a given range
  1717. Adds the current byte and, for each passed range, reads a new byte and
  1718. checks if it is inside the range. If a violation was detected, set up an
  1719. error message and return false. Otherwise, return true.
  1720. @param[in] ranges list of integers; interpreted as list of pairs of
  1721. inclusive lower and upper bound, respectively
  1722. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  1723. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  1724. @return true if and only if no range violation was detected
  1725. */
  1726. bool next_byte_in_range(std::initializer_list<int> ranges)
  1727. {
  1728. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  1729. add(current);
  1730. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  1731. {
  1732. get();
  1733. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  1734. {
  1735. add(current);
  1736. }
  1737. else
  1738. {
  1739. error_message = "invalid string: ill-formed UTF-8 byte";
  1740. return false;
  1741. }
  1742. }
  1743. return true;
  1744. }
  1745. /*!
  1746. @brief scan a string literal
  1747. This function scans a string according to Sect. 7 of RFC 7159. While
  1748. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  1749. function returns successfully, token_buffer is *not* null-terminated (as it
  1750. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  1751. string.
  1752. @return token_type::value_string if string could be successfully scanned,
  1753. token_type::parse_error otherwise
  1754. @note In case of errors, variable error_message contains a textual
  1755. description.
  1756. */
  1757. token_type scan_string()
  1758. {
  1759. // reset token_buffer (ignore opening quote)
  1760. reset();
  1761. // we entered the function by reading an open quote
  1762. assert(current == '\"');
  1763. while (true)
  1764. {
  1765. // get next character
  1766. switch (get())
  1767. {
  1768. // end of file while parsing string
  1769. case std::char_traits<char>::eof():
  1770. {
  1771. error_message = "invalid string: missing closing quote";
  1772. return token_type::parse_error;
  1773. }
  1774. // closing quote
  1775. case '\"':
  1776. {
  1777. return token_type::value_string;
  1778. }
  1779. // escapes
  1780. case '\\':
  1781. {
  1782. switch (get())
  1783. {
  1784. // quotation mark
  1785. case '\"':
  1786. add('\"');
  1787. break;
  1788. // reverse solidus
  1789. case '\\':
  1790. add('\\');
  1791. break;
  1792. // solidus
  1793. case '/':
  1794. add('/');
  1795. break;
  1796. // backspace
  1797. case 'b':
  1798. add('\b');
  1799. break;
  1800. // form feed
  1801. case 'f':
  1802. add('\f');
  1803. break;
  1804. // line feed
  1805. case 'n':
  1806. add('\n');
  1807. break;
  1808. // carriage return
  1809. case 'r':
  1810. add('\r');
  1811. break;
  1812. // tab
  1813. case 't':
  1814. add('\t');
  1815. break;
  1816. // unicode escapes
  1817. case 'u':
  1818. {
  1819. const int codepoint1 = get_codepoint();
  1820. int codepoint = codepoint1; // start with codepoint1
  1821. if (JSON_UNLIKELY(codepoint1 == -1))
  1822. {
  1823. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  1824. return token_type::parse_error;
  1825. }
  1826. // check if code point is a high surrogate
  1827. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  1828. {
  1829. // expect next \uxxxx entry
  1830. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  1831. {
  1832. const int codepoint2 = get_codepoint();
  1833. if (JSON_UNLIKELY(codepoint2 == -1))
  1834. {
  1835. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  1836. return token_type::parse_error;
  1837. }
  1838. // check if codepoint2 is a low surrogate
  1839. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  1840. {
  1841. // overwrite codepoint
  1842. codepoint =
  1843. // high surrogate occupies the most significant 22 bits
  1844. (codepoint1 << 10)
  1845. // low surrogate occupies the least significant 15 bits
  1846. + codepoint2
  1847. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  1848. // in the result so we have to subtract with:
  1849. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  1850. - 0x35FDC00;
  1851. }
  1852. else
  1853. {
  1854. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  1855. return token_type::parse_error;
  1856. }
  1857. }
  1858. else
  1859. {
  1860. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  1861. return token_type::parse_error;
  1862. }
  1863. }
  1864. else
  1865. {
  1866. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  1867. {
  1868. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  1869. return token_type::parse_error;
  1870. }
  1871. }
  1872. // result of the above calculation yields a proper codepoint
  1873. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  1874. // translate codepoint into bytes
  1875. if (codepoint < 0x80)
  1876. {
  1877. // 1-byte characters: 0xxxxxxx (ASCII)
  1878. add(codepoint);
  1879. }
  1880. else if (codepoint <= 0x7FF)
  1881. {
  1882. // 2-byte characters: 110xxxxx 10xxxxxx
  1883. add(0xC0 | (codepoint >> 6));
  1884. add(0x80 | (codepoint & 0x3F));
  1885. }
  1886. else if (codepoint <= 0xFFFF)
  1887. {
  1888. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  1889. add(0xE0 | (codepoint >> 12));
  1890. add(0x80 | ((codepoint >> 6) & 0x3F));
  1891. add(0x80 | (codepoint & 0x3F));
  1892. }
  1893. else
  1894. {
  1895. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1896. add(0xF0 | (codepoint >> 18));
  1897. add(0x80 | ((codepoint >> 12) & 0x3F));
  1898. add(0x80 | ((codepoint >> 6) & 0x3F));
  1899. add(0x80 | (codepoint & 0x3F));
  1900. }
  1901. break;
  1902. }
  1903. // other characters after escape
  1904. default:
  1905. error_message = "invalid string: forbidden character after backslash";
  1906. return token_type::parse_error;
  1907. }
  1908. break;
  1909. }
  1910. // invalid control characters
  1911. case 0x00:
  1912. case 0x01:
  1913. case 0x02:
  1914. case 0x03:
  1915. case 0x04:
  1916. case 0x05:
  1917. case 0x06:
  1918. case 0x07:
  1919. case 0x08:
  1920. case 0x09:
  1921. case 0x0A:
  1922. case 0x0B:
  1923. case 0x0C:
  1924. case 0x0D:
  1925. case 0x0E:
  1926. case 0x0F:
  1927. case 0x10:
  1928. case 0x11:
  1929. case 0x12:
  1930. case 0x13:
  1931. case 0x14:
  1932. case 0x15:
  1933. case 0x16:
  1934. case 0x17:
  1935. case 0x18:
  1936. case 0x19:
  1937. case 0x1A:
  1938. case 0x1B:
  1939. case 0x1C:
  1940. case 0x1D:
  1941. case 0x1E:
  1942. case 0x1F:
  1943. {
  1944. error_message = "invalid string: control character must be escaped";
  1945. return token_type::parse_error;
  1946. }
  1947. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  1948. case 0x20:
  1949. case 0x21:
  1950. case 0x23:
  1951. case 0x24:
  1952. case 0x25:
  1953. case 0x26:
  1954. case 0x27:
  1955. case 0x28:
  1956. case 0x29:
  1957. case 0x2A:
  1958. case 0x2B:
  1959. case 0x2C:
  1960. case 0x2D:
  1961. case 0x2E:
  1962. case 0x2F:
  1963. case 0x30:
  1964. case 0x31:
  1965. case 0x32:
  1966. case 0x33:
  1967. case 0x34:
  1968. case 0x35:
  1969. case 0x36:
  1970. case 0x37:
  1971. case 0x38:
  1972. case 0x39:
  1973. case 0x3A:
  1974. case 0x3B:
  1975. case 0x3C:
  1976. case 0x3D:
  1977. case 0x3E:
  1978. case 0x3F:
  1979. case 0x40:
  1980. case 0x41:
  1981. case 0x42:
  1982. case 0x43:
  1983. case 0x44:
  1984. case 0x45:
  1985. case 0x46:
  1986. case 0x47:
  1987. case 0x48:
  1988. case 0x49:
  1989. case 0x4A:
  1990. case 0x4B:
  1991. case 0x4C:
  1992. case 0x4D:
  1993. case 0x4E:
  1994. case 0x4F:
  1995. case 0x50:
  1996. case 0x51:
  1997. case 0x52:
  1998. case 0x53:
  1999. case 0x54:
  2000. case 0x55:
  2001. case 0x56:
  2002. case 0x57:
  2003. case 0x58:
  2004. case 0x59:
  2005. case 0x5A:
  2006. case 0x5B:
  2007. case 0x5D:
  2008. case 0x5E:
  2009. case 0x5F:
  2010. case 0x60:
  2011. case 0x61:
  2012. case 0x62:
  2013. case 0x63:
  2014. case 0x64:
  2015. case 0x65:
  2016. case 0x66:
  2017. case 0x67:
  2018. case 0x68:
  2019. case 0x69:
  2020. case 0x6A:
  2021. case 0x6B:
  2022. case 0x6C:
  2023. case 0x6D:
  2024. case 0x6E:
  2025. case 0x6F:
  2026. case 0x70:
  2027. case 0x71:
  2028. case 0x72:
  2029. case 0x73:
  2030. case 0x74:
  2031. case 0x75:
  2032. case 0x76:
  2033. case 0x77:
  2034. case 0x78:
  2035. case 0x79:
  2036. case 0x7A:
  2037. case 0x7B:
  2038. case 0x7C:
  2039. case 0x7D:
  2040. case 0x7E:
  2041. case 0x7F:
  2042. {
  2043. add(current);
  2044. break;
  2045. }
  2046. // U+0080..U+07FF: bytes C2..DF 80..BF
  2047. case 0xC2:
  2048. case 0xC3:
  2049. case 0xC4:
  2050. case 0xC5:
  2051. case 0xC6:
  2052. case 0xC7:
  2053. case 0xC8:
  2054. case 0xC9:
  2055. case 0xCA:
  2056. case 0xCB:
  2057. case 0xCC:
  2058. case 0xCD:
  2059. case 0xCE:
  2060. case 0xCF:
  2061. case 0xD0:
  2062. case 0xD1:
  2063. case 0xD2:
  2064. case 0xD3:
  2065. case 0xD4:
  2066. case 0xD5:
  2067. case 0xD6:
  2068. case 0xD7:
  2069. case 0xD8:
  2070. case 0xD9:
  2071. case 0xDA:
  2072. case 0xDB:
  2073. case 0xDC:
  2074. case 0xDD:
  2075. case 0xDE:
  2076. case 0xDF:
  2077. {
  2078. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  2079. {
  2080. return token_type::parse_error;
  2081. }
  2082. break;
  2083. }
  2084. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  2085. case 0xE0:
  2086. {
  2087. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  2088. {
  2089. return token_type::parse_error;
  2090. }
  2091. break;
  2092. }
  2093. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  2094. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  2095. case 0xE1:
  2096. case 0xE2:
  2097. case 0xE3:
  2098. case 0xE4:
  2099. case 0xE5:
  2100. case 0xE6:
  2101. case 0xE7:
  2102. case 0xE8:
  2103. case 0xE9:
  2104. case 0xEA:
  2105. case 0xEB:
  2106. case 0xEC:
  2107. case 0xEE:
  2108. case 0xEF:
  2109. {
  2110. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  2111. {
  2112. return token_type::parse_error;
  2113. }
  2114. break;
  2115. }
  2116. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  2117. case 0xED:
  2118. {
  2119. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  2120. {
  2121. return token_type::parse_error;
  2122. }
  2123. break;
  2124. }
  2125. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  2126. case 0xF0:
  2127. {
  2128. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  2129. {
  2130. return token_type::parse_error;
  2131. }
  2132. break;
  2133. }
  2134. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  2135. case 0xF1:
  2136. case 0xF2:
  2137. case 0xF3:
  2138. {
  2139. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  2140. {
  2141. return token_type::parse_error;
  2142. }
  2143. break;
  2144. }
  2145. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  2146. case 0xF4:
  2147. {
  2148. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  2149. {
  2150. return token_type::parse_error;
  2151. }
  2152. break;
  2153. }
  2154. // remaining bytes (80..C1 and F5..FF) are ill-formed
  2155. default:
  2156. {
  2157. error_message = "invalid string: ill-formed UTF-8 byte";
  2158. return token_type::parse_error;
  2159. }
  2160. }
  2161. }
  2162. }
  2163. static void strtof(float& f, const char* str, char** endptr) noexcept
  2164. {
  2165. f = std::strtof(str, endptr);
  2166. }
  2167. static void strtof(double& f, const char* str, char** endptr) noexcept
  2168. {
  2169. f = std::strtod(str, endptr);
  2170. }
  2171. static void strtof(long double& f, const char* str, char** endptr) noexcept
  2172. {
  2173. f = std::strtold(str, endptr);
  2174. }
  2175. /*!
  2176. @brief scan a number literal
  2177. This function scans a string according to Sect. 6 of RFC 7159.
  2178. The function is realized with a deterministic finite state machine derived
  2179. from the grammar described in RFC 7159. Starting in state "init", the
  2180. input is read and used to determined the next state. Only state "done"
  2181. accepts the number. State "error" is a trap state to model errors. In the
  2182. table below, "anything" means any character but the ones listed before.
  2183. state | 0 | 1-9 | e E | + | - | . | anything
  2184. ---------|----------|----------|----------|---------|---------|----------|-----------
  2185. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  2186. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  2187. zero | done | done | exponent | done | done | decimal1 | done
  2188. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  2189. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  2190. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  2191. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  2192. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  2193. any2 | any2 | any2 | done | done | done | done | done
  2194. The state machine is realized with one label per state (prefixed with
  2195. "scan_number_") and `goto` statements between them. The state machine
  2196. contains cycles, but any cycle can be left when EOF is read. Therefore,
  2197. the function is guaranteed to terminate.
  2198. During scanning, the read bytes are stored in token_buffer. This string is
  2199. then converted to a signed integer, an unsigned integer, or a
  2200. floating-point number.
  2201. @return token_type::value_unsigned, token_type::value_integer, or
  2202. token_type::value_float if number could be successfully scanned,
  2203. token_type::parse_error otherwise
  2204. @note The scanner is independent of the current locale. Internally, the
  2205. locale's decimal point is used instead of `.` to work with the
  2206. locale-dependent converters.
  2207. */
  2208. token_type scan_number()
  2209. {
  2210. // reset token_buffer to store the number's bytes
  2211. reset();
  2212. // the type of the parsed number; initially set to unsigned; will be
  2213. // changed if minus sign, decimal point or exponent is read
  2214. token_type number_type = token_type::value_unsigned;
  2215. // state (init): we just found out we need to scan a number
  2216. switch (current)
  2217. {
  2218. case '-':
  2219. {
  2220. add(current);
  2221. goto scan_number_minus;
  2222. }
  2223. case '0':
  2224. {
  2225. add(current);
  2226. goto scan_number_zero;
  2227. }
  2228. case '1':
  2229. case '2':
  2230. case '3':
  2231. case '4':
  2232. case '5':
  2233. case '6':
  2234. case '7':
  2235. case '8':
  2236. case '9':
  2237. {
  2238. add(current);
  2239. goto scan_number_any1;
  2240. }
  2241. default:
  2242. {
  2243. // all other characters are rejected outside scan_number()
  2244. assert(false); // LCOV_EXCL_LINE
  2245. }
  2246. }
  2247. scan_number_minus:
  2248. // state: we just parsed a leading minus sign
  2249. number_type = token_type::value_integer;
  2250. switch (get())
  2251. {
  2252. case '0':
  2253. {
  2254. add(current);
  2255. goto scan_number_zero;
  2256. }
  2257. case '1':
  2258. case '2':
  2259. case '3':
  2260. case '4':
  2261. case '5':
  2262. case '6':
  2263. case '7':
  2264. case '8':
  2265. case '9':
  2266. {
  2267. add(current);
  2268. goto scan_number_any1;
  2269. }
  2270. default:
  2271. {
  2272. error_message = "invalid number; expected digit after '-'";
  2273. return token_type::parse_error;
  2274. }
  2275. }
  2276. scan_number_zero:
  2277. // state: we just parse a zero (maybe with a leading minus sign)
  2278. switch (get())
  2279. {
  2280. case '.':
  2281. {
  2282. add(decimal_point_char);
  2283. goto scan_number_decimal1;
  2284. }
  2285. case 'e':
  2286. case 'E':
  2287. {
  2288. add(current);
  2289. goto scan_number_exponent;
  2290. }
  2291. default:
  2292. goto scan_number_done;
  2293. }
  2294. scan_number_any1:
  2295. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  2296. switch (get())
  2297. {
  2298. case '0':
  2299. case '1':
  2300. case '2':
  2301. case '3':
  2302. case '4':
  2303. case '5':
  2304. case '6':
  2305. case '7':
  2306. case '8':
  2307. case '9':
  2308. {
  2309. add(current);
  2310. goto scan_number_any1;
  2311. }
  2312. case '.':
  2313. {
  2314. add(decimal_point_char);
  2315. goto scan_number_decimal1;
  2316. }
  2317. case 'e':
  2318. case 'E':
  2319. {
  2320. add(current);
  2321. goto scan_number_exponent;
  2322. }
  2323. default:
  2324. goto scan_number_done;
  2325. }
  2326. scan_number_decimal1:
  2327. // state: we just parsed a decimal point
  2328. number_type = token_type::value_float;
  2329. switch (get())
  2330. {
  2331. case '0':
  2332. case '1':
  2333. case '2':
  2334. case '3':
  2335. case '4':
  2336. case '5':
  2337. case '6':
  2338. case '7':
  2339. case '8':
  2340. case '9':
  2341. {
  2342. add(current);
  2343. goto scan_number_decimal2;
  2344. }
  2345. default:
  2346. {
  2347. error_message = "invalid number; expected digit after '.'";
  2348. return token_type::parse_error;
  2349. }
  2350. }
  2351. scan_number_decimal2:
  2352. // we just parsed at least one number after a decimal point
  2353. switch (get())
  2354. {
  2355. case '0':
  2356. case '1':
  2357. case '2':
  2358. case '3':
  2359. case '4':
  2360. case '5':
  2361. case '6':
  2362. case '7':
  2363. case '8':
  2364. case '9':
  2365. {
  2366. add(current);
  2367. goto scan_number_decimal2;
  2368. }
  2369. case 'e':
  2370. case 'E':
  2371. {
  2372. add(current);
  2373. goto scan_number_exponent;
  2374. }
  2375. default:
  2376. goto scan_number_done;
  2377. }
  2378. scan_number_exponent:
  2379. // we just parsed an exponent
  2380. number_type = token_type::value_float;
  2381. switch (get())
  2382. {
  2383. case '+':
  2384. case '-':
  2385. {
  2386. add(current);
  2387. goto scan_number_sign;
  2388. }
  2389. case '0':
  2390. case '1':
  2391. case '2':
  2392. case '3':
  2393. case '4':
  2394. case '5':
  2395. case '6':
  2396. case '7':
  2397. case '8':
  2398. case '9':
  2399. {
  2400. add(current);
  2401. goto scan_number_any2;
  2402. }
  2403. default:
  2404. {
  2405. error_message =
  2406. "invalid number; expected '+', '-', or digit after exponent";
  2407. return token_type::parse_error;
  2408. }
  2409. }
  2410. scan_number_sign:
  2411. // we just parsed an exponent sign
  2412. switch (get())
  2413. {
  2414. case '0':
  2415. case '1':
  2416. case '2':
  2417. case '3':
  2418. case '4':
  2419. case '5':
  2420. case '6':
  2421. case '7':
  2422. case '8':
  2423. case '9':
  2424. {
  2425. add(current);
  2426. goto scan_number_any2;
  2427. }
  2428. default:
  2429. {
  2430. error_message = "invalid number; expected digit after exponent sign";
  2431. return token_type::parse_error;
  2432. }
  2433. }
  2434. scan_number_any2:
  2435. // we just parsed a number after the exponent or exponent sign
  2436. switch (get())
  2437. {
  2438. case '0':
  2439. case '1':
  2440. case '2':
  2441. case '3':
  2442. case '4':
  2443. case '5':
  2444. case '6':
  2445. case '7':
  2446. case '8':
  2447. case '9':
  2448. {
  2449. add(current);
  2450. goto scan_number_any2;
  2451. }
  2452. default:
  2453. goto scan_number_done;
  2454. }
  2455. scan_number_done:
  2456. // unget the character after the number (we only read it to know that
  2457. // we are done scanning a number)
  2458. unget();
  2459. char* endptr = nullptr;
  2460. errno = 0;
  2461. // try to parse integers first and fall back to floats
  2462. if (number_type == token_type::value_unsigned)
  2463. {
  2464. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  2465. // we checked the number format before
  2466. assert(endptr == token_buffer.data() + token_buffer.size());
  2467. if (errno == 0)
  2468. {
  2469. value_unsigned = static_cast<number_unsigned_t>(x);
  2470. if (value_unsigned == x)
  2471. {
  2472. return token_type::value_unsigned;
  2473. }
  2474. }
  2475. }
  2476. else if (number_type == token_type::value_integer)
  2477. {
  2478. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  2479. // we checked the number format before
  2480. assert(endptr == token_buffer.data() + token_buffer.size());
  2481. if (errno == 0)
  2482. {
  2483. value_integer = static_cast<number_integer_t>(x);
  2484. if (value_integer == x)
  2485. {
  2486. return token_type::value_integer;
  2487. }
  2488. }
  2489. }
  2490. // this code is reached if we parse a floating-point number or if an
  2491. // integer conversion above failed
  2492. strtof(value_float, token_buffer.data(), &endptr);
  2493. // we checked the number format before
  2494. assert(endptr == token_buffer.data() + token_buffer.size());
  2495. return token_type::value_float;
  2496. }
  2497. /*!
  2498. @param[in] literal_text the literal text to expect
  2499. @param[in] length the length of the passed literal text
  2500. @param[in] return_type the token type to return on success
  2501. */
  2502. token_type scan_literal(const char* literal_text, const std::size_t length,
  2503. token_type return_type)
  2504. {
  2505. assert(current == literal_text[0]);
  2506. for (std::size_t i = 1; i < length; ++i)
  2507. {
  2508. if (JSON_UNLIKELY(get() != literal_text[i]))
  2509. {
  2510. error_message = "invalid literal";
  2511. return token_type::parse_error;
  2512. }
  2513. }
  2514. return return_type;
  2515. }
  2516. /////////////////////
  2517. // input management
  2518. /////////////////////
  2519. /// reset token_buffer; current character is beginning of token
  2520. void reset() noexcept
  2521. {
  2522. token_buffer.clear();
  2523. token_string.clear();
  2524. token_string.push_back(std::char_traits<char>::to_char_type(current));
  2525. }
  2526. /*
  2527. @brief get next character from the input
  2528. This function provides the interface to the used input adapter. It does
  2529. not throw in case the input reached EOF, but returns a
  2530. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  2531. for use in error messages.
  2532. @return character read from the input
  2533. */
  2534. std::char_traits<char>::int_type get()
  2535. {
  2536. ++chars_read;
  2537. current = ia->get_character();
  2538. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  2539. {
  2540. token_string.push_back(std::char_traits<char>::to_char_type(current));
  2541. }
  2542. return current;
  2543. }
  2544. /// unget current character (return it again on next get)
  2545. void unget()
  2546. {
  2547. --chars_read;
  2548. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  2549. {
  2550. ia->unget_character();
  2551. assert(token_string.size() != 0);
  2552. token_string.pop_back();
  2553. }
  2554. }
  2555. /// add a character to token_buffer
  2556. void add(int c)
  2557. {
  2558. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  2559. }
  2560. public:
  2561. /////////////////////
  2562. // value getters
  2563. /////////////////////
  2564. /// return integer value
  2565. constexpr number_integer_t get_number_integer() const noexcept
  2566. {
  2567. return value_integer;
  2568. }
  2569. /// return unsigned integer value
  2570. constexpr number_unsigned_t get_number_unsigned() const noexcept
  2571. {
  2572. return value_unsigned;
  2573. }
  2574. /// return floating-point value
  2575. constexpr number_float_t get_number_float() const noexcept
  2576. {
  2577. return value_float;
  2578. }
  2579. /// return current string value (implicitly resets the token; useful only once)
  2580. string_t&& move_string()
  2581. {
  2582. return std::move(token_buffer);
  2583. }
  2584. /////////////////////
  2585. // diagnostics
  2586. /////////////////////
  2587. /// return position of last read token
  2588. constexpr std::size_t get_position() const noexcept
  2589. {
  2590. return chars_read;
  2591. }
  2592. /// return the last read token (for errors only). Will never contain EOF
  2593. /// (an arbitrary value that is not a valid char value, often -1), because
  2594. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  2595. std::string get_token_string() const
  2596. {
  2597. // escape control characters
  2598. std::string result;
  2599. for (const auto c : token_string)
  2600. {
  2601. if ('\x00' <= c and c <= '\x1F')
  2602. {
  2603. // escape control characters
  2604. std::stringstream ss;
  2605. ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
  2606. << std::hex << static_cast<int>(c) << ">";
  2607. result += ss.str();
  2608. }
  2609. else
  2610. {
  2611. // add character as is
  2612. result.push_back(c);
  2613. }
  2614. }
  2615. return result;
  2616. }
  2617. /// return syntax error message
  2618. constexpr const char* get_error_message() const noexcept
  2619. {
  2620. return error_message;
  2621. }
  2622. /////////////////////
  2623. // actual scanner
  2624. /////////////////////
  2625. token_type scan()
  2626. {
  2627. // read next character and ignore whitespace
  2628. do
  2629. {
  2630. get();
  2631. }
  2632. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  2633. switch (current)
  2634. {
  2635. // structural characters
  2636. case '[':
  2637. return token_type::begin_array;
  2638. case ']':
  2639. return token_type::end_array;
  2640. case '{':
  2641. return token_type::begin_object;
  2642. case '}':
  2643. return token_type::end_object;
  2644. case ':':
  2645. return token_type::name_separator;
  2646. case ',':
  2647. return token_type::value_separator;
  2648. // literals
  2649. case 't':
  2650. return scan_literal("true", 4, token_type::literal_true);
  2651. case 'f':
  2652. return scan_literal("false", 5, token_type::literal_false);
  2653. case 'n':
  2654. return scan_literal("null", 4, token_type::literal_null);
  2655. // string
  2656. case '\"':
  2657. return scan_string();
  2658. // number
  2659. case '-':
  2660. case '0':
  2661. case '1':
  2662. case '2':
  2663. case '3':
  2664. case '4':
  2665. case '5':
  2666. case '6':
  2667. case '7':
  2668. case '8':
  2669. case '9':
  2670. return scan_number();
  2671. // end of input (the null byte is needed when parsing from
  2672. // string literals)
  2673. case '\0':
  2674. case std::char_traits<char>::eof():
  2675. return token_type::end_of_input;
  2676. // error
  2677. default:
  2678. error_message = "invalid literal";
  2679. return token_type::parse_error;
  2680. }
  2681. }
  2682. private:
  2683. /// input adapter
  2684. detail::input_adapter_t ia = nullptr;
  2685. /// the current character
  2686. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  2687. /// the number of characters read
  2688. std::size_t chars_read = 0;
  2689. /// raw input token string (for error messages)
  2690. std::vector<char> token_string {};
  2691. /// buffer for variable-length tokens (numbers, strings)
  2692. string_t token_buffer {};
  2693. /// a description of occurred lexer errors
  2694. const char* error_message = "";
  2695. // number values
  2696. number_integer_t value_integer = 0;
  2697. number_unsigned_t value_unsigned = 0;
  2698. number_float_t value_float = 0;
  2699. /// the decimal point
  2700. const char decimal_point_char = '.';
  2701. };
  2702. }
  2703. }
  2704. // #include <nlohmann/detail/input/parser.hpp>
  2705. #include <cassert> // assert
  2706. #include <cmath> // isfinite
  2707. #include <cstdint> // uint8_t
  2708. #include <functional> // function
  2709. #include <string> // string
  2710. #include <utility> // move
  2711. // #include <nlohmann/detail/exceptions.hpp>
  2712. // #include <nlohmann/detail/macro_scope.hpp>
  2713. // #include <nlohmann/detail/input/input_adapters.hpp>
  2714. // #include <nlohmann/detail/input/lexer.hpp>
  2715. // #include <nlohmann/detail/value_t.hpp>
  2716. namespace nlohmann
  2717. {
  2718. namespace detail
  2719. {
  2720. ////////////
  2721. // parser //
  2722. ////////////
  2723. /*!
  2724. @brief syntax analysis
  2725. This class implements a recursive decent parser.
  2726. */
  2727. template<typename BasicJsonType>
  2728. class parser
  2729. {
  2730. using number_integer_t = typename BasicJsonType::number_integer_t;
  2731. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2732. using number_float_t = typename BasicJsonType::number_float_t;
  2733. using string_t = typename BasicJsonType::string_t;
  2734. using lexer_t = lexer<BasicJsonType>;
  2735. using token_type = typename lexer_t::token_type;
  2736. public:
  2737. enum class parse_event_t : uint8_t
  2738. {
  2739. /// the parser read `{` and started to process a JSON object
  2740. object_start,
  2741. /// the parser read `}` and finished processing a JSON object
  2742. object_end,
  2743. /// the parser read `[` and started to process a JSON array
  2744. array_start,
  2745. /// the parser read `]` and finished processing a JSON array
  2746. array_end,
  2747. /// the parser read a key of a value in an object
  2748. key,
  2749. /// the parser finished reading a JSON value
  2750. value
  2751. };
  2752. using parser_callback_t =
  2753. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  2754. /// a parser reading from an input adapter
  2755. explicit parser(detail::input_adapter_t adapter,
  2756. const parser_callback_t cb = nullptr,
  2757. const bool allow_exceptions_ = true)
  2758. : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
  2759. {}
  2760. /*!
  2761. @brief public parser interface
  2762. @param[in] strict whether to expect the last token to be EOF
  2763. @param[in,out] result parsed JSON value
  2764. @throw parse_error.101 in case of an unexpected token
  2765. @throw parse_error.102 if to_unicode fails or surrogate error
  2766. @throw parse_error.103 if to_unicode fails
  2767. */
  2768. void parse(const bool strict, BasicJsonType& result)
  2769. {
  2770. // read first token
  2771. get_token();
  2772. parse_internal(true, result);
  2773. result.assert_invariant();
  2774. // in strict mode, input must be completely read
  2775. if (strict)
  2776. {
  2777. get_token();
  2778. expect(token_type::end_of_input);
  2779. }
  2780. // in case of an error, return discarded value
  2781. if (errored)
  2782. {
  2783. result = value_t::discarded;
  2784. return;
  2785. }
  2786. // set top-level value to null if it was discarded by the callback
  2787. // function
  2788. if (result.is_discarded())
  2789. {
  2790. result = nullptr;
  2791. }
  2792. }
  2793. /*!
  2794. @brief public accept interface
  2795. @param[in] strict whether to expect the last token to be EOF
  2796. @return whether the input is a proper JSON text
  2797. */
  2798. bool accept(const bool strict = true)
  2799. {
  2800. // read first token
  2801. get_token();
  2802. if (not accept_internal())
  2803. {
  2804. return false;
  2805. }
  2806. // strict => last token must be EOF
  2807. return not strict or (get_token() == token_type::end_of_input);
  2808. }
  2809. private:
  2810. /*!
  2811. @brief the actual parser
  2812. @throw parse_error.101 in case of an unexpected token
  2813. @throw parse_error.102 if to_unicode fails or surrogate error
  2814. @throw parse_error.103 if to_unicode fails
  2815. */
  2816. void parse_internal(bool keep, BasicJsonType& result)
  2817. {
  2818. // never parse after a parse error was detected
  2819. assert(not errored);
  2820. // start with a discarded value
  2821. if (not result.is_discarded())
  2822. {
  2823. result.m_value.destroy(result.m_type);
  2824. result.m_type = value_t::discarded;
  2825. }
  2826. switch (last_token)
  2827. {
  2828. case token_type::begin_object:
  2829. {
  2830. if (keep)
  2831. {
  2832. if (callback)
  2833. {
  2834. keep = callback(depth++, parse_event_t::object_start, result);
  2835. }
  2836. if (not callback or keep)
  2837. {
  2838. // explicitly set result to object to cope with {}
  2839. result.m_type = value_t::object;
  2840. result.m_value = value_t::object;
  2841. }
  2842. }
  2843. // read next token
  2844. get_token();
  2845. // closing } -> we are done
  2846. if (last_token == token_type::end_object)
  2847. {
  2848. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  2849. {
  2850. result.m_value.destroy(result.m_type);
  2851. result.m_type = value_t::discarded;
  2852. }
  2853. break;
  2854. }
  2855. // parse values
  2856. string_t key;
  2857. BasicJsonType value;
  2858. while (true)
  2859. {
  2860. // store key
  2861. if (not expect(token_type::value_string))
  2862. {
  2863. return;
  2864. }
  2865. key = m_lexer.move_string();
  2866. bool keep_tag = false;
  2867. if (keep)
  2868. {
  2869. if (callback)
  2870. {
  2871. BasicJsonType k(key);
  2872. keep_tag = callback(depth, parse_event_t::key, k);
  2873. }
  2874. else
  2875. {
  2876. keep_tag = true;
  2877. }
  2878. }
  2879. // parse separator (:)
  2880. get_token();
  2881. if (not expect(token_type::name_separator))
  2882. {
  2883. return;
  2884. }
  2885. // parse and add value
  2886. get_token();
  2887. value.m_value.destroy(value.m_type);
  2888. value.m_type = value_t::discarded;
  2889. parse_internal(keep, value);
  2890. if (JSON_UNLIKELY(errored))
  2891. {
  2892. return;
  2893. }
  2894. if (keep and keep_tag and not value.is_discarded())
  2895. {
  2896. result.m_value.object->emplace(std::move(key), std::move(value));
  2897. }
  2898. // comma -> next value
  2899. get_token();
  2900. if (last_token == token_type::value_separator)
  2901. {
  2902. get_token();
  2903. continue;
  2904. }
  2905. // closing }
  2906. if (not expect(token_type::end_object))
  2907. {
  2908. return;
  2909. }
  2910. break;
  2911. }
  2912. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  2913. {
  2914. result.m_value.destroy(result.m_type);
  2915. result.m_type = value_t::discarded;
  2916. }
  2917. break;
  2918. }
  2919. case token_type::begin_array:
  2920. {
  2921. if (keep)
  2922. {
  2923. if (callback)
  2924. {
  2925. keep = callback(depth++, parse_event_t::array_start, result);
  2926. }
  2927. if (not callback or keep)
  2928. {
  2929. // explicitly set result to array to cope with []
  2930. result.m_type = value_t::array;
  2931. result.m_value = value_t::array;
  2932. }
  2933. }
  2934. // read next token
  2935. get_token();
  2936. // closing ] -> we are done
  2937. if (last_token == token_type::end_array)
  2938. {
  2939. if (callback and not callback(--depth, parse_event_t::array_end, result))
  2940. {
  2941. result.m_value.destroy(result.m_type);
  2942. result.m_type = value_t::discarded;
  2943. }
  2944. break;
  2945. }
  2946. // parse values
  2947. BasicJsonType value;
  2948. while (true)
  2949. {
  2950. // parse value
  2951. value.m_value.destroy(value.m_type);
  2952. value.m_type = value_t::discarded;
  2953. parse_internal(keep, value);
  2954. if (JSON_UNLIKELY(errored))
  2955. {
  2956. return;
  2957. }
  2958. if (keep and not value.is_discarded())
  2959. {
  2960. result.m_value.array->push_back(std::move(value));
  2961. }
  2962. // comma -> next value
  2963. get_token();
  2964. if (last_token == token_type::value_separator)
  2965. {
  2966. get_token();
  2967. continue;
  2968. }
  2969. // closing ]
  2970. if (not expect(token_type::end_array))
  2971. {
  2972. return;
  2973. }
  2974. break;
  2975. }
  2976. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  2977. {
  2978. result.m_value.destroy(result.m_type);
  2979. result.m_type = value_t::discarded;
  2980. }
  2981. break;
  2982. }
  2983. case token_type::literal_null:
  2984. {
  2985. result.m_type = value_t::null;
  2986. break;
  2987. }
  2988. case token_type::value_string:
  2989. {
  2990. result.m_type = value_t::string;
  2991. result.m_value = m_lexer.move_string();
  2992. break;
  2993. }
  2994. case token_type::literal_true:
  2995. {
  2996. result.m_type = value_t::boolean;
  2997. result.m_value = true;
  2998. break;
  2999. }
  3000. case token_type::literal_false:
  3001. {
  3002. result.m_type = value_t::boolean;
  3003. result.m_value = false;
  3004. break;
  3005. }
  3006. case token_type::value_unsigned:
  3007. {
  3008. result.m_type = value_t::number_unsigned;
  3009. result.m_value = m_lexer.get_number_unsigned();
  3010. break;
  3011. }
  3012. case token_type::value_integer:
  3013. {
  3014. result.m_type = value_t::number_integer;
  3015. result.m_value = m_lexer.get_number_integer();
  3016. break;
  3017. }
  3018. case token_type::value_float:
  3019. {
  3020. result.m_type = value_t::number_float;
  3021. result.m_value = m_lexer.get_number_float();
  3022. // throw in case of infinity or NAN
  3023. if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
  3024. {
  3025. if (allow_exceptions)
  3026. {
  3027. JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
  3028. m_lexer.get_token_string() + "'"));
  3029. }
  3030. expect(token_type::uninitialized);
  3031. }
  3032. break;
  3033. }
  3034. case token_type::parse_error:
  3035. {
  3036. // using "uninitialized" to avoid "expected" message
  3037. if (not expect(token_type::uninitialized))
  3038. {
  3039. return;
  3040. }
  3041. break; // LCOV_EXCL_LINE
  3042. }
  3043. default:
  3044. {
  3045. // the last token was unexpected; we expected a value
  3046. if (not expect(token_type::literal_or_value))
  3047. {
  3048. return;
  3049. }
  3050. break; // LCOV_EXCL_LINE
  3051. }
  3052. }
  3053. if (keep and callback and not callback(depth, parse_event_t::value, result))
  3054. {
  3055. result.m_value.destroy(result.m_type);
  3056. result.m_type = value_t::discarded;
  3057. }
  3058. }
  3059. /*!
  3060. @brief the actual acceptor
  3061. @invariant 1. The last token is not yet processed. Therefore, the caller
  3062. of this function must make sure a token has been read.
  3063. 2. When this function returns, the last token is processed.
  3064. That is, the last read character was already considered.
  3065. This invariant makes sure that no token needs to be "unput".
  3066. */
  3067. bool accept_internal()
  3068. {
  3069. switch (last_token)
  3070. {
  3071. case token_type::begin_object:
  3072. {
  3073. // read next token
  3074. get_token();
  3075. // closing } -> we are done
  3076. if (last_token == token_type::end_object)
  3077. {
  3078. return true;
  3079. }
  3080. // parse values
  3081. while (true)
  3082. {
  3083. // parse key
  3084. if (last_token != token_type::value_string)
  3085. {
  3086. return false;
  3087. }
  3088. // parse separator (:)
  3089. get_token();
  3090. if (last_token != token_type::name_separator)
  3091. {
  3092. return false;
  3093. }
  3094. // parse value
  3095. get_token();
  3096. if (not accept_internal())
  3097. {
  3098. return false;
  3099. }
  3100. // comma -> next value
  3101. get_token();
  3102. if (last_token == token_type::value_separator)
  3103. {
  3104. get_token();
  3105. continue;
  3106. }
  3107. // closing }
  3108. return (last_token == token_type::end_object);
  3109. }
  3110. }
  3111. case token_type::begin_array:
  3112. {
  3113. // read next token
  3114. get_token();
  3115. // closing ] -> we are done
  3116. if (last_token == token_type::end_array)
  3117. {
  3118. return true;
  3119. }
  3120. // parse values
  3121. while (true)
  3122. {
  3123. // parse value
  3124. if (not accept_internal())
  3125. {
  3126. return false;
  3127. }
  3128. // comma -> next value
  3129. get_token();
  3130. if (last_token == token_type::value_separator)
  3131. {
  3132. get_token();
  3133. continue;
  3134. }
  3135. // closing ]
  3136. return (last_token == token_type::end_array);
  3137. }
  3138. }
  3139. case token_type::value_float:
  3140. {
  3141. // reject infinity or NAN
  3142. return std::isfinite(m_lexer.get_number_float());
  3143. }
  3144. case token_type::literal_false:
  3145. case token_type::literal_null:
  3146. case token_type::literal_true:
  3147. case token_type::value_integer:
  3148. case token_type::value_string:
  3149. case token_type::value_unsigned:
  3150. return true;
  3151. default: // the last token was unexpected
  3152. return false;
  3153. }
  3154. }
  3155. /// get next token from lexer
  3156. token_type get_token()
  3157. {
  3158. return (last_token = m_lexer.scan());
  3159. }
  3160. /*!
  3161. @throw parse_error.101 if expected token did not occur
  3162. */
  3163. bool expect(token_type t)
  3164. {
  3165. if (JSON_UNLIKELY(t != last_token))
  3166. {
  3167. errored = true;
  3168. expected = t;
  3169. if (allow_exceptions)
  3170. {
  3171. throw_exception();
  3172. }
  3173. else
  3174. {
  3175. return false;
  3176. }
  3177. }
  3178. return true;
  3179. }
  3180. [[noreturn]] void throw_exception() const
  3181. {
  3182. std::string error_msg = "syntax error - ";
  3183. if (last_token == token_type::parse_error)
  3184. {
  3185. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  3186. m_lexer.get_token_string() + "'";
  3187. }
  3188. else
  3189. {
  3190. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  3191. }
  3192. if (expected != token_type::uninitialized)
  3193. {
  3194. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  3195. }
  3196. JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
  3197. }
  3198. private:
  3199. /// current level of recursion
  3200. int depth = 0;
  3201. /// callback function
  3202. const parser_callback_t callback = nullptr;
  3203. /// the type of the last read token
  3204. token_type last_token = token_type::uninitialized;
  3205. /// the lexer
  3206. lexer_t m_lexer;
  3207. /// whether a syntax error occurred
  3208. bool errored = false;
  3209. /// possible reason for the syntax error
  3210. token_type expected = token_type::uninitialized;
  3211. /// whether to throw exceptions in case of errors
  3212. const bool allow_exceptions = true;
  3213. };
  3214. }
  3215. }
  3216. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  3217. #include <cstddef> // ptrdiff_t
  3218. #include <limits> // numeric_limits
  3219. namespace nlohmann
  3220. {
  3221. namespace detail
  3222. {
  3223. /*
  3224. @brief an iterator for primitive JSON types
  3225. This class models an iterator for primitive JSON types (boolean, number,
  3226. string). It's only purpose is to allow the iterator/const_iterator classes
  3227. to "iterate" over primitive values. Internally, the iterator is modeled by
  3228. a `difference_type` variable. Value begin_value (`0`) models the begin,
  3229. end_value (`1`) models past the end.
  3230. */
  3231. class primitive_iterator_t
  3232. {
  3233. private:
  3234. using difference_type = std::ptrdiff_t;
  3235. static constexpr difference_type begin_value = 0;
  3236. static constexpr difference_type end_value = begin_value + 1;
  3237. /// iterator as signed integer type
  3238. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  3239. public:
  3240. constexpr difference_type get_value() const noexcept
  3241. {
  3242. return m_it;
  3243. }
  3244. /// set iterator to a defined beginning
  3245. void set_begin() noexcept
  3246. {
  3247. m_it = begin_value;
  3248. }
  3249. /// set iterator to a defined past the end
  3250. void set_end() noexcept
  3251. {
  3252. m_it = end_value;
  3253. }
  3254. /// return whether the iterator can be dereferenced
  3255. constexpr bool is_begin() const noexcept
  3256. {
  3257. return m_it == begin_value;
  3258. }
  3259. /// return whether the iterator is at end
  3260. constexpr bool is_end() const noexcept
  3261. {
  3262. return m_it == end_value;
  3263. }
  3264. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3265. {
  3266. return lhs.m_it == rhs.m_it;
  3267. }
  3268. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3269. {
  3270. return lhs.m_it < rhs.m_it;
  3271. }
  3272. primitive_iterator_t operator+(difference_type n) noexcept
  3273. {
  3274. auto result = *this;
  3275. result += n;
  3276. return result;
  3277. }
  3278. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3279. {
  3280. return lhs.m_it - rhs.m_it;
  3281. }
  3282. primitive_iterator_t& operator++() noexcept
  3283. {
  3284. ++m_it;
  3285. return *this;
  3286. }
  3287. primitive_iterator_t const operator++(int) noexcept
  3288. {
  3289. auto result = *this;
  3290. m_it++;
  3291. return result;
  3292. }
  3293. primitive_iterator_t& operator--() noexcept
  3294. {
  3295. --m_it;
  3296. return *this;
  3297. }
  3298. primitive_iterator_t const operator--(int) noexcept
  3299. {
  3300. auto result = *this;
  3301. m_it--;
  3302. return result;
  3303. }
  3304. primitive_iterator_t& operator+=(difference_type n) noexcept
  3305. {
  3306. m_it += n;
  3307. return *this;
  3308. }
  3309. primitive_iterator_t& operator-=(difference_type n) noexcept
  3310. {
  3311. m_it -= n;
  3312. return *this;
  3313. }
  3314. };
  3315. }
  3316. }
  3317. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  3318. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  3319. namespace nlohmann
  3320. {
  3321. namespace detail
  3322. {
  3323. /*!
  3324. @brief an iterator value
  3325. @note This structure could easily be a union, but MSVC currently does not allow
  3326. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  3327. */
  3328. template<typename BasicJsonType> struct internal_iterator
  3329. {
  3330. /// iterator for JSON objects
  3331. typename BasicJsonType::object_t::iterator object_iterator {};
  3332. /// iterator for JSON arrays
  3333. typename BasicJsonType::array_t::iterator array_iterator {};
  3334. /// generic iterator for all other types
  3335. primitive_iterator_t primitive_iterator {};
  3336. };
  3337. }
  3338. }
  3339. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  3340. #include <ciso646> // not
  3341. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  3342. #include <type_traits> // conditional, is_const, remove_const
  3343. // #include <nlohmann/detail/exceptions.hpp>
  3344. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  3345. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  3346. // #include <nlohmann/detail/macro_scope.hpp>
  3347. // #include <nlohmann/detail/meta.hpp>
  3348. // #include <nlohmann/detail/value_t.hpp>
  3349. namespace nlohmann
  3350. {
  3351. namespace detail
  3352. {
  3353. // forward declare, to be able to friend it later on
  3354. template<typename IteratorType> class iteration_proxy;
  3355. /*!
  3356. @brief a template for a bidirectional iterator for the @ref basic_json class
  3357. This class implements a both iterators (iterator and const_iterator) for the
  3358. @ref basic_json class.
  3359. @note An iterator is called *initialized* when a pointer to a JSON value has
  3360. been set (e.g., by a constructor or a copy assignment). If the iterator is
  3361. default-constructed, it is *uninitialized* and most methods are undefined.
  3362. **The library uses assertions to detect calls on uninitialized iterators.**
  3363. @requirement The class satisfies the following concept requirements:
  3364. -
  3365. [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
  3366. The iterator that can be moved can be moved in both directions (i.e.
  3367. incremented and decremented).
  3368. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  3369. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  3370. */
  3371. template<typename BasicJsonType>
  3372. class iter_impl
  3373. {
  3374. /// allow basic_json to access private members
  3375. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  3376. friend BasicJsonType;
  3377. friend iteration_proxy<iter_impl>;
  3378. using object_t = typename BasicJsonType::object_t;
  3379. using array_t = typename BasicJsonType::array_t;
  3380. // make sure BasicJsonType is basic_json or const basic_json
  3381. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  3382. "iter_impl only accepts (const) basic_json");
  3383. public:
  3384. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  3385. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  3386. /// A user-defined iterator should provide publicly accessible typedefs named
  3387. /// iterator_category, value_type, difference_type, pointer, and reference.
  3388. /// Note that value_type is required to be non-const, even for constant iterators.
  3389. using iterator_category = std::bidirectional_iterator_tag;
  3390. /// the type of the values when the iterator is dereferenced
  3391. using value_type = typename BasicJsonType::value_type;
  3392. /// a type to represent differences between iterators
  3393. using difference_type = typename BasicJsonType::difference_type;
  3394. /// defines a pointer to the type iterated over (value_type)
  3395. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  3396. typename BasicJsonType::const_pointer,
  3397. typename BasicJsonType::pointer>::type;
  3398. /// defines a reference to the type iterated over (value_type)
  3399. using reference =
  3400. typename std::conditional<std::is_const<BasicJsonType>::value,
  3401. typename BasicJsonType::const_reference,
  3402. typename BasicJsonType::reference>::type;
  3403. /// default constructor
  3404. iter_impl() = default;
  3405. /*!
  3406. @brief constructor for a given JSON instance
  3407. @param[in] object pointer to a JSON object for this iterator
  3408. @pre object != nullptr
  3409. @post The iterator is initialized; i.e. `m_object != nullptr`.
  3410. */
  3411. explicit iter_impl(pointer object) noexcept : m_object(object)
  3412. {
  3413. assert(m_object != nullptr);
  3414. switch (m_object->m_type)
  3415. {
  3416. case value_t::object:
  3417. {
  3418. m_it.object_iterator = typename object_t::iterator();
  3419. break;
  3420. }
  3421. case value_t::array:
  3422. {
  3423. m_it.array_iterator = typename array_t::iterator();
  3424. break;
  3425. }
  3426. default:
  3427. {
  3428. m_it.primitive_iterator = primitive_iterator_t();
  3429. break;
  3430. }
  3431. }
  3432. }
  3433. /*!
  3434. @note The conventional copy constructor and copy assignment are implicitly
  3435. defined. Combined with the following converting constructor and
  3436. assignment, they support: (1) copy from iterator to iterator, (2)
  3437. copy from const iterator to const iterator, and (3) conversion from
  3438. iterator to const iterator. However conversion from const iterator
  3439. to iterator is not defined.
  3440. */
  3441. /*!
  3442. @brief converting constructor
  3443. @param[in] other non-const iterator to copy from
  3444. @note It is not checked whether @a other is initialized.
  3445. */
  3446. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  3447. : m_object(other.m_object), m_it(other.m_it) {}
  3448. /*!
  3449. @brief converting assignment
  3450. @param[in,out] other non-const iterator to copy from
  3451. @return const/non-const iterator
  3452. @note It is not checked whether @a other is initialized.
  3453. */
  3454. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  3455. {
  3456. m_object = other.m_object;
  3457. m_it = other.m_it;
  3458. return *this;
  3459. }
  3460. private:
  3461. /*!
  3462. @brief set the iterator to the first value
  3463. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3464. */
  3465. void set_begin() noexcept
  3466. {
  3467. assert(m_object != nullptr);
  3468. switch (m_object->m_type)
  3469. {
  3470. case value_t::object:
  3471. {
  3472. m_it.object_iterator = m_object->m_value.object->begin();
  3473. break;
  3474. }
  3475. case value_t::array:
  3476. {
  3477. m_it.array_iterator = m_object->m_value.array->begin();
  3478. break;
  3479. }
  3480. case value_t::null:
  3481. {
  3482. // set to end so begin()==end() is true: null is empty
  3483. m_it.primitive_iterator.set_end();
  3484. break;
  3485. }
  3486. default:
  3487. {
  3488. m_it.primitive_iterator.set_begin();
  3489. break;
  3490. }
  3491. }
  3492. }
  3493. /*!
  3494. @brief set the iterator past the last value
  3495. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3496. */
  3497. void set_end() noexcept
  3498. {
  3499. assert(m_object != nullptr);
  3500. switch (m_object->m_type)
  3501. {
  3502. case value_t::object:
  3503. {
  3504. m_it.object_iterator = m_object->m_value.object->end();
  3505. break;
  3506. }
  3507. case value_t::array:
  3508. {
  3509. m_it.array_iterator = m_object->m_value.array->end();
  3510. break;
  3511. }
  3512. default:
  3513. {
  3514. m_it.primitive_iterator.set_end();
  3515. break;
  3516. }
  3517. }
  3518. }
  3519. public:
  3520. /*!
  3521. @brief return a reference to the value pointed to by the iterator
  3522. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3523. */
  3524. reference operator*() const
  3525. {
  3526. assert(m_object != nullptr);
  3527. switch (m_object->m_type)
  3528. {
  3529. case value_t::object:
  3530. {
  3531. assert(m_it.object_iterator != m_object->m_value.object->end());
  3532. return m_it.object_iterator->second;
  3533. }
  3534. case value_t::array:
  3535. {
  3536. assert(m_it.array_iterator != m_object->m_value.array->end());
  3537. return *m_it.array_iterator;
  3538. }
  3539. case value_t::null:
  3540. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3541. default:
  3542. {
  3543. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  3544. {
  3545. return *m_object;
  3546. }
  3547. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3548. }
  3549. }
  3550. }
  3551. /*!
  3552. @brief dereference the iterator
  3553. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3554. */
  3555. pointer operator->() const
  3556. {
  3557. assert(m_object != nullptr);
  3558. switch (m_object->m_type)
  3559. {
  3560. case value_t::object:
  3561. {
  3562. assert(m_it.object_iterator != m_object->m_value.object->end());
  3563. return &(m_it.object_iterator->second);
  3564. }
  3565. case value_t::array:
  3566. {
  3567. assert(m_it.array_iterator != m_object->m_value.array->end());
  3568. return &*m_it.array_iterator;
  3569. }
  3570. default:
  3571. {
  3572. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  3573. {
  3574. return m_object;
  3575. }
  3576. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3577. }
  3578. }
  3579. }
  3580. /*!
  3581. @brief post-increment (it++)
  3582. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3583. */
  3584. iter_impl const operator++(int)
  3585. {
  3586. auto result = *this;
  3587. ++(*this);
  3588. return result;
  3589. }
  3590. /*!
  3591. @brief pre-increment (++it)
  3592. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3593. */
  3594. iter_impl& operator++()
  3595. {
  3596. assert(m_object != nullptr);
  3597. switch (m_object->m_type)
  3598. {
  3599. case value_t::object:
  3600. {
  3601. std::advance(m_it.object_iterator, 1);
  3602. break;
  3603. }
  3604. case value_t::array:
  3605. {
  3606. std::advance(m_it.array_iterator, 1);
  3607. break;
  3608. }
  3609. default:
  3610. {
  3611. ++m_it.primitive_iterator;
  3612. break;
  3613. }
  3614. }
  3615. return *this;
  3616. }
  3617. /*!
  3618. @brief post-decrement (it--)
  3619. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3620. */
  3621. iter_impl const operator--(int)
  3622. {
  3623. auto result = *this;
  3624. --(*this);
  3625. return result;
  3626. }
  3627. /*!
  3628. @brief pre-decrement (--it)
  3629. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3630. */
  3631. iter_impl& operator--()
  3632. {
  3633. assert(m_object != nullptr);
  3634. switch (m_object->m_type)
  3635. {
  3636. case value_t::object:
  3637. {
  3638. std::advance(m_it.object_iterator, -1);
  3639. break;
  3640. }
  3641. case value_t::array:
  3642. {
  3643. std::advance(m_it.array_iterator, -1);
  3644. break;
  3645. }
  3646. default:
  3647. {
  3648. --m_it.primitive_iterator;
  3649. break;
  3650. }
  3651. }
  3652. return *this;
  3653. }
  3654. /*!
  3655. @brief comparison: equal
  3656. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3657. */
  3658. bool operator==(const iter_impl& other) const
  3659. {
  3660. // if objects are not the same, the comparison is undefined
  3661. if (JSON_UNLIKELY(m_object != other.m_object))
  3662. {
  3663. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  3664. }
  3665. assert(m_object != nullptr);
  3666. switch (m_object->m_type)
  3667. {
  3668. case value_t::object:
  3669. return (m_it.object_iterator == other.m_it.object_iterator);
  3670. case value_t::array:
  3671. return (m_it.array_iterator == other.m_it.array_iterator);
  3672. default:
  3673. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  3674. }
  3675. }
  3676. /*!
  3677. @brief comparison: not equal
  3678. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3679. */
  3680. bool operator!=(const iter_impl& other) const
  3681. {
  3682. return not operator==(other);
  3683. }
  3684. /*!
  3685. @brief comparison: smaller
  3686. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3687. */
  3688. bool operator<(const iter_impl& other) const
  3689. {
  3690. // if objects are not the same, the comparison is undefined
  3691. if (JSON_UNLIKELY(m_object != other.m_object))
  3692. {
  3693. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  3694. }
  3695. assert(m_object != nullptr);
  3696. switch (m_object->m_type)
  3697. {
  3698. case value_t::object:
  3699. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  3700. case value_t::array:
  3701. return (m_it.array_iterator < other.m_it.array_iterator);
  3702. default:
  3703. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  3704. }
  3705. }
  3706. /*!
  3707. @brief comparison: less than or equal
  3708. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3709. */
  3710. bool operator<=(const iter_impl& other) const
  3711. {
  3712. return not other.operator < (*this);
  3713. }
  3714. /*!
  3715. @brief comparison: greater than
  3716. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3717. */
  3718. bool operator>(const iter_impl& other) const
  3719. {
  3720. return not operator<=(other);
  3721. }
  3722. /*!
  3723. @brief comparison: greater than or equal
  3724. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3725. */
  3726. bool operator>=(const iter_impl& other) const
  3727. {
  3728. return not operator<(other);
  3729. }
  3730. /*!
  3731. @brief add to iterator
  3732. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3733. */
  3734. iter_impl& operator+=(difference_type i)
  3735. {
  3736. assert(m_object != nullptr);
  3737. switch (m_object->m_type)
  3738. {
  3739. case value_t::object:
  3740. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  3741. case value_t::array:
  3742. {
  3743. std::advance(m_it.array_iterator, i);
  3744. break;
  3745. }
  3746. default:
  3747. {
  3748. m_it.primitive_iterator += i;
  3749. break;
  3750. }
  3751. }
  3752. return *this;
  3753. }
  3754. /*!
  3755. @brief subtract from iterator
  3756. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3757. */
  3758. iter_impl& operator-=(difference_type i)
  3759. {
  3760. return operator+=(-i);
  3761. }
  3762. /*!
  3763. @brief add to iterator
  3764. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3765. */
  3766. iter_impl operator+(difference_type i) const
  3767. {
  3768. auto result = *this;
  3769. result += i;
  3770. return result;
  3771. }
  3772. /*!
  3773. @brief addition of distance and iterator
  3774. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3775. */
  3776. friend iter_impl operator+(difference_type i, const iter_impl& it)
  3777. {
  3778. auto result = it;
  3779. result += i;
  3780. return result;
  3781. }
  3782. /*!
  3783. @brief subtract from iterator
  3784. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3785. */
  3786. iter_impl operator-(difference_type i) const
  3787. {
  3788. auto result = *this;
  3789. result -= i;
  3790. return result;
  3791. }
  3792. /*!
  3793. @brief return difference
  3794. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3795. */
  3796. difference_type operator-(const iter_impl& other) const
  3797. {
  3798. assert(m_object != nullptr);
  3799. switch (m_object->m_type)
  3800. {
  3801. case value_t::object:
  3802. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  3803. case value_t::array:
  3804. return m_it.array_iterator - other.m_it.array_iterator;
  3805. default:
  3806. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  3807. }
  3808. }
  3809. /*!
  3810. @brief access to successor
  3811. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3812. */
  3813. reference operator[](difference_type n) const
  3814. {
  3815. assert(m_object != nullptr);
  3816. switch (m_object->m_type)
  3817. {
  3818. case value_t::object:
  3819. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  3820. case value_t::array:
  3821. return *std::next(m_it.array_iterator, n);
  3822. case value_t::null:
  3823. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3824. default:
  3825. {
  3826. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  3827. {
  3828. return *m_object;
  3829. }
  3830. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3831. }
  3832. }
  3833. }
  3834. /*!
  3835. @brief return the key of an object iterator
  3836. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3837. */
  3838. typename object_t::key_type key() const
  3839. {
  3840. assert(m_object != nullptr);
  3841. if (JSON_LIKELY(m_object->is_object()))
  3842. {
  3843. return m_it.object_iterator->first;
  3844. }
  3845. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  3846. }
  3847. /*!
  3848. @brief return the value of an iterator
  3849. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3850. */
  3851. reference value() const
  3852. {
  3853. return operator*();
  3854. }
  3855. private:
  3856. /// associated JSON instance
  3857. pointer m_object = nullptr;
  3858. /// the actual iterator of the associated instance
  3859. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it;
  3860. };
  3861. }
  3862. }
  3863. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3864. #include <cstddef> // size_t
  3865. #include <string> // string, to_string
  3866. // #include <nlohmann/detail/value_t.hpp>
  3867. namespace nlohmann
  3868. {
  3869. namespace detail
  3870. {
  3871. /// proxy class for the items() function
  3872. template<typename IteratorType> class iteration_proxy
  3873. {
  3874. private:
  3875. /// helper class for iteration
  3876. class iteration_proxy_internal
  3877. {
  3878. private:
  3879. /// the iterator
  3880. IteratorType anchor;
  3881. /// an index for arrays (used to create key names)
  3882. std::size_t array_index = 0;
  3883. public:
  3884. explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
  3885. /// dereference operator (needed for range-based for)
  3886. iteration_proxy_internal& operator*()
  3887. {
  3888. return *this;
  3889. }
  3890. /// increment operator (needed for range-based for)
  3891. iteration_proxy_internal& operator++()
  3892. {
  3893. ++anchor;
  3894. ++array_index;
  3895. return *this;
  3896. }
  3897. /// inequality operator (needed for range-based for)
  3898. bool operator!=(const iteration_proxy_internal& o) const noexcept
  3899. {
  3900. return anchor != o.anchor;
  3901. }
  3902. /// return key of the iterator
  3903. std::string key() const
  3904. {
  3905. assert(anchor.m_object != nullptr);
  3906. switch (anchor.m_object->type())
  3907. {
  3908. // use integer array index as key
  3909. case value_t::array:
  3910. return std::to_string(array_index);
  3911. // use key from the object
  3912. case value_t::object:
  3913. return anchor.key();
  3914. // use an empty key for all primitive types
  3915. default:
  3916. return "";
  3917. }
  3918. }
  3919. /// return value of the iterator
  3920. typename IteratorType::reference value() const
  3921. {
  3922. return anchor.value();
  3923. }
  3924. };
  3925. /// the container to iterate
  3926. typename IteratorType::reference container;
  3927. public:
  3928. /// construct iteration proxy from a container
  3929. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3930. : container(cont) {}
  3931. /// return iterator begin (needed for range-based for)
  3932. iteration_proxy_internal begin() noexcept
  3933. {
  3934. return iteration_proxy_internal(container.begin());
  3935. }
  3936. /// return iterator end (needed for range-based for)
  3937. iteration_proxy_internal end() noexcept
  3938. {
  3939. return iteration_proxy_internal(container.end());
  3940. }
  3941. };
  3942. }
  3943. }
  3944. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  3945. #include <cstddef> // ptrdiff_t
  3946. #include <iterator> // reverse_iterator
  3947. #include <utility> // declval
  3948. namespace nlohmann
  3949. {
  3950. namespace detail
  3951. {
  3952. //////////////////////
  3953. // reverse_iterator //
  3954. //////////////////////
  3955. /*!
  3956. @brief a template for a reverse iterator class
  3957. @tparam Base the base iterator type to reverse. Valid types are @ref
  3958. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  3959. create @ref const_reverse_iterator).
  3960. @requirement The class satisfies the following concept requirements:
  3961. -
  3962. [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
  3963. The iterator that can be moved can be moved in both directions (i.e.
  3964. incremented and decremented).
  3965. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  3966. It is possible to write to the pointed-to element (only if @a Base is
  3967. @ref iterator).
  3968. @since version 1.0.0
  3969. */
  3970. template<typename Base>
  3971. class json_reverse_iterator : public std::reverse_iterator<Base>
  3972. {
  3973. public:
  3974. using difference_type = std::ptrdiff_t;
  3975. /// shortcut to the reverse iterator adapter
  3976. using base_iterator = std::reverse_iterator<Base>;
  3977. /// the reference type for the pointed-to element
  3978. using reference = typename Base::reference;
  3979. /// create reverse iterator from iterator
  3980. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  3981. : base_iterator(it) {}
  3982. /// create reverse iterator from base class
  3983. json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  3984. /// post-increment (it++)
  3985. json_reverse_iterator const operator++(int)
  3986. {
  3987. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  3988. }
  3989. /// pre-increment (++it)
  3990. json_reverse_iterator& operator++()
  3991. {
  3992. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  3993. }
  3994. /// post-decrement (it--)
  3995. json_reverse_iterator const operator--(int)
  3996. {
  3997. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  3998. }
  3999. /// pre-decrement (--it)
  4000. json_reverse_iterator& operator--()
  4001. {
  4002. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  4003. }
  4004. /// add to iterator
  4005. json_reverse_iterator& operator+=(difference_type i)
  4006. {
  4007. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  4008. }
  4009. /// add to iterator
  4010. json_reverse_iterator operator+(difference_type i) const
  4011. {
  4012. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  4013. }
  4014. /// subtract from iterator
  4015. json_reverse_iterator operator-(difference_type i) const
  4016. {
  4017. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  4018. }
  4019. /// return difference
  4020. difference_type operator-(const json_reverse_iterator& other) const
  4021. {
  4022. return base_iterator(*this) - base_iterator(other);
  4023. }
  4024. /// access to successor
  4025. reference operator[](difference_type n) const
  4026. {
  4027. return *(this->operator+(n));
  4028. }
  4029. /// return the key of an object iterator
  4030. auto key() const -> decltype(std::declval<Base>().key())
  4031. {
  4032. auto it = --this->base();
  4033. return it.key();
  4034. }
  4035. /// return the value of an iterator
  4036. reference value() const
  4037. {
  4038. auto it = --this->base();
  4039. return it.operator * ();
  4040. }
  4041. };
  4042. }
  4043. }
  4044. // #include <nlohmann/detail/output/output_adapters.hpp>
  4045. #include <algorithm> // copy
  4046. #include <cstddef> // size_t
  4047. #include <ios> // streamsize
  4048. #include <iterator> // back_inserter
  4049. #include <memory> // shared_ptr, make_shared
  4050. #include <ostream> // basic_ostream
  4051. #include <string> // basic_string
  4052. #include <vector> // vector
  4053. namespace nlohmann
  4054. {
  4055. namespace detail
  4056. {
  4057. /// abstract output adapter interface
  4058. template<typename CharType> struct output_adapter_protocol
  4059. {
  4060. virtual void write_character(CharType c) = 0;
  4061. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  4062. virtual ~output_adapter_protocol() = default;
  4063. };
  4064. /// a type to simplify interfaces
  4065. template<typename CharType>
  4066. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  4067. /// output adapter for byte vectors
  4068. template<typename CharType>
  4069. class output_vector_adapter : public output_adapter_protocol<CharType>
  4070. {
  4071. public:
  4072. explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
  4073. void write_character(CharType c) override
  4074. {
  4075. v.push_back(c);
  4076. }
  4077. void write_characters(const CharType* s, std::size_t length) override
  4078. {
  4079. std::copy(s, s + length, std::back_inserter(v));
  4080. }
  4081. private:
  4082. std::vector<CharType>& v;
  4083. };
  4084. /// output adapter for output streams
  4085. template<typename CharType>
  4086. class output_stream_adapter : public output_adapter_protocol<CharType>
  4087. {
  4088. public:
  4089. explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
  4090. void write_character(CharType c) override
  4091. {
  4092. stream.put(c);
  4093. }
  4094. void write_characters(const CharType* s, std::size_t length) override
  4095. {
  4096. stream.write(s, static_cast<std::streamsize>(length));
  4097. }
  4098. private:
  4099. std::basic_ostream<CharType>& stream;
  4100. };
  4101. /// output adapter for basic_string
  4102. template<typename CharType, typename StringType = std::basic_string<CharType>>
  4103. class output_string_adapter : public output_adapter_protocol<CharType>
  4104. {
  4105. public:
  4106. explicit output_string_adapter(StringType& s) : str(s) {}
  4107. void write_character(CharType c) override
  4108. {
  4109. str.push_back(c);
  4110. }
  4111. void write_characters(const CharType* s, std::size_t length) override
  4112. {
  4113. str.append(s, length);
  4114. }
  4115. private:
  4116. StringType& str;
  4117. };
  4118. template<typename CharType, typename StringType = std::basic_string<CharType>>
  4119. class output_adapter
  4120. {
  4121. public:
  4122. output_adapter(std::vector<CharType>& vec)
  4123. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  4124. output_adapter(std::basic_ostream<CharType>& s)
  4125. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  4126. output_adapter(StringType& s)
  4127. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  4128. operator output_adapter_t<CharType>()
  4129. {
  4130. return oa;
  4131. }
  4132. private:
  4133. output_adapter_t<CharType> oa = nullptr;
  4134. };
  4135. }
  4136. }
  4137. // #include <nlohmann/detail/input/binary_reader.hpp>
  4138. #include <algorithm> // generate_n
  4139. #include <array> // array
  4140. #include <cassert> // assert
  4141. #include <cmath> // ldexp
  4142. #include <cstddef> // size_t
  4143. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  4144. #include <cstring> // memcpy
  4145. #include <iomanip> // setw, setfill
  4146. #include <ios> // hex
  4147. #include <iterator> // back_inserter
  4148. #include <limits> // numeric_limits
  4149. #include <sstream> // stringstream
  4150. #include <string> // char_traits, string
  4151. #include <utility> // make_pair, move
  4152. // #include <nlohmann/detail/input/input_adapters.hpp>
  4153. // #include <nlohmann/detail/exceptions.hpp>
  4154. // #include <nlohmann/detail/macro_scope.hpp>
  4155. // #include <nlohmann/detail/value_t.hpp>
  4156. namespace nlohmann
  4157. {
  4158. namespace detail
  4159. {
  4160. ///////////////////
  4161. // binary reader //
  4162. ///////////////////
  4163. /*!
  4164. @brief deserialization of CBOR and MessagePack values
  4165. */
  4166. template<typename BasicJsonType>
  4167. class binary_reader
  4168. {
  4169. using number_integer_t = typename BasicJsonType::number_integer_t;
  4170. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4171. using string_t = typename BasicJsonType::string_t;
  4172. public:
  4173. /*!
  4174. @brief create a binary reader
  4175. @param[in] adapter input adapter to read from
  4176. */
  4177. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  4178. {
  4179. assert(ia);
  4180. }
  4181. /*!
  4182. @brief create a JSON value from CBOR input
  4183. @param[in] strict whether to expect the input to be consumed completed
  4184. @return JSON value created from CBOR input
  4185. @throw parse_error.110 if input ended unexpectedly or the end of file was
  4186. not reached when @a strict was set to true
  4187. @throw parse_error.112 if unsupported byte was read
  4188. */
  4189. BasicJsonType parse_cbor(const bool strict)
  4190. {
  4191. const auto res = parse_cbor_internal();
  4192. if (strict)
  4193. {
  4194. get();
  4195. expect_eof();
  4196. }
  4197. return res;
  4198. }
  4199. /*!
  4200. @brief create a JSON value from MessagePack input
  4201. @param[in] strict whether to expect the input to be consumed completed
  4202. @return JSON value created from MessagePack input
  4203. @throw parse_error.110 if input ended unexpectedly or the end of file was
  4204. not reached when @a strict was set to true
  4205. @throw parse_error.112 if unsupported byte was read
  4206. */
  4207. BasicJsonType parse_msgpack(const bool strict)
  4208. {
  4209. const auto res = parse_msgpack_internal();
  4210. if (strict)
  4211. {
  4212. get();
  4213. expect_eof();
  4214. }
  4215. return res;
  4216. }
  4217. /*!
  4218. @brief create a JSON value from UBJSON input
  4219. @param[in] strict whether to expect the input to be consumed completed
  4220. @return JSON value created from UBJSON input
  4221. @throw parse_error.110 if input ended unexpectedly or the end of file was
  4222. not reached when @a strict was set to true
  4223. @throw parse_error.112 if unsupported byte was read
  4224. */
  4225. BasicJsonType parse_ubjson(const bool strict)
  4226. {
  4227. const auto res = parse_ubjson_internal();
  4228. if (strict)
  4229. {
  4230. get_ignore_noop();
  4231. expect_eof();
  4232. }
  4233. return res;
  4234. }
  4235. /*!
  4236. @brief determine system byte order
  4237. @return true if and only if system's byte order is little endian
  4238. @note from http://stackoverflow.com/a/1001328/266378
  4239. */
  4240. static constexpr bool little_endianess(int num = 1) noexcept
  4241. {
  4242. return (*reinterpret_cast<char*>(&num) == 1);
  4243. }
  4244. private:
  4245. /*!
  4246. @param[in] get_char whether a new character should be retrieved from the
  4247. input (true, default) or whether the last read
  4248. character should be considered instead
  4249. */
  4250. BasicJsonType parse_cbor_internal(const bool get_char = true)
  4251. {
  4252. switch (get_char ? get() : current)
  4253. {
  4254. // EOF
  4255. case std::char_traits<char>::eof():
  4256. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  4257. // Integer 0x00..0x17 (0..23)
  4258. case 0x00:
  4259. case 0x01:
  4260. case 0x02:
  4261. case 0x03:
  4262. case 0x04:
  4263. case 0x05:
  4264. case 0x06:
  4265. case 0x07:
  4266. case 0x08:
  4267. case 0x09:
  4268. case 0x0A:
  4269. case 0x0B:
  4270. case 0x0C:
  4271. case 0x0D:
  4272. case 0x0E:
  4273. case 0x0F:
  4274. case 0x10:
  4275. case 0x11:
  4276. case 0x12:
  4277. case 0x13:
  4278. case 0x14:
  4279. case 0x15:
  4280. case 0x16:
  4281. case 0x17:
  4282. return static_cast<number_unsigned_t>(current);
  4283. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  4284. return get_number<uint8_t>();
  4285. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  4286. return get_number<uint16_t>();
  4287. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  4288. return get_number<uint32_t>();
  4289. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  4290. return get_number<uint64_t>();
  4291. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  4292. case 0x20:
  4293. case 0x21:
  4294. case 0x22:
  4295. case 0x23:
  4296. case 0x24:
  4297. case 0x25:
  4298. case 0x26:
  4299. case 0x27:
  4300. case 0x28:
  4301. case 0x29:
  4302. case 0x2A:
  4303. case 0x2B:
  4304. case 0x2C:
  4305. case 0x2D:
  4306. case 0x2E:
  4307. case 0x2F:
  4308. case 0x30:
  4309. case 0x31:
  4310. case 0x32:
  4311. case 0x33:
  4312. case 0x34:
  4313. case 0x35:
  4314. case 0x36:
  4315. case 0x37:
  4316. return static_cast<int8_t>(0x20 - 1 - current);
  4317. case 0x38: // Negative integer (one-byte uint8_t follows)
  4318. {
  4319. return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
  4320. }
  4321. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4322. {
  4323. return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
  4324. }
  4325. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  4326. {
  4327. return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
  4328. }
  4329. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  4330. {
  4331. return static_cast<number_integer_t>(-1) -
  4332. static_cast<number_integer_t>(get_number<uint64_t>());
  4333. }
  4334. // UTF-8 string (0x00..0x17 bytes follow)
  4335. case 0x60:
  4336. case 0x61:
  4337. case 0x62:
  4338. case 0x63:
  4339. case 0x64:
  4340. case 0x65:
  4341. case 0x66:
  4342. case 0x67:
  4343. case 0x68:
  4344. case 0x69:
  4345. case 0x6A:
  4346. case 0x6B:
  4347. case 0x6C:
  4348. case 0x6D:
  4349. case 0x6E:
  4350. case 0x6F:
  4351. case 0x70:
  4352. case 0x71:
  4353. case 0x72:
  4354. case 0x73:
  4355. case 0x74:
  4356. case 0x75:
  4357. case 0x76:
  4358. case 0x77:
  4359. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4360. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4361. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4362. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4363. case 0x7F: // UTF-8 string (indefinite length)
  4364. {
  4365. return get_cbor_string();
  4366. }
  4367. // array (0x00..0x17 data items follow)
  4368. case 0x80:
  4369. case 0x81:
  4370. case 0x82:
  4371. case 0x83:
  4372. case 0x84:
  4373. case 0x85:
  4374. case 0x86:
  4375. case 0x87:
  4376. case 0x88:
  4377. case 0x89:
  4378. case 0x8A:
  4379. case 0x8B:
  4380. case 0x8C:
  4381. case 0x8D:
  4382. case 0x8E:
  4383. case 0x8F:
  4384. case 0x90:
  4385. case 0x91:
  4386. case 0x92:
  4387. case 0x93:
  4388. case 0x94:
  4389. case 0x95:
  4390. case 0x96:
  4391. case 0x97:
  4392. {
  4393. return get_cbor_array(current & 0x1F);
  4394. }
  4395. case 0x98: // array (one-byte uint8_t for n follows)
  4396. {
  4397. return get_cbor_array(get_number<uint8_t>());
  4398. }
  4399. case 0x99: // array (two-byte uint16_t for n follow)
  4400. {
  4401. return get_cbor_array(get_number<uint16_t>());
  4402. }
  4403. case 0x9A: // array (four-byte uint32_t for n follow)
  4404. {
  4405. return get_cbor_array(get_number<uint32_t>());
  4406. }
  4407. case 0x9B: // array (eight-byte uint64_t for n follow)
  4408. {
  4409. return get_cbor_array(get_number<uint64_t>());
  4410. }
  4411. case 0x9F: // array (indefinite length)
  4412. {
  4413. BasicJsonType result = value_t::array;
  4414. while (get() != 0xFF)
  4415. {
  4416. result.push_back(parse_cbor_internal(false));
  4417. }
  4418. return result;
  4419. }
  4420. // map (0x00..0x17 pairs of data items follow)
  4421. case 0xA0:
  4422. case 0xA1:
  4423. case 0xA2:
  4424. case 0xA3:
  4425. case 0xA4:
  4426. case 0xA5:
  4427. case 0xA6:
  4428. case 0xA7:
  4429. case 0xA8:
  4430. case 0xA9:
  4431. case 0xAA:
  4432. case 0xAB:
  4433. case 0xAC:
  4434. case 0xAD:
  4435. case 0xAE:
  4436. case 0xAF:
  4437. case 0xB0:
  4438. case 0xB1:
  4439. case 0xB2:
  4440. case 0xB3:
  4441. case 0xB4:
  4442. case 0xB5:
  4443. case 0xB6:
  4444. case 0xB7:
  4445. {
  4446. return get_cbor_object(current & 0x1F);
  4447. }
  4448. case 0xB8: // map (one-byte uint8_t for n follows)
  4449. {
  4450. return get_cbor_object(get_number<uint8_t>());
  4451. }
  4452. case 0xB9: // map (two-byte uint16_t for n follow)
  4453. {
  4454. return get_cbor_object(get_number<uint16_t>());
  4455. }
  4456. case 0xBA: // map (four-byte uint32_t for n follow)
  4457. {
  4458. return get_cbor_object(get_number<uint32_t>());
  4459. }
  4460. case 0xBB: // map (eight-byte uint64_t for n follow)
  4461. {
  4462. return get_cbor_object(get_number<uint64_t>());
  4463. }
  4464. case 0xBF: // map (indefinite length)
  4465. {
  4466. BasicJsonType result = value_t::object;
  4467. while (get() != 0xFF)
  4468. {
  4469. auto key = get_cbor_string();
  4470. result[key] = parse_cbor_internal();
  4471. }
  4472. return result;
  4473. }
  4474. case 0xF4: // false
  4475. {
  4476. return false;
  4477. }
  4478. case 0xF5: // true
  4479. {
  4480. return true;
  4481. }
  4482. case 0xF6: // null
  4483. {
  4484. return value_t::null;
  4485. }
  4486. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  4487. {
  4488. const int byte1 = get();
  4489. unexpect_eof();
  4490. const int byte2 = get();
  4491. unexpect_eof();
  4492. // code from RFC 7049, Appendix D, Figure 3:
  4493. // As half-precision floating-point numbers were only added
  4494. // to IEEE 754 in 2008, today's programming platforms often
  4495. // still only have limited support for them. It is very
  4496. // easy to include at least decoding support for them even
  4497. // without such support. An example of a small decoder for
  4498. // half-precision floating-point numbers in the C language
  4499. // is shown in Fig. 3.
  4500. const int half = (byte1 << 8) + byte2;
  4501. const int exp = (half >> 10) & 0x1F;
  4502. const int mant = half & 0x3FF;
  4503. double val;
  4504. if (exp == 0)
  4505. {
  4506. val = std::ldexp(mant, -24);
  4507. }
  4508. else if (exp != 31)
  4509. {
  4510. val = std::ldexp(mant + 1024, exp - 25);
  4511. }
  4512. else
  4513. {
  4514. val = (mant == 0) ? std::numeric_limits<double>::infinity()
  4515. : std::numeric_limits<double>::quiet_NaN();
  4516. }
  4517. return (half & 0x8000) != 0 ? -val : val;
  4518. }
  4519. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  4520. {
  4521. return get_number<float>();
  4522. }
  4523. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  4524. {
  4525. return get_number<double>();
  4526. }
  4527. default: // anything else (0xFF is handled inside the other types)
  4528. {
  4529. std::stringstream ss;
  4530. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4531. JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
  4532. }
  4533. }
  4534. }
  4535. BasicJsonType parse_msgpack_internal()
  4536. {
  4537. switch (get())
  4538. {
  4539. // EOF
  4540. case std::char_traits<char>::eof():
  4541. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  4542. // positive fixint
  4543. case 0x00:
  4544. case 0x01:
  4545. case 0x02:
  4546. case 0x03:
  4547. case 0x04:
  4548. case 0x05:
  4549. case 0x06:
  4550. case 0x07:
  4551. case 0x08:
  4552. case 0x09:
  4553. case 0x0A:
  4554. case 0x0B:
  4555. case 0x0C:
  4556. case 0x0D:
  4557. case 0x0E:
  4558. case 0x0F:
  4559. case 0x10:
  4560. case 0x11:
  4561. case 0x12:
  4562. case 0x13:
  4563. case 0x14:
  4564. case 0x15:
  4565. case 0x16:
  4566. case 0x17:
  4567. case 0x18:
  4568. case 0x19:
  4569. case 0x1A:
  4570. case 0x1B:
  4571. case 0x1C:
  4572. case 0x1D:
  4573. case 0x1E:
  4574. case 0x1F:
  4575. case 0x20:
  4576. case 0x21:
  4577. case 0x22:
  4578. case 0x23:
  4579. case 0x24:
  4580. case 0x25:
  4581. case 0x26:
  4582. case 0x27:
  4583. case 0x28:
  4584. case 0x29:
  4585. case 0x2A:
  4586. case 0x2B:
  4587. case 0x2C:
  4588. case 0x2D:
  4589. case 0x2E:
  4590. case 0x2F:
  4591. case 0x30:
  4592. case 0x31:
  4593. case 0x32:
  4594. case 0x33:
  4595. case 0x34:
  4596. case 0x35:
  4597. case 0x36:
  4598. case 0x37:
  4599. case 0x38:
  4600. case 0x39:
  4601. case 0x3A:
  4602. case 0x3B:
  4603. case 0x3C:
  4604. case 0x3D:
  4605. case 0x3E:
  4606. case 0x3F:
  4607. case 0x40:
  4608. case 0x41:
  4609. case 0x42:
  4610. case 0x43:
  4611. case 0x44:
  4612. case 0x45:
  4613. case 0x46:
  4614. case 0x47:
  4615. case 0x48:
  4616. case 0x49:
  4617. case 0x4A:
  4618. case 0x4B:
  4619. case 0x4C:
  4620. case 0x4D:
  4621. case 0x4E:
  4622. case 0x4F:
  4623. case 0x50:
  4624. case 0x51:
  4625. case 0x52:
  4626. case 0x53:
  4627. case 0x54:
  4628. case 0x55:
  4629. case 0x56:
  4630. case 0x57:
  4631. case 0x58:
  4632. case 0x59:
  4633. case 0x5A:
  4634. case 0x5B:
  4635. case 0x5C:
  4636. case 0x5D:
  4637. case 0x5E:
  4638. case 0x5F:
  4639. case 0x60:
  4640. case 0x61:
  4641. case 0x62:
  4642. case 0x63:
  4643. case 0x64:
  4644. case 0x65:
  4645. case 0x66:
  4646. case 0x67:
  4647. case 0x68:
  4648. case 0x69:
  4649. case 0x6A:
  4650. case 0x6B:
  4651. case 0x6C:
  4652. case 0x6D:
  4653. case 0x6E:
  4654. case 0x6F:
  4655. case 0x70:
  4656. case 0x71:
  4657. case 0x72:
  4658. case 0x73:
  4659. case 0x74:
  4660. case 0x75:
  4661. case 0x76:
  4662. case 0x77:
  4663. case 0x78:
  4664. case 0x79:
  4665. case 0x7A:
  4666. case 0x7B:
  4667. case 0x7C:
  4668. case 0x7D:
  4669. case 0x7E:
  4670. case 0x7F:
  4671. return static_cast<number_unsigned_t>(current);
  4672. // fixmap
  4673. case 0x80:
  4674. case 0x81:
  4675. case 0x82:
  4676. case 0x83:
  4677. case 0x84:
  4678. case 0x85:
  4679. case 0x86:
  4680. case 0x87:
  4681. case 0x88:
  4682. case 0x89:
  4683. case 0x8A:
  4684. case 0x8B:
  4685. case 0x8C:
  4686. case 0x8D:
  4687. case 0x8E:
  4688. case 0x8F:
  4689. {
  4690. return get_msgpack_object(current & 0x0F);
  4691. }
  4692. // fixarray
  4693. case 0x90:
  4694. case 0x91:
  4695. case 0x92:
  4696. case 0x93:
  4697. case 0x94:
  4698. case 0x95:
  4699. case 0x96:
  4700. case 0x97:
  4701. case 0x98:
  4702. case 0x99:
  4703. case 0x9A:
  4704. case 0x9B:
  4705. case 0x9C:
  4706. case 0x9D:
  4707. case 0x9E:
  4708. case 0x9F:
  4709. {
  4710. return get_msgpack_array(current & 0x0F);
  4711. }
  4712. // fixstr
  4713. case 0xA0:
  4714. case 0xA1:
  4715. case 0xA2:
  4716. case 0xA3:
  4717. case 0xA4:
  4718. case 0xA5:
  4719. case 0xA6:
  4720. case 0xA7:
  4721. case 0xA8:
  4722. case 0xA9:
  4723. case 0xAA:
  4724. case 0xAB:
  4725. case 0xAC:
  4726. case 0xAD:
  4727. case 0xAE:
  4728. case 0xAF:
  4729. case 0xB0:
  4730. case 0xB1:
  4731. case 0xB2:
  4732. case 0xB3:
  4733. case 0xB4:
  4734. case 0xB5:
  4735. case 0xB6:
  4736. case 0xB7:
  4737. case 0xB8:
  4738. case 0xB9:
  4739. case 0xBA:
  4740. case 0xBB:
  4741. case 0xBC:
  4742. case 0xBD:
  4743. case 0xBE:
  4744. case 0xBF:
  4745. return get_msgpack_string();
  4746. case 0xC0: // nil
  4747. return value_t::null;
  4748. case 0xC2: // false
  4749. return false;
  4750. case 0xC3: // true
  4751. return true;
  4752. case 0xCA: // float 32
  4753. return get_number<float>();
  4754. case 0xCB: // float 64
  4755. return get_number<double>();
  4756. case 0xCC: // uint 8
  4757. return get_number<uint8_t>();
  4758. case 0xCD: // uint 16
  4759. return get_number<uint16_t>();
  4760. case 0xCE: // uint 32
  4761. return get_number<uint32_t>();
  4762. case 0xCF: // uint 64
  4763. return get_number<uint64_t>();
  4764. case 0xD0: // int 8
  4765. return get_number<int8_t>();
  4766. case 0xD1: // int 16
  4767. return get_number<int16_t>();
  4768. case 0xD2: // int 32
  4769. return get_number<int32_t>();
  4770. case 0xD3: // int 64
  4771. return get_number<int64_t>();
  4772. case 0xD9: // str 8
  4773. case 0xDA: // str 16
  4774. case 0xDB: // str 32
  4775. return get_msgpack_string();
  4776. case 0xDC: // array 16
  4777. {
  4778. return get_msgpack_array(get_number<uint16_t>());
  4779. }
  4780. case 0xDD: // array 32
  4781. {
  4782. return get_msgpack_array(get_number<uint32_t>());
  4783. }
  4784. case 0xDE: // map 16
  4785. {
  4786. return get_msgpack_object(get_number<uint16_t>());
  4787. }
  4788. case 0xDF: // map 32
  4789. {
  4790. return get_msgpack_object(get_number<uint32_t>());
  4791. }
  4792. // positive fixint
  4793. case 0xE0:
  4794. case 0xE1:
  4795. case 0xE2:
  4796. case 0xE3:
  4797. case 0xE4:
  4798. case 0xE5:
  4799. case 0xE6:
  4800. case 0xE7:
  4801. case 0xE8:
  4802. case 0xE9:
  4803. case 0xEA:
  4804. case 0xEB:
  4805. case 0xEC:
  4806. case 0xED:
  4807. case 0xEE:
  4808. case 0xEF:
  4809. case 0xF0:
  4810. case 0xF1:
  4811. case 0xF2:
  4812. case 0xF3:
  4813. case 0xF4:
  4814. case 0xF5:
  4815. case 0xF6:
  4816. case 0xF7:
  4817. case 0xF8:
  4818. case 0xF9:
  4819. case 0xFA:
  4820. case 0xFB:
  4821. case 0xFC:
  4822. case 0xFD:
  4823. case 0xFE:
  4824. case 0xFF:
  4825. return static_cast<int8_t>(current);
  4826. default: // anything else
  4827. {
  4828. std::stringstream ss;
  4829. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4830. JSON_THROW(parse_error::create(112, chars_read,
  4831. "error reading MessagePack; last byte: 0x" + ss.str()));
  4832. }
  4833. }
  4834. }
  4835. /*!
  4836. @param[in] get_char whether a new character should be retrieved from the
  4837. input (true, default) or whether the last read
  4838. character should be considered instead
  4839. */
  4840. BasicJsonType parse_ubjson_internal(const bool get_char = true)
  4841. {
  4842. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  4843. }
  4844. /*!
  4845. @brief get next character from the input
  4846. This function provides the interface to the used input adapter. It does
  4847. not throw in case the input reached EOF, but returns a -'ve valued
  4848. `std::char_traits<char>::eof()` in that case.
  4849. @return character read from the input
  4850. */
  4851. int get()
  4852. {
  4853. ++chars_read;
  4854. return (current = ia->get_character());
  4855. }
  4856. /*!
  4857. @return character read from the input after ignoring all 'N' entries
  4858. */
  4859. int get_ignore_noop()
  4860. {
  4861. do
  4862. {
  4863. get();
  4864. }
  4865. while (current == 'N');
  4866. return current;
  4867. }
  4868. /*
  4869. @brief read a number from the input
  4870. @tparam NumberType the type of the number
  4871. @return number of type @a NumberType
  4872. @note This function needs to respect the system's endianess, because
  4873. bytes in CBOR and MessagePack are stored in network order (big
  4874. endian) and therefore need reordering on little endian systems.
  4875. @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
  4876. */
  4877. template<typename NumberType> NumberType get_number()
  4878. {
  4879. // step 1: read input into array with system's byte order
  4880. std::array<uint8_t, sizeof(NumberType)> vec;
  4881. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  4882. {
  4883. get();
  4884. unexpect_eof();
  4885. // reverse byte order prior to conversion if necessary
  4886. if (is_little_endian)
  4887. {
  4888. vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
  4889. }
  4890. else
  4891. {
  4892. vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
  4893. }
  4894. }
  4895. // step 2: convert array into number of type T and return
  4896. NumberType result;
  4897. std::memcpy(&result, vec.data(), sizeof(NumberType));
  4898. return result;
  4899. }
  4900. /*!
  4901. @brief create a string by reading characters from the input
  4902. @param[in] len number of bytes to read
  4903. @note We can not reserve @a len bytes for the result, because @a len
  4904. may be too large. Usually, @ref unexpect_eof() detects the end of
  4905. the input before we run out of string memory.
  4906. @return string created by reading @a len bytes
  4907. @throw parse_error.110 if input has less than @a len bytes
  4908. */
  4909. template<typename NumberType>
  4910. string_t get_string(const NumberType len)
  4911. {
  4912. string_t result;
  4913. std::generate_n(std::back_inserter(result), len, [this]()
  4914. {
  4915. get();
  4916. unexpect_eof();
  4917. return static_cast<char>(current);
  4918. });
  4919. return result;
  4920. }
  4921. /*!
  4922. @brief reads a CBOR string
  4923. This function first reads starting bytes to determine the expected
  4924. string length and then copies this number of bytes into a string.
  4925. Additionally, CBOR's strings with indefinite lengths are supported.
  4926. @return string
  4927. @throw parse_error.110 if input ended
  4928. @throw parse_error.113 if an unexpected byte is read
  4929. */
  4930. string_t get_cbor_string()
  4931. {
  4932. unexpect_eof();
  4933. switch (current)
  4934. {
  4935. // UTF-8 string (0x00..0x17 bytes follow)
  4936. case 0x60:
  4937. case 0x61:
  4938. case 0x62:
  4939. case 0x63:
  4940. case 0x64:
  4941. case 0x65:
  4942. case 0x66:
  4943. case 0x67:
  4944. case 0x68:
  4945. case 0x69:
  4946. case 0x6A:
  4947. case 0x6B:
  4948. case 0x6C:
  4949. case 0x6D:
  4950. case 0x6E:
  4951. case 0x6F:
  4952. case 0x70:
  4953. case 0x71:
  4954. case 0x72:
  4955. case 0x73:
  4956. case 0x74:
  4957. case 0x75:
  4958. case 0x76:
  4959. case 0x77:
  4960. {
  4961. return get_string(current & 0x1F);
  4962. }
  4963. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4964. {
  4965. return get_string(get_number<uint8_t>());
  4966. }
  4967. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4968. {
  4969. return get_string(get_number<uint16_t>());
  4970. }
  4971. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4972. {
  4973. return get_string(get_number<uint32_t>());
  4974. }
  4975. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4976. {
  4977. return get_string(get_number<uint64_t>());
  4978. }
  4979. case 0x7F: // UTF-8 string (indefinite length)
  4980. {
  4981. string_t result;
  4982. while (get() != 0xFF)
  4983. {
  4984. result.append(get_cbor_string());
  4985. }
  4986. return result;
  4987. }
  4988. default:
  4989. {
  4990. std::stringstream ss;
  4991. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4992. JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
  4993. }
  4994. }
  4995. }
  4996. template<typename NumberType>
  4997. BasicJsonType get_cbor_array(const NumberType len)
  4998. {
  4999. BasicJsonType result = value_t::array;
  5000. std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
  5001. {
  5002. return parse_cbor_internal();
  5003. });
  5004. return result;
  5005. }
  5006. template<typename NumberType>
  5007. BasicJsonType get_cbor_object(const NumberType len)
  5008. {
  5009. BasicJsonType result = value_t::object;
  5010. std::generate_n(std::inserter(*result.m_value.object,
  5011. result.m_value.object->end()),
  5012. len, [this]()
  5013. {
  5014. get();
  5015. auto key = get_cbor_string();
  5016. auto val = parse_cbor_internal();
  5017. return std::make_pair(std::move(key), std::move(val));
  5018. });
  5019. return result;
  5020. }
  5021. /*!
  5022. @brief reads a MessagePack string
  5023. This function first reads starting bytes to determine the expected
  5024. string length and then copies this number of bytes into a string.
  5025. @return string
  5026. @throw parse_error.110 if input ended
  5027. @throw parse_error.113 if an unexpected byte is read
  5028. */
  5029. string_t get_msgpack_string()
  5030. {
  5031. unexpect_eof();
  5032. switch (current)
  5033. {
  5034. // fixstr
  5035. case 0xA0:
  5036. case 0xA1:
  5037. case 0xA2:
  5038. case 0xA3:
  5039. case 0xA4:
  5040. case 0xA5:
  5041. case 0xA6:
  5042. case 0xA7:
  5043. case 0xA8:
  5044. case 0xA9:
  5045. case 0xAA:
  5046. case 0xAB:
  5047. case 0xAC:
  5048. case 0xAD:
  5049. case 0xAE:
  5050. case 0xAF:
  5051. case 0xB0:
  5052. case 0xB1:
  5053. case 0xB2:
  5054. case 0xB3:
  5055. case 0xB4:
  5056. case 0xB5:
  5057. case 0xB6:
  5058. case 0xB7:
  5059. case 0xB8:
  5060. case 0xB9:
  5061. case 0xBA:
  5062. case 0xBB:
  5063. case 0xBC:
  5064. case 0xBD:
  5065. case 0xBE:
  5066. case 0xBF:
  5067. {
  5068. return get_string(current & 0x1F);
  5069. }
  5070. case 0xD9: // str 8
  5071. {
  5072. return get_string(get_number<uint8_t>());
  5073. }
  5074. case 0xDA: // str 16
  5075. {
  5076. return get_string(get_number<uint16_t>());
  5077. }
  5078. case 0xDB: // str 32
  5079. {
  5080. return get_string(get_number<uint32_t>());
  5081. }
  5082. default:
  5083. {
  5084. std::stringstream ss;
  5085. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  5086. JSON_THROW(parse_error::create(113, chars_read,
  5087. "expected a MessagePack string; last byte: 0x" + ss.str()));
  5088. }
  5089. }
  5090. }
  5091. template<typename NumberType>
  5092. BasicJsonType get_msgpack_array(const NumberType len)
  5093. {
  5094. BasicJsonType result = value_t::array;
  5095. std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
  5096. {
  5097. return parse_msgpack_internal();
  5098. });
  5099. return result;
  5100. }
  5101. template<typename NumberType>
  5102. BasicJsonType get_msgpack_object(const NumberType len)
  5103. {
  5104. BasicJsonType result = value_t::object;
  5105. std::generate_n(std::inserter(*result.m_value.object,
  5106. result.m_value.object->end()),
  5107. len, [this]()
  5108. {
  5109. get();
  5110. auto key = get_msgpack_string();
  5111. auto val = parse_msgpack_internal();
  5112. return std::make_pair(std::move(key), std::move(val));
  5113. });
  5114. return result;
  5115. }
  5116. /*!
  5117. @brief reads a UBJSON string
  5118. This function is either called after reading the 'S' byte explicitly
  5119. indicating a string, or in case of an object key where the 'S' byte can be
  5120. left out.
  5121. @param[in] get_char whether a new character should be retrieved from the
  5122. input (true, default) or whether the last read
  5123. character should be considered instead
  5124. @return string
  5125. @throw parse_error.110 if input ended
  5126. @throw parse_error.113 if an unexpected byte is read
  5127. */
  5128. string_t get_ubjson_string(const bool get_char = true)
  5129. {
  5130. if (get_char)
  5131. {
  5132. get(); // TODO: may we ignore N here?
  5133. }
  5134. unexpect_eof();
  5135. switch (current)
  5136. {
  5137. case 'U':
  5138. return get_string(get_number<uint8_t>());
  5139. case 'i':
  5140. return get_string(get_number<int8_t>());
  5141. case 'I':
  5142. return get_string(get_number<int16_t>());
  5143. case 'l':
  5144. return get_string(get_number<int32_t>());
  5145. case 'L':
  5146. return get_string(get_number<int64_t>());
  5147. default:
  5148. std::stringstream ss;
  5149. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  5150. JSON_THROW(parse_error::create(113, chars_read,
  5151. "expected a UBJSON string; last byte: 0x" + ss.str()));
  5152. }
  5153. }
  5154. /*!
  5155. @brief determine the type and size for a container
  5156. In the optimized UBJSON format, a type and a size can be provided to allow
  5157. for a more compact representation.
  5158. @return pair of the size and the type
  5159. */
  5160. std::pair<std::size_t, int> get_ubjson_size_type()
  5161. {
  5162. std::size_t sz = string_t::npos;
  5163. int tc = 0;
  5164. get_ignore_noop();
  5165. if (current == '$')
  5166. {
  5167. tc = get(); // must not ignore 'N', because 'N' maybe the type
  5168. unexpect_eof();
  5169. get_ignore_noop();
  5170. if (current != '#')
  5171. {
  5172. std::stringstream ss;
  5173. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  5174. JSON_THROW(parse_error::create(112, chars_read,
  5175. "expected '#' after UBJSON type information; last byte: 0x" + ss.str()));
  5176. }
  5177. sz = parse_ubjson_internal();
  5178. }
  5179. else if (current == '#')
  5180. {
  5181. sz = parse_ubjson_internal();
  5182. }
  5183. return std::make_pair(sz, tc);
  5184. }
  5185. BasicJsonType get_ubjson_value(const int prefix)
  5186. {
  5187. switch (prefix)
  5188. {
  5189. case std::char_traits<char>::eof(): // EOF
  5190. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  5191. case 'T': // true
  5192. return true;
  5193. case 'F': // false
  5194. return false;
  5195. case 'Z': // null
  5196. return nullptr;
  5197. case 'U':
  5198. return get_number<uint8_t>();
  5199. case 'i':
  5200. return get_number<int8_t>();
  5201. case 'I':
  5202. return get_number<int16_t>();
  5203. case 'l':
  5204. return get_number<int32_t>();
  5205. case 'L':
  5206. return get_number<int64_t>();
  5207. case 'd':
  5208. return get_number<float>();
  5209. case 'D':
  5210. return get_number<double>();
  5211. case 'C': // char
  5212. {
  5213. get();
  5214. unexpect_eof();
  5215. if (JSON_UNLIKELY(current > 127))
  5216. {
  5217. std::stringstream ss;
  5218. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  5219. JSON_THROW(parse_error::create(113, chars_read,
  5220. "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + ss.str()));
  5221. }
  5222. return string_t(1, static_cast<char>(current));
  5223. }
  5224. case 'S': // string
  5225. return get_ubjson_string();
  5226. case '[': // array
  5227. return get_ubjson_array();
  5228. case '{': // object
  5229. return get_ubjson_object();
  5230. default: // anything else
  5231. std::stringstream ss;
  5232. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  5233. JSON_THROW(parse_error::create(112, chars_read,
  5234. "error reading UBJSON; last byte: 0x" + ss.str()));
  5235. }
  5236. }
  5237. BasicJsonType get_ubjson_array()
  5238. {
  5239. BasicJsonType result = value_t::array;
  5240. const auto size_and_type = get_ubjson_size_type();
  5241. if (size_and_type.first != string_t::npos)
  5242. {
  5243. if (JSON_UNLIKELY(size_and_type.first > result.max_size()))
  5244. {
  5245. JSON_THROW(out_of_range::create(408,
  5246. "excessive array size: " + std::to_string(size_and_type.first)));
  5247. }
  5248. if (size_and_type.second != 0)
  5249. {
  5250. if (size_and_type.second != 'N')
  5251. {
  5252. std::generate_n(std::back_inserter(*result.m_value.array),
  5253. size_and_type.first, [this, size_and_type]()
  5254. {
  5255. return get_ubjson_value(size_and_type.second);
  5256. });
  5257. }
  5258. }
  5259. else
  5260. {
  5261. std::generate_n(std::back_inserter(*result.m_value.array),
  5262. size_and_type.first, [this]()
  5263. {
  5264. return parse_ubjson_internal();
  5265. });
  5266. }
  5267. }
  5268. else
  5269. {
  5270. while (current != ']')
  5271. {
  5272. result.push_back(parse_ubjson_internal(false));
  5273. get_ignore_noop();
  5274. }
  5275. }
  5276. return result;
  5277. }
  5278. BasicJsonType get_ubjson_object()
  5279. {
  5280. BasicJsonType result = value_t::object;
  5281. const auto size_and_type = get_ubjson_size_type();
  5282. if (size_and_type.first != string_t::npos)
  5283. {
  5284. if (JSON_UNLIKELY(size_and_type.first > result.max_size()))
  5285. {
  5286. JSON_THROW(out_of_range::create(408,
  5287. "excessive object size: " + std::to_string(size_and_type.first)));
  5288. }
  5289. if (size_and_type.second != 0)
  5290. {
  5291. std::generate_n(std::inserter(*result.m_value.object,
  5292. result.m_value.object->end()),
  5293. size_and_type.first, [this, size_and_type]()
  5294. {
  5295. auto key = get_ubjson_string();
  5296. auto val = get_ubjson_value(size_and_type.second);
  5297. return std::make_pair(std::move(key), std::move(val));
  5298. });
  5299. }
  5300. else
  5301. {
  5302. std::generate_n(std::inserter(*result.m_value.object,
  5303. result.m_value.object->end()),
  5304. size_and_type.first, [this]()
  5305. {
  5306. auto key = get_ubjson_string();
  5307. auto val = parse_ubjson_internal();
  5308. return std::make_pair(std::move(key), std::move(val));
  5309. });
  5310. }
  5311. }
  5312. else
  5313. {
  5314. while (current != '}')
  5315. {
  5316. auto key = get_ubjson_string(false);
  5317. result[std::move(key)] = parse_ubjson_internal();
  5318. get_ignore_noop();
  5319. }
  5320. }
  5321. return result;
  5322. }
  5323. /*!
  5324. @brief throw if end of input is not reached
  5325. @throw parse_error.110 if input not ended
  5326. */
  5327. void expect_eof() const
  5328. {
  5329. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  5330. {
  5331. JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
  5332. }
  5333. }
  5334. /*!
  5335. @briefthrow if end of input is reached
  5336. @throw parse_error.110 if input ended
  5337. */
  5338. void unexpect_eof() const
  5339. {
  5340. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  5341. {
  5342. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  5343. }
  5344. }
  5345. private:
  5346. /// input adapter
  5347. input_adapter_t ia = nullptr;
  5348. /// the current character
  5349. int current = std::char_traits<char>::eof();
  5350. /// the number of characters read
  5351. std::size_t chars_read = 0;
  5352. /// whether we can assume little endianess
  5353. const bool is_little_endian = little_endianess();
  5354. };
  5355. }
  5356. }
  5357. // #include <nlohmann/detail/output/binary_writer.hpp>
  5358. #include <algorithm> // reverse
  5359. #include <array> // array
  5360. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  5361. #include <cstring> // memcpy
  5362. #include <limits> // numeric_limits
  5363. // #include <nlohmann/detail/input/binary_reader.hpp>
  5364. // #include <nlohmann/detail/output/output_adapters.hpp>
  5365. namespace nlohmann
  5366. {
  5367. namespace detail
  5368. {
  5369. ///////////////////
  5370. // binary writer //
  5371. ///////////////////
  5372. /*!
  5373. @brief serialization to CBOR and MessagePack values
  5374. */
  5375. template<typename BasicJsonType, typename CharType>
  5376. class binary_writer
  5377. {
  5378. public:
  5379. /*!
  5380. @brief create a binary writer
  5381. @param[in] adapter output adapter to write to
  5382. */
  5383. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  5384. {
  5385. assert(oa);
  5386. }
  5387. /*!
  5388. @brief[in] j JSON value to serialize
  5389. */
  5390. void write_cbor(const BasicJsonType& j)
  5391. {
  5392. switch (j.type())
  5393. {
  5394. case value_t::null:
  5395. {
  5396. oa->write_character(static_cast<CharType>(0xF6));
  5397. break;
  5398. }
  5399. case value_t::boolean:
  5400. {
  5401. oa->write_character(j.m_value.boolean
  5402. ? static_cast<CharType>(0xF5)
  5403. : static_cast<CharType>(0xF4));
  5404. break;
  5405. }
  5406. case value_t::number_integer:
  5407. {
  5408. if (j.m_value.number_integer >= 0)
  5409. {
  5410. // CBOR does not differentiate between positive signed
  5411. // integers and unsigned integers. Therefore, we used the
  5412. // code from the value_t::number_unsigned case here.
  5413. if (j.m_value.number_integer <= 0x17)
  5414. {
  5415. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5416. }
  5417. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  5418. {
  5419. oa->write_character(static_cast<CharType>(0x18));
  5420. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5421. }
  5422. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  5423. {
  5424. oa->write_character(static_cast<CharType>(0x19));
  5425. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5426. }
  5427. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  5428. {
  5429. oa->write_character(static_cast<CharType>(0x1A));
  5430. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5431. }
  5432. else
  5433. {
  5434. oa->write_character(static_cast<CharType>(0x1B));
  5435. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5436. }
  5437. }
  5438. else
  5439. {
  5440. // The conversions below encode the sign in the first
  5441. // byte, and the value is converted to a positive number.
  5442. const auto positive_number = -1 - j.m_value.number_integer;
  5443. if (j.m_value.number_integer >= -24)
  5444. {
  5445. write_number(static_cast<uint8_t>(0x20 + positive_number));
  5446. }
  5447. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  5448. {
  5449. oa->write_character(static_cast<CharType>(0x38));
  5450. write_number(static_cast<uint8_t>(positive_number));
  5451. }
  5452. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  5453. {
  5454. oa->write_character(static_cast<CharType>(0x39));
  5455. write_number(static_cast<uint16_t>(positive_number));
  5456. }
  5457. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  5458. {
  5459. oa->write_character(static_cast<CharType>(0x3A));
  5460. write_number(static_cast<uint32_t>(positive_number));
  5461. }
  5462. else
  5463. {
  5464. oa->write_character(static_cast<CharType>(0x3B));
  5465. write_number(static_cast<uint64_t>(positive_number));
  5466. }
  5467. }
  5468. break;
  5469. }
  5470. case value_t::number_unsigned:
  5471. {
  5472. if (j.m_value.number_unsigned <= 0x17)
  5473. {
  5474. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  5475. }
  5476. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5477. {
  5478. oa->write_character(static_cast<CharType>(0x18));
  5479. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  5480. }
  5481. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5482. {
  5483. oa->write_character(static_cast<CharType>(0x19));
  5484. write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
  5485. }
  5486. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5487. {
  5488. oa->write_character(static_cast<CharType>(0x1A));
  5489. write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
  5490. }
  5491. else
  5492. {
  5493. oa->write_character(static_cast<CharType>(0x1B));
  5494. write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
  5495. }
  5496. break;
  5497. }
  5498. case value_t::number_float: // Double-Precision Float
  5499. {
  5500. oa->write_character(static_cast<CharType>(0xFB));
  5501. write_number(j.m_value.number_float);
  5502. break;
  5503. }
  5504. case value_t::string:
  5505. {
  5506. // step 1: write control byte and the string length
  5507. const auto N = j.m_value.string->size();
  5508. if (N <= 0x17)
  5509. {
  5510. write_number(static_cast<uint8_t>(0x60 + N));
  5511. }
  5512. else if (N <= (std::numeric_limits<uint8_t>::max)())
  5513. {
  5514. oa->write_character(static_cast<CharType>(0x78));
  5515. write_number(static_cast<uint8_t>(N));
  5516. }
  5517. else if (N <= (std::numeric_limits<uint16_t>::max)())
  5518. {
  5519. oa->write_character(static_cast<CharType>(0x79));
  5520. write_number(static_cast<uint16_t>(N));
  5521. }
  5522. else if (N <= (std::numeric_limits<uint32_t>::max)())
  5523. {
  5524. oa->write_character(static_cast<CharType>(0x7A));
  5525. write_number(static_cast<uint32_t>(N));
  5526. }
  5527. // LCOV_EXCL_START
  5528. else if (N <= (std::numeric_limits<uint64_t>::max)())
  5529. {
  5530. oa->write_character(static_cast<CharType>(0x7B));
  5531. write_number(static_cast<uint64_t>(N));
  5532. }
  5533. // LCOV_EXCL_STOP
  5534. // step 2: write the string
  5535. oa->write_characters(
  5536. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  5537. j.m_value.string->size());
  5538. break;
  5539. }
  5540. case value_t::array:
  5541. {
  5542. // step 1: write control byte and the array size
  5543. const auto N = j.m_value.array->size();
  5544. if (N <= 0x17)
  5545. {
  5546. write_number(static_cast<uint8_t>(0x80 + N));
  5547. }
  5548. else if (N <= (std::numeric_limits<uint8_t>::max)())
  5549. {
  5550. oa->write_character(static_cast<CharType>(0x98));
  5551. write_number(static_cast<uint8_t>(N));
  5552. }
  5553. else if (N <= (std::numeric_limits<uint16_t>::max)())
  5554. {
  5555. oa->write_character(static_cast<CharType>(0x99));
  5556. write_number(static_cast<uint16_t>(N));
  5557. }
  5558. else if (N <= (std::numeric_limits<uint32_t>::max)())
  5559. {
  5560. oa->write_character(static_cast<CharType>(0x9A));
  5561. write_number(static_cast<uint32_t>(N));
  5562. }
  5563. // LCOV_EXCL_START
  5564. else if (N <= (std::numeric_limits<uint64_t>::max)())
  5565. {
  5566. oa->write_character(static_cast<CharType>(0x9B));
  5567. write_number(static_cast<uint64_t>(N));
  5568. }
  5569. // LCOV_EXCL_STOP
  5570. // step 2: write each element
  5571. for (const auto& el : *j.m_value.array)
  5572. {
  5573. write_cbor(el);
  5574. }
  5575. break;
  5576. }
  5577. case value_t::object:
  5578. {
  5579. // step 1: write control byte and the object size
  5580. const auto N = j.m_value.object->size();
  5581. if (N <= 0x17)
  5582. {
  5583. write_number(static_cast<uint8_t>(0xA0 + N));
  5584. }
  5585. else if (N <= (std::numeric_limits<uint8_t>::max)())
  5586. {
  5587. oa->write_character(static_cast<CharType>(0xB8));
  5588. write_number(static_cast<uint8_t>(N));
  5589. }
  5590. else if (N <= (std::numeric_limits<uint16_t>::max)())
  5591. {
  5592. oa->write_character(static_cast<CharType>(0xB9));
  5593. write_number(static_cast<uint16_t>(N));
  5594. }
  5595. else if (N <= (std::numeric_limits<uint32_t>::max)())
  5596. {
  5597. oa->write_character(static_cast<CharType>(0xBA));
  5598. write_number(static_cast<uint32_t>(N));
  5599. }
  5600. // LCOV_EXCL_START
  5601. else if (N <= (std::numeric_limits<uint64_t>::max)())
  5602. {
  5603. oa->write_character(static_cast<CharType>(0xBB));
  5604. write_number(static_cast<uint64_t>(N));
  5605. }
  5606. // LCOV_EXCL_STOP
  5607. // step 2: write each element
  5608. for (const auto& el : *j.m_value.object)
  5609. {
  5610. write_cbor(el.first);
  5611. write_cbor(el.second);
  5612. }
  5613. break;
  5614. }
  5615. default:
  5616. break;
  5617. }
  5618. }
  5619. /*!
  5620. @brief[in] j JSON value to serialize
  5621. */
  5622. void write_msgpack(const BasicJsonType& j)
  5623. {
  5624. switch (j.type())
  5625. {
  5626. case value_t::null: // nil
  5627. {
  5628. oa->write_character(static_cast<CharType>(0xC0));
  5629. break;
  5630. }
  5631. case value_t::boolean: // true and false
  5632. {
  5633. oa->write_character(j.m_value.boolean
  5634. ? static_cast<CharType>(0xC3)
  5635. : static_cast<CharType>(0xC2));
  5636. break;
  5637. }
  5638. case value_t::number_integer:
  5639. {
  5640. if (j.m_value.number_integer >= 0)
  5641. {
  5642. // MessagePack does not differentiate between positive
  5643. // signed integers and unsigned integers. Therefore, we used
  5644. // the code from the value_t::number_unsigned case here.
  5645. if (j.m_value.number_unsigned < 128)
  5646. {
  5647. // positive fixnum
  5648. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5649. }
  5650. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5651. {
  5652. // uint 8
  5653. oa->write_character(static_cast<CharType>(0xCC));
  5654. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5655. }
  5656. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5657. {
  5658. // uint 16
  5659. oa->write_character(static_cast<CharType>(0xCD));
  5660. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5661. }
  5662. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5663. {
  5664. // uint 32
  5665. oa->write_character(static_cast<CharType>(0xCE));
  5666. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5667. }
  5668. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  5669. {
  5670. // uint 64
  5671. oa->write_character(static_cast<CharType>(0xCF));
  5672. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5673. }
  5674. }
  5675. else
  5676. {
  5677. if (j.m_value.number_integer >= -32)
  5678. {
  5679. // negative fixnum
  5680. write_number(static_cast<int8_t>(j.m_value.number_integer));
  5681. }
  5682. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
  5683. j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  5684. {
  5685. // int 8
  5686. oa->write_character(static_cast<CharType>(0xD0));
  5687. write_number(static_cast<int8_t>(j.m_value.number_integer));
  5688. }
  5689. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
  5690. j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  5691. {
  5692. // int 16
  5693. oa->write_character(static_cast<CharType>(0xD1));
  5694. write_number(static_cast<int16_t>(j.m_value.number_integer));
  5695. }
  5696. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
  5697. j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  5698. {
  5699. // int 32
  5700. oa->write_character(static_cast<CharType>(0xD2));
  5701. write_number(static_cast<int32_t>(j.m_value.number_integer));
  5702. }
  5703. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
  5704. j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  5705. {
  5706. // int 64
  5707. oa->write_character(static_cast<CharType>(0xD3));
  5708. write_number(static_cast<int64_t>(j.m_value.number_integer));
  5709. }
  5710. }
  5711. break;
  5712. }
  5713. case value_t::number_unsigned:
  5714. {
  5715. if (j.m_value.number_unsigned < 128)
  5716. {
  5717. // positive fixnum
  5718. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5719. }
  5720. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5721. {
  5722. // uint 8
  5723. oa->write_character(static_cast<CharType>(0xCC));
  5724. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5725. }
  5726. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5727. {
  5728. // uint 16
  5729. oa->write_character(static_cast<CharType>(0xCD));
  5730. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5731. }
  5732. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5733. {
  5734. // uint 32
  5735. oa->write_character(static_cast<CharType>(0xCE));
  5736. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5737. }
  5738. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  5739. {
  5740. // uint 64
  5741. oa->write_character(static_cast<CharType>(0xCF));
  5742. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5743. }
  5744. break;
  5745. }
  5746. case value_t::number_float: // float 64
  5747. {
  5748. oa->write_character(static_cast<CharType>(0xCB));
  5749. write_number(j.m_value.number_float);
  5750. break;
  5751. }
  5752. case value_t::string:
  5753. {
  5754. // step 1: write control byte and the string length
  5755. const auto N = j.m_value.string->size();
  5756. if (N <= 31)
  5757. {
  5758. // fixstr
  5759. write_number(static_cast<uint8_t>(0xA0 | N));
  5760. }
  5761. else if (N <= (std::numeric_limits<uint8_t>::max)())
  5762. {
  5763. // str 8
  5764. oa->write_character(static_cast<CharType>(0xD9));
  5765. write_number(static_cast<uint8_t>(N));
  5766. }
  5767. else if (N <= (std::numeric_limits<uint16_t>::max)())
  5768. {
  5769. // str 16
  5770. oa->write_character(static_cast<CharType>(0xDA));
  5771. write_number(static_cast<uint16_t>(N));
  5772. }
  5773. else if (N <= (std::numeric_limits<uint32_t>::max)())
  5774. {
  5775. // str 32
  5776. oa->write_character(static_cast<CharType>(0xDB));
  5777. write_number(static_cast<uint32_t>(N));
  5778. }
  5779. // step 2: write the string
  5780. oa->write_characters(
  5781. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  5782. j.m_value.string->size());
  5783. break;
  5784. }
  5785. case value_t::array:
  5786. {
  5787. // step 1: write control byte and the array size
  5788. const auto N = j.m_value.array->size();
  5789. if (N <= 15)
  5790. {
  5791. // fixarray
  5792. write_number(static_cast<uint8_t>(0x90 | N));
  5793. }
  5794. else if (N <= (std::numeric_limits<uint16_t>::max)())
  5795. {
  5796. // array 16
  5797. oa->write_character(static_cast<CharType>(0xDC));
  5798. write_number(static_cast<uint16_t>(N));
  5799. }
  5800. else if (N <= (std::numeric_limits<uint32_t>::max)())
  5801. {
  5802. // array 32
  5803. oa->write_character(static_cast<CharType>(0xDD));
  5804. write_number(static_cast<uint32_t>(N));
  5805. }
  5806. // step 2: write each element
  5807. for (const auto& el : *j.m_value.array)
  5808. {
  5809. write_msgpack(el);
  5810. }
  5811. break;
  5812. }
  5813. case value_t::object:
  5814. {
  5815. // step 1: write control byte and the object size
  5816. const auto N = j.m_value.object->size();
  5817. if (N <= 15)
  5818. {
  5819. // fixmap
  5820. write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
  5821. }
  5822. else if (N <= (std::numeric_limits<uint16_t>::max)())
  5823. {
  5824. // map 16
  5825. oa->write_character(static_cast<CharType>(0xDE));
  5826. write_number(static_cast<uint16_t>(N));
  5827. }
  5828. else if (N <= (std::numeric_limits<uint32_t>::max)())
  5829. {
  5830. // map 32
  5831. oa->write_character(static_cast<CharType>(0xDF));
  5832. write_number(static_cast<uint32_t>(N));
  5833. }
  5834. // step 2: write each element
  5835. for (const auto& el : *j.m_value.object)
  5836. {
  5837. write_msgpack(el.first);
  5838. write_msgpack(el.second);
  5839. }
  5840. break;
  5841. }
  5842. default:
  5843. break;
  5844. }
  5845. }
  5846. /*!
  5847. @param[in] j JSON value to serialize
  5848. @param[in] use_count whether to use '#' prefixes (optimized format)
  5849. @param[in] use_type whether to use '$' prefixes (optimized format)
  5850. @param[in] add_prefix whether prefixes need to be used for this value
  5851. */
  5852. void write_ubjson(const BasicJsonType& j, const bool use_count,
  5853. const bool use_type, const bool add_prefix = true)
  5854. {
  5855. switch (j.type())
  5856. {
  5857. case value_t::null:
  5858. {
  5859. if (add_prefix)
  5860. {
  5861. oa->write_character(static_cast<CharType>('Z'));
  5862. }
  5863. break;
  5864. }
  5865. case value_t::boolean:
  5866. {
  5867. if (add_prefix)
  5868. oa->write_character(j.m_value.boolean
  5869. ? static_cast<CharType>('T')
  5870. : static_cast<CharType>('F'));
  5871. break;
  5872. }
  5873. case value_t::number_integer:
  5874. {
  5875. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  5876. break;
  5877. }
  5878. case value_t::number_unsigned:
  5879. {
  5880. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  5881. break;
  5882. }
  5883. case value_t::number_float:
  5884. {
  5885. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  5886. break;
  5887. }
  5888. case value_t::string:
  5889. {
  5890. if (add_prefix)
  5891. {
  5892. oa->write_character(static_cast<CharType>('S'));
  5893. }
  5894. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  5895. oa->write_characters(
  5896. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  5897. j.m_value.string->size());
  5898. break;
  5899. }
  5900. case value_t::array:
  5901. {
  5902. if (add_prefix)
  5903. {
  5904. oa->write_character(static_cast<CharType>('['));
  5905. }
  5906. bool prefix_required = true;
  5907. if (use_type and not j.m_value.array->empty())
  5908. {
  5909. assert(use_count);
  5910. const char first_prefix = ubjson_prefix(j.front());
  5911. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  5912. [this, first_prefix](const BasicJsonType & v)
  5913. {
  5914. return ubjson_prefix(v) == first_prefix;
  5915. });
  5916. if (same_prefix)
  5917. {
  5918. prefix_required = false;
  5919. oa->write_character(static_cast<CharType>('$'));
  5920. oa->write_character(static_cast<CharType>(first_prefix));
  5921. }
  5922. }
  5923. if (use_count)
  5924. {
  5925. oa->write_character(static_cast<CharType>('#'));
  5926. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  5927. }
  5928. for (const auto& el : *j.m_value.array)
  5929. {
  5930. write_ubjson(el, use_count, use_type, prefix_required);
  5931. }
  5932. if (not use_count)
  5933. {
  5934. oa->write_character(static_cast<CharType>(']'));
  5935. }
  5936. break;
  5937. }
  5938. case value_t::object:
  5939. {
  5940. if (add_prefix)
  5941. {
  5942. oa->write_character(static_cast<CharType>('{'));
  5943. }
  5944. bool prefix_required = true;
  5945. if (use_type and not j.m_value.object->empty())
  5946. {
  5947. assert(use_count);
  5948. const char first_prefix = ubjson_prefix(j.front());
  5949. const bool same_prefix = std::all_of(j.begin(), j.end(),
  5950. [this, first_prefix](const BasicJsonType & v)
  5951. {
  5952. return ubjson_prefix(v) == first_prefix;
  5953. });
  5954. if (same_prefix)
  5955. {
  5956. prefix_required = false;
  5957. oa->write_character(static_cast<CharType>('$'));
  5958. oa->write_character(static_cast<CharType>(first_prefix));
  5959. }
  5960. }
  5961. if (use_count)
  5962. {
  5963. oa->write_character(static_cast<CharType>('#'));
  5964. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  5965. }
  5966. for (const auto& el : *j.m_value.object)
  5967. {
  5968. write_number_with_ubjson_prefix(el.first.size(), true);
  5969. oa->write_characters(
  5970. reinterpret_cast<const CharType*>(el.first.c_str()),
  5971. el.first.size());
  5972. write_ubjson(el.second, use_count, use_type, prefix_required);
  5973. }
  5974. if (not use_count)
  5975. {
  5976. oa->write_character(static_cast<CharType>('}'));
  5977. }
  5978. break;
  5979. }
  5980. default:
  5981. break;
  5982. }
  5983. }
  5984. private:
  5985. /*
  5986. @brief write a number to output input
  5987. @param[in] n number of type @a NumberType
  5988. @tparam NumberType the type of the number
  5989. @note This function needs to respect the system's endianess, because bytes
  5990. in CBOR, MessagePack, and UBJSON are stored in network order (big
  5991. endian) and therefore need reordering on little endian systems.
  5992. */
  5993. template<typename NumberType>
  5994. void write_number(const NumberType n)
  5995. {
  5996. // step 1: write number to array of length NumberType
  5997. std::array<CharType, sizeof(NumberType)> vec;
  5998. std::memcpy(vec.data(), &n, sizeof(NumberType));
  5999. // step 2: write array to output (with possible reordering)
  6000. if (is_little_endian)
  6001. {
  6002. // reverse byte order prior to conversion if necessary
  6003. std::reverse(vec.begin(), vec.end());
  6004. }
  6005. oa->write_characters(vec.data(), sizeof(NumberType));
  6006. }
  6007. // UBJSON: write number (floating point)
  6008. template<typename NumberType, typename std::enable_if<
  6009. std::is_floating_point<NumberType>::value, int>::type = 0>
  6010. void write_number_with_ubjson_prefix(const NumberType n,
  6011. const bool add_prefix)
  6012. {
  6013. if (add_prefix)
  6014. {
  6015. oa->write_character(static_cast<CharType>('D')); // float64
  6016. }
  6017. write_number(n);
  6018. }
  6019. // UBJSON: write number (unsigned integer)
  6020. template<typename NumberType, typename std::enable_if<
  6021. std::is_unsigned<NumberType>::value, int>::type = 0>
  6022. void write_number_with_ubjson_prefix(const NumberType n,
  6023. const bool add_prefix)
  6024. {
  6025. if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)()))
  6026. {
  6027. if (add_prefix)
  6028. {
  6029. oa->write_character(static_cast<CharType>('i')); // int8
  6030. }
  6031. write_number(static_cast<uint8_t>(n));
  6032. }
  6033. else if (n <= (std::numeric_limits<uint8_t>::max)())
  6034. {
  6035. if (add_prefix)
  6036. {
  6037. oa->write_character(static_cast<CharType>('U')); // uint8
  6038. }
  6039. write_number(static_cast<uint8_t>(n));
  6040. }
  6041. else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)()))
  6042. {
  6043. if (add_prefix)
  6044. {
  6045. oa->write_character(static_cast<CharType>('I')); // int16
  6046. }
  6047. write_number(static_cast<int16_t>(n));
  6048. }
  6049. else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
  6050. {
  6051. if (add_prefix)
  6052. {
  6053. oa->write_character(static_cast<CharType>('l')); // int32
  6054. }
  6055. write_number(static_cast<int32_t>(n));
  6056. }
  6057. else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
  6058. {
  6059. if (add_prefix)
  6060. {
  6061. oa->write_character(static_cast<CharType>('L')); // int64
  6062. }
  6063. write_number(static_cast<int64_t>(n));
  6064. }
  6065. else
  6066. {
  6067. JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
  6068. }
  6069. }
  6070. // UBJSON: write number (signed integer)
  6071. template<typename NumberType, typename std::enable_if<
  6072. std::is_signed<NumberType>::value and
  6073. not std::is_floating_point<NumberType>::value, int>::type = 0>
  6074. void write_number_with_ubjson_prefix(const NumberType n,
  6075. const bool add_prefix)
  6076. {
  6077. if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
  6078. {
  6079. if (add_prefix)
  6080. {
  6081. oa->write_character(static_cast<CharType>('i')); // int8
  6082. }
  6083. write_number(static_cast<int8_t>(n));
  6084. }
  6085. else if (static_cast<int64_t>((std::numeric_limits<uint8_t>::min)()) <= n and n <= static_cast<int64_t>((std::numeric_limits<uint8_t>::max)()))
  6086. {
  6087. if (add_prefix)
  6088. {
  6089. oa->write_character(static_cast<CharType>('U')); // uint8
  6090. }
  6091. write_number(static_cast<uint8_t>(n));
  6092. }
  6093. else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)())
  6094. {
  6095. if (add_prefix)
  6096. {
  6097. oa->write_character(static_cast<CharType>('I')); // int16
  6098. }
  6099. write_number(static_cast<int16_t>(n));
  6100. }
  6101. else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)())
  6102. {
  6103. if (add_prefix)
  6104. {
  6105. oa->write_character(static_cast<CharType>('l')); // int32
  6106. }
  6107. write_number(static_cast<int32_t>(n));
  6108. }
  6109. else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)())
  6110. {
  6111. if (add_prefix)
  6112. {
  6113. oa->write_character(static_cast<CharType>('L')); // int64
  6114. }
  6115. write_number(static_cast<int64_t>(n));
  6116. }
  6117. // LCOV_EXCL_START
  6118. else
  6119. {
  6120. JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
  6121. }
  6122. // LCOV_EXCL_STOP
  6123. }
  6124. /*!
  6125. @brief determine the type prefix of container values
  6126. @note This function does not need to be 100% accurate when it comes to
  6127. integer limits. In case a number exceeds the limits of int64_t,
  6128. this will be detected by a later call to function
  6129. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  6130. value that does not fit the previous limits.
  6131. */
  6132. char ubjson_prefix(const BasicJsonType& j) const noexcept
  6133. {
  6134. switch (j.type())
  6135. {
  6136. case value_t::null:
  6137. return 'Z';
  6138. case value_t::boolean:
  6139. return j.m_value.boolean ? 'T' : 'F';
  6140. case value_t::number_integer:
  6141. {
  6142. if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  6143. {
  6144. return 'i';
  6145. }
  6146. else if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  6147. {
  6148. return 'U';
  6149. }
  6150. else if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  6151. {
  6152. return 'I';
  6153. }
  6154. else if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  6155. {
  6156. return 'l';
  6157. }
  6158. else // no check and assume int64_t (see note above)
  6159. {
  6160. return 'L';
  6161. }
  6162. }
  6163. case value_t::number_unsigned:
  6164. {
  6165. if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)())
  6166. {
  6167. return 'i';
  6168. }
  6169. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  6170. {
  6171. return 'U';
  6172. }
  6173. else if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)())
  6174. {
  6175. return 'I';
  6176. }
  6177. else if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)())
  6178. {
  6179. return 'l';
  6180. }
  6181. else // no check and assume int64_t (see note above)
  6182. {
  6183. return 'L';
  6184. }
  6185. }
  6186. case value_t::number_float:
  6187. return 'D';
  6188. case value_t::string:
  6189. return 'S';
  6190. case value_t::array:
  6191. return '[';
  6192. case value_t::object:
  6193. return '{';
  6194. default: // discarded values
  6195. return 'N';
  6196. }
  6197. }
  6198. private:
  6199. /// whether we can assume little endianess
  6200. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  6201. /// the output
  6202. output_adapter_t<CharType> oa = nullptr;
  6203. };
  6204. }
  6205. }
  6206. // #include <nlohmann/detail/output/serializer.hpp>
  6207. #include <algorithm> // reverse, remove, fill, find, none_of
  6208. #include <array> // array
  6209. #include <cassert> // assert
  6210. #include <ciso646> // and, or
  6211. #include <clocale> // localeconv, lconv
  6212. #include <cmath> // labs, isfinite, isnan, signbit
  6213. #include <cstddef> // size_t, ptrdiff_t
  6214. #include <cstdint> // uint8_t
  6215. #include <cstdio> // snprintf
  6216. #include <iomanip> // setfill
  6217. #include <iterator> // next
  6218. #include <limits> // numeric_limits
  6219. #include <string> // string
  6220. #include <sstream> // stringstream
  6221. #include <type_traits> // is_same
  6222. // #include <nlohmann/detail/exceptions.hpp>
  6223. // #include <nlohmann/detail/conversions/to_chars.hpp>
  6224. #include <cassert> // assert
  6225. #include <ciso646> // or, and, not
  6226. #include <cmath> // signbit, isfinite
  6227. #include <cstdint> // intN_t, uintN_t
  6228. #include <cstring> // memcpy, memmove
  6229. namespace nlohmann
  6230. {
  6231. namespace detail
  6232. {
  6233. /*!
  6234. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  6235. conversion.
  6236. This implementation is a slightly modified version of the reference
  6237. implementation which may be obtained from
  6238. http://florian.loitsch.com/publications (bench.tar.gz).
  6239. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  6240. For a detailed description of the algorithm see:
  6241. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  6242. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  6243. Language Design and Implementation, PLDI 2010
  6244. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  6245. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  6246. Design and Implementation, PLDI 1996
  6247. */
  6248. namespace dtoa_impl
  6249. {
  6250. template <typename Target, typename Source>
  6251. Target reinterpret_bits(const Source source)
  6252. {
  6253. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  6254. Target target;
  6255. std::memcpy(&target, &source, sizeof(Source));
  6256. return target;
  6257. }
  6258. struct diyfp // f * 2^e
  6259. {
  6260. static constexpr int kPrecision = 64; // = q
  6261. uint64_t f;
  6262. int e;
  6263. constexpr diyfp() noexcept : f(0), e(0) {}
  6264. constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  6265. /*!
  6266. @brief returns x - y
  6267. @pre x.e == y.e and x.f >= y.f
  6268. */
  6269. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  6270. {
  6271. assert(x.e == y.e);
  6272. assert(x.f >= y.f);
  6273. return diyfp(x.f - y.f, x.e);
  6274. }
  6275. /*!
  6276. @brief returns x * y
  6277. @note The result is rounded. (Only the upper q bits are returned.)
  6278. */
  6279. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  6280. {
  6281. static_assert(kPrecision == 64, "internal error");
  6282. // Computes:
  6283. // f = round((x.f * y.f) / 2^q)
  6284. // e = x.e + y.e + q
  6285. // Emulate the 64-bit * 64-bit multiplication:
  6286. //
  6287. // p = u * v
  6288. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  6289. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  6290. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  6291. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  6292. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  6293. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  6294. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  6295. //
  6296. // (Since Q might be larger than 2^32 - 1)
  6297. //
  6298. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  6299. //
  6300. // (Q_hi + H does not overflow a 64-bit int)
  6301. //
  6302. // = p_lo + 2^64 p_hi
  6303. const uint64_t u_lo = x.f & 0xFFFFFFFF;
  6304. const uint64_t u_hi = x.f >> 32;
  6305. const uint64_t v_lo = y.f & 0xFFFFFFFF;
  6306. const uint64_t v_hi = y.f >> 32;
  6307. const uint64_t p0 = u_lo * v_lo;
  6308. const uint64_t p1 = u_lo * v_hi;
  6309. const uint64_t p2 = u_hi * v_lo;
  6310. const uint64_t p3 = u_hi * v_hi;
  6311. const uint64_t p0_hi = p0 >> 32;
  6312. const uint64_t p1_lo = p1 & 0xFFFFFFFF;
  6313. const uint64_t p1_hi = p1 >> 32;
  6314. const uint64_t p2_lo = p2 & 0xFFFFFFFF;
  6315. const uint64_t p2_hi = p2 >> 32;
  6316. uint64_t Q = p0_hi + p1_lo + p2_lo;
  6317. // The full product might now be computed as
  6318. //
  6319. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  6320. // p_lo = p0_lo + (Q << 32)
  6321. //
  6322. // But in this particular case here, the full p_lo is not required.
  6323. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  6324. // Q_hi + 1 does not overflow).
  6325. Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
  6326. const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
  6327. return diyfp(h, x.e + y.e + 64);
  6328. }
  6329. /*!
  6330. @brief normalize x such that the significand is >= 2^(q-1)
  6331. @pre x.f != 0
  6332. */
  6333. static diyfp normalize(diyfp x) noexcept
  6334. {
  6335. assert(x.f != 0);
  6336. while ((x.f >> 63) == 0)
  6337. {
  6338. x.f <<= 1;
  6339. x.e--;
  6340. }
  6341. return x;
  6342. }
  6343. /*!
  6344. @brief normalize x such that the result has the exponent E
  6345. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  6346. */
  6347. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  6348. {
  6349. const int delta = x.e - target_exponent;
  6350. assert(delta >= 0);
  6351. assert(((x.f << delta) >> delta) == x.f);
  6352. return diyfp(x.f << delta, target_exponent);
  6353. }
  6354. };
  6355. struct boundaries
  6356. {
  6357. diyfp w;
  6358. diyfp minus;
  6359. diyfp plus;
  6360. };
  6361. /*!
  6362. Compute the (normalized) diyfp representing the input number 'value' and its
  6363. boundaries.
  6364. @pre value must be finite and positive
  6365. */
  6366. template <typename FloatType>
  6367. boundaries compute_boundaries(FloatType value)
  6368. {
  6369. assert(std::isfinite(value));
  6370. assert(value > 0);
  6371. // Convert the IEEE representation into a diyfp.
  6372. //
  6373. // If v is denormal:
  6374. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  6375. // If v is normalized:
  6376. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  6377. static_assert(std::numeric_limits<FloatType>::is_iec559,
  6378. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  6379. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  6380. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  6381. constexpr int kMinExp = 1 - kBias;
  6382. constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  6383. using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
  6384. const uint64_t bits = reinterpret_bits<bits_type>(value);
  6385. const uint64_t E = bits >> (kPrecision - 1);
  6386. const uint64_t F = bits & (kHiddenBit - 1);
  6387. const bool is_denormal = (E == 0);
  6388. const diyfp v = is_denormal
  6389. ? diyfp(F, kMinExp)
  6390. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  6391. // Compute the boundaries m- and m+ of the floating-point value
  6392. // v = f * 2^e.
  6393. //
  6394. // Determine v- and v+, the floating-point predecessor and successor if v,
  6395. // respectively.
  6396. //
  6397. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  6398. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  6399. //
  6400. // v+ = v + 2^e
  6401. //
  6402. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  6403. // between m- and m+ round to v, regardless of how the input rounding
  6404. // algorithm breaks ties.
  6405. //
  6406. // ---+-------------+-------------+-------------+-------------+--- (A)
  6407. // v- m- v m+ v+
  6408. //
  6409. // -----------------+------+------+-------------+-------------+--- (B)
  6410. // v- m- v m+ v+
  6411. const bool lower_boundary_is_closer = (F == 0 and E > 1);
  6412. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  6413. const diyfp m_minus = lower_boundary_is_closer
  6414. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  6415. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  6416. // Determine the normalized w+ = m+.
  6417. const diyfp w_plus = diyfp::normalize(m_plus);
  6418. // Determine w- = m- such that e_(w-) = e_(w+).
  6419. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  6420. return {diyfp::normalize(v), w_minus, w_plus};
  6421. }
  6422. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  6423. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  6424. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  6425. //
  6426. // alpha <= e = e_c + e_w + q <= gamma
  6427. //
  6428. // or
  6429. //
  6430. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  6431. // <= f_c * f_w * 2^gamma
  6432. //
  6433. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  6434. //
  6435. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  6436. //
  6437. // or
  6438. //
  6439. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  6440. //
  6441. // The choice of (alpha,gamma) determines the size of the table and the form of
  6442. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  6443. // in practice:
  6444. //
  6445. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  6446. // processed independently: An integral part p1, and a fractional part p2:
  6447. //
  6448. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  6449. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  6450. // = p1 + p2 * 2^e
  6451. //
  6452. // The conversion of p1 into decimal form requires a series of divisions and
  6453. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  6454. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  6455. // achieved by choosing
  6456. //
  6457. // -e >= 32 or e <= -32 := gamma
  6458. //
  6459. // In order to convert the fractional part
  6460. //
  6461. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  6462. //
  6463. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  6464. // d[-i] are extracted in order:
  6465. //
  6466. // (10 * p2) div 2^-e = d[-1]
  6467. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  6468. //
  6469. // The multiplication by 10 must not overflow. It is sufficient to choose
  6470. //
  6471. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  6472. //
  6473. // Since p2 = f mod 2^-e < 2^-e,
  6474. //
  6475. // -e <= 60 or e >= -60 := alpha
  6476. constexpr int kAlpha = -60;
  6477. constexpr int kGamma = -32;
  6478. struct cached_power // c = f * 2^e ~= 10^k
  6479. {
  6480. uint64_t f;
  6481. int e;
  6482. int k;
  6483. };
  6484. /*!
  6485. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  6486. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  6487. satisfies (Definition 3.2 from [1])
  6488. alpha <= e_c + e + q <= gamma.
  6489. */
  6490. inline cached_power get_cached_power_for_binary_exponent(int e)
  6491. {
  6492. // Now
  6493. //
  6494. // alpha <= e_c + e + q <= gamma (1)
  6495. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  6496. //
  6497. // and since the c's are normalized, 2^(q-1) <= f_c,
  6498. //
  6499. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  6500. // ==> 2^(alpha - e - 1) <= c
  6501. //
  6502. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  6503. //
  6504. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  6505. // = ceil( (alpha - e - 1) * log_10(2) )
  6506. //
  6507. // From the paper:
  6508. // "In theory the result of the procedure could be wrong since c is rounded,
  6509. // and the computation itself is approximated [...]. In practice, however,
  6510. // this simple function is sufficient."
  6511. //
  6512. // For IEEE double precision floating-point numbers converted into
  6513. // normalized diyfp's w = f * 2^e, with q = 64,
  6514. //
  6515. // e >= -1022 (min IEEE exponent)
  6516. // -52 (p - 1)
  6517. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  6518. // -11 (normalize the diyfp)
  6519. // = -1137
  6520. //
  6521. // and
  6522. //
  6523. // e <= +1023 (max IEEE exponent)
  6524. // -52 (p - 1)
  6525. // -11 (normalize the diyfp)
  6526. // = 960
  6527. //
  6528. // This binary exponent range [-1137,960] results in a decimal exponent
  6529. // range [-307,324]. One does not need to store a cached power for each
  6530. // k in this range. For each such k it suffices to find a cached power
  6531. // such that the exponent of the product lies in [alpha,gamma].
  6532. // This implies that the difference of the decimal exponents of adjacent
  6533. // table entries must be less than or equal to
  6534. //
  6535. // floor( (gamma - alpha) * log_10(2) ) = 8.
  6536. //
  6537. // (A smaller distance gamma-alpha would require a larger table.)
  6538. // NB:
  6539. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  6540. constexpr int kCachedPowersSize = 79;
  6541. constexpr int kCachedPowersMinDecExp = -300;
  6542. constexpr int kCachedPowersDecStep = 8;
  6543. static constexpr cached_power kCachedPowers[] =
  6544. {
  6545. { 0xAB70FE17C79AC6CA, -1060, -300 },
  6546. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  6547. { 0xBE5691EF416BD60C, -1007, -284 },
  6548. { 0x8DD01FAD907FFC3C, -980, -276 },
  6549. { 0xD3515C2831559A83, -954, -268 },
  6550. { 0x9D71AC8FADA6C9B5, -927, -260 },
  6551. { 0xEA9C227723EE8BCB, -901, -252 },
  6552. { 0xAECC49914078536D, -874, -244 },
  6553. { 0x823C12795DB6CE57, -847, -236 },
  6554. { 0xC21094364DFB5637, -821, -228 },
  6555. { 0x9096EA6F3848984F, -794, -220 },
  6556. { 0xD77485CB25823AC7, -768, -212 },
  6557. { 0xA086CFCD97BF97F4, -741, -204 },
  6558. { 0xEF340A98172AACE5, -715, -196 },
  6559. { 0xB23867FB2A35B28E, -688, -188 },
  6560. { 0x84C8D4DFD2C63F3B, -661, -180 },
  6561. { 0xC5DD44271AD3CDBA, -635, -172 },
  6562. { 0x936B9FCEBB25C996, -608, -164 },
  6563. { 0xDBAC6C247D62A584, -582, -156 },
  6564. { 0xA3AB66580D5FDAF6, -555, -148 },
  6565. { 0xF3E2F893DEC3F126, -529, -140 },
  6566. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  6567. { 0x87625F056C7C4A8B, -475, -124 },
  6568. { 0xC9BCFF6034C13053, -449, -116 },
  6569. { 0x964E858C91BA2655, -422, -108 },
  6570. { 0xDFF9772470297EBD, -396, -100 },
  6571. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  6572. { 0xF8A95FCF88747D94, -343, -84 },
  6573. { 0xB94470938FA89BCF, -316, -76 },
  6574. { 0x8A08F0F8BF0F156B, -289, -68 },
  6575. { 0xCDB02555653131B6, -263, -60 },
  6576. { 0x993FE2C6D07B7FAC, -236, -52 },
  6577. { 0xE45C10C42A2B3B06, -210, -44 },
  6578. { 0xAA242499697392D3, -183, -36 },
  6579. { 0xFD87B5F28300CA0E, -157, -28 },
  6580. { 0xBCE5086492111AEB, -130, -20 },
  6581. { 0x8CBCCC096F5088CC, -103, -12 },
  6582. { 0xD1B71758E219652C, -77, -4 },
  6583. { 0x9C40000000000000, -50, 4 },
  6584. { 0xE8D4A51000000000, -24, 12 },
  6585. { 0xAD78EBC5AC620000, 3, 20 },
  6586. { 0x813F3978F8940984, 30, 28 },
  6587. { 0xC097CE7BC90715B3, 56, 36 },
  6588. { 0x8F7E32CE7BEA5C70, 83, 44 },
  6589. { 0xD5D238A4ABE98068, 109, 52 },
  6590. { 0x9F4F2726179A2245, 136, 60 },
  6591. { 0xED63A231D4C4FB27, 162, 68 },
  6592. { 0xB0DE65388CC8ADA8, 189, 76 },
  6593. { 0x83C7088E1AAB65DB, 216, 84 },
  6594. { 0xC45D1DF942711D9A, 242, 92 },
  6595. { 0x924D692CA61BE758, 269, 100 },
  6596. { 0xDA01EE641A708DEA, 295, 108 },
  6597. { 0xA26DA3999AEF774A, 322, 116 },
  6598. { 0xF209787BB47D6B85, 348, 124 },
  6599. { 0xB454E4A179DD1877, 375, 132 },
  6600. { 0x865B86925B9BC5C2, 402, 140 },
  6601. { 0xC83553C5C8965D3D, 428, 148 },
  6602. { 0x952AB45CFA97A0B3, 455, 156 },
  6603. { 0xDE469FBD99A05FE3, 481, 164 },
  6604. { 0xA59BC234DB398C25, 508, 172 },
  6605. { 0xF6C69A72A3989F5C, 534, 180 },
  6606. { 0xB7DCBF5354E9BECE, 561, 188 },
  6607. { 0x88FCF317F22241E2, 588, 196 },
  6608. { 0xCC20CE9BD35C78A5, 614, 204 },
  6609. { 0x98165AF37B2153DF, 641, 212 },
  6610. { 0xE2A0B5DC971F303A, 667, 220 },
  6611. { 0xA8D9D1535CE3B396, 694, 228 },
  6612. { 0xFB9B7CD9A4A7443C, 720, 236 },
  6613. { 0xBB764C4CA7A44410, 747, 244 },
  6614. { 0x8BAB8EEFB6409C1A, 774, 252 },
  6615. { 0xD01FEF10A657842C, 800, 260 },
  6616. { 0x9B10A4E5E9913129, 827, 268 },
  6617. { 0xE7109BFBA19C0C9D, 853, 276 },
  6618. { 0xAC2820D9623BF429, 880, 284 },
  6619. { 0x80444B5E7AA7CF85, 907, 292 },
  6620. { 0xBF21E44003ACDD2D, 933, 300 },
  6621. { 0x8E679C2F5E44FF8F, 960, 308 },
  6622. { 0xD433179D9C8CB841, 986, 316 },
  6623. { 0x9E19DB92B4E31BA9, 1013, 324 },
  6624. };
  6625. // This computation gives exactly the same results for k as
  6626. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  6627. // for |e| <= 1500, but doesn't require floating-point operations.
  6628. // NB: log_10(2) ~= 78913 / 2^18
  6629. assert(e >= -1500);
  6630. assert(e <= 1500);
  6631. const int f = kAlpha - e - 1;
  6632. const int k = (f * 78913) / (1 << 18) + (f > 0);
  6633. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  6634. assert(index >= 0);
  6635. assert(index < kCachedPowersSize);
  6636. static_cast<void>(kCachedPowersSize); // Fix warning.
  6637. const cached_power cached = kCachedPowers[index];
  6638. assert(kAlpha <= cached.e + e + 64);
  6639. assert(kGamma >= cached.e + e + 64);
  6640. return cached;
  6641. }
  6642. /*!
  6643. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  6644. For n == 0, returns 1 and sets pow10 := 1.
  6645. */
  6646. inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
  6647. {
  6648. // LCOV_EXCL_START
  6649. if (n >= 1000000000)
  6650. {
  6651. pow10 = 1000000000;
  6652. return 10;
  6653. }
  6654. // LCOV_EXCL_STOP
  6655. else if (n >= 100000000)
  6656. {
  6657. pow10 = 100000000;
  6658. return 9;
  6659. }
  6660. else if (n >= 10000000)
  6661. {
  6662. pow10 = 10000000;
  6663. return 8;
  6664. }
  6665. else if (n >= 1000000)
  6666. {
  6667. pow10 = 1000000;
  6668. return 7;
  6669. }
  6670. else if (n >= 100000)
  6671. {
  6672. pow10 = 100000;
  6673. return 6;
  6674. }
  6675. else if (n >= 10000)
  6676. {
  6677. pow10 = 10000;
  6678. return 5;
  6679. }
  6680. else if (n >= 1000)
  6681. {
  6682. pow10 = 1000;
  6683. return 4;
  6684. }
  6685. else if (n >= 100)
  6686. {
  6687. pow10 = 100;
  6688. return 3;
  6689. }
  6690. else if (n >= 10)
  6691. {
  6692. pow10 = 10;
  6693. return 2;
  6694. }
  6695. else
  6696. {
  6697. pow10 = 1;
  6698. return 1;
  6699. }
  6700. }
  6701. inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
  6702. uint64_t rest, uint64_t ten_k)
  6703. {
  6704. assert(len >= 1);
  6705. assert(dist <= delta);
  6706. assert(rest <= delta);
  6707. assert(ten_k > 0);
  6708. // <--------------------------- delta ---->
  6709. // <---- dist --------->
  6710. // --------------[------------------+-------------------]--------------
  6711. // M- w M+
  6712. //
  6713. // ten_k
  6714. // <------>
  6715. // <---- rest ---->
  6716. // --------------[------------------+----+--------------]--------------
  6717. // w V
  6718. // = buf * 10^k
  6719. //
  6720. // ten_k represents a unit-in-the-last-place in the decimal representation
  6721. // stored in buf.
  6722. // Decrement buf by ten_k while this takes buf closer to w.
  6723. // The tests are written in this order to avoid overflow in unsigned
  6724. // integer arithmetic.
  6725. while (rest < dist
  6726. and delta - rest >= ten_k
  6727. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  6728. {
  6729. assert(buf[len - 1] != '0');
  6730. buf[len - 1]--;
  6731. rest += ten_k;
  6732. }
  6733. }
  6734. /*!
  6735. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  6736. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  6737. */
  6738. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  6739. diyfp M_minus, diyfp w, diyfp M_plus)
  6740. {
  6741. static_assert(kAlpha >= -60, "internal error");
  6742. static_assert(kGamma <= -32, "internal error");
  6743. // Generates the digits (and the exponent) of a decimal floating-point
  6744. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  6745. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  6746. //
  6747. // <--------------------------- delta ---->
  6748. // <---- dist --------->
  6749. // --------------[------------------+-------------------]--------------
  6750. // M- w M+
  6751. //
  6752. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  6753. // V is in [M-,M+].
  6754. assert(M_plus.e >= kAlpha);
  6755. assert(M_plus.e <= kGamma);
  6756. uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  6757. uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  6758. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  6759. //
  6760. // M+ = f * 2^e
  6761. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  6762. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  6763. // = p1 + p2 * 2^e
  6764. const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
  6765. uint32_t p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
  6766. uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  6767. // 1)
  6768. //
  6769. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  6770. assert(p1 > 0);
  6771. uint32_t pow10;
  6772. const int k = find_largest_pow10(p1, pow10);
  6773. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  6774. //
  6775. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  6776. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  6777. //
  6778. // M+ = p1 + p2 * 2^e
  6779. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  6780. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  6781. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  6782. //
  6783. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  6784. //
  6785. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  6786. //
  6787. // but stop as soon as
  6788. //
  6789. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  6790. int n = k;
  6791. while (n > 0)
  6792. {
  6793. // Invariants:
  6794. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  6795. // pow10 = 10^(n-1) <= p1 < 10^n
  6796. //
  6797. const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  6798. const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  6799. //
  6800. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  6801. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  6802. //
  6803. assert(d <= 9);
  6804. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  6805. //
  6806. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  6807. //
  6808. p1 = r;
  6809. n--;
  6810. //
  6811. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  6812. // pow10 = 10^n
  6813. //
  6814. // Now check if enough digits have been generated.
  6815. // Compute
  6816. //
  6817. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  6818. //
  6819. // Note:
  6820. // Since rest and delta share the same exponent e, it suffices to
  6821. // compare the significands.
  6822. const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
  6823. if (rest <= delta)
  6824. {
  6825. // V = buffer * 10^n, with M- <= V <= M+.
  6826. decimal_exponent += n;
  6827. // We may now just stop. But instead look if the buffer could be
  6828. // decremented to bring V closer to w.
  6829. //
  6830. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  6831. // The rounding procedure works with diyfp's with an implicit
  6832. // exponent of e.
  6833. //
  6834. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  6835. //
  6836. const uint64_t ten_n = uint64_t{pow10} << -one.e;
  6837. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  6838. return;
  6839. }
  6840. pow10 /= 10;
  6841. //
  6842. // pow10 = 10^(n-1) <= p1 < 10^n
  6843. // Invariants restored.
  6844. }
  6845. // 2)
  6846. //
  6847. // The digits of the integral part have been generated:
  6848. //
  6849. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  6850. // = buffer + p2 * 2^e
  6851. //
  6852. // Now generate the digits of the fractional part p2 * 2^e.
  6853. //
  6854. // Note:
  6855. // No decimal point is generated: the exponent is adjusted instead.
  6856. //
  6857. // p2 actually represents the fraction
  6858. //
  6859. // p2 * 2^e
  6860. // = p2 / 2^-e
  6861. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  6862. //
  6863. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  6864. //
  6865. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  6866. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  6867. //
  6868. // using
  6869. //
  6870. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  6871. // = ( d) * 2^-e + ( r)
  6872. //
  6873. // or
  6874. // 10^m * p2 * 2^e = d + r * 2^e
  6875. //
  6876. // i.e.
  6877. //
  6878. // M+ = buffer + p2 * 2^e
  6879. // = buffer + 10^-m * (d + r * 2^e)
  6880. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  6881. //
  6882. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  6883. assert(p2 > delta);
  6884. int m = 0;
  6885. for (;;)
  6886. {
  6887. // Invariant:
  6888. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  6889. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  6890. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  6891. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  6892. //
  6893. assert(p2 <= UINT64_MAX / 10);
  6894. p2 *= 10;
  6895. const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  6896. const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  6897. //
  6898. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  6899. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  6900. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  6901. //
  6902. assert(d <= 9);
  6903. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  6904. //
  6905. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  6906. //
  6907. p2 = r;
  6908. m++;
  6909. //
  6910. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  6911. // Invariant restored.
  6912. // Check if enough digits have been generated.
  6913. //
  6914. // 10^-m * p2 * 2^e <= delta * 2^e
  6915. // p2 * 2^e <= 10^m * delta * 2^e
  6916. // p2 <= 10^m * delta
  6917. delta *= 10;
  6918. dist *= 10;
  6919. if (p2 <= delta)
  6920. {
  6921. break;
  6922. }
  6923. }
  6924. // V = buffer * 10^-m, with M- <= V <= M+.
  6925. decimal_exponent -= m;
  6926. // 1 ulp in the decimal representation is now 10^-m.
  6927. // Since delta and dist are now scaled by 10^m, we need to do the
  6928. // same with ulp in order to keep the units in sync.
  6929. //
  6930. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  6931. //
  6932. const uint64_t ten_m = one.f;
  6933. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  6934. // By construction this algorithm generates the shortest possible decimal
  6935. // number (Loitsch, Theorem 6.2) which rounds back to w.
  6936. // For an input number of precision p, at least
  6937. //
  6938. // N = 1 + ceil(p * log_10(2))
  6939. //
  6940. // decimal digits are sufficient to identify all binary floating-point
  6941. // numbers (Matula, "In-and-Out conversions").
  6942. // This implies that the algorithm does not produce more than N decimal
  6943. // digits.
  6944. //
  6945. // N = 17 for p = 53 (IEEE double precision)
  6946. // N = 9 for p = 24 (IEEE single precision)
  6947. }
  6948. /*!
  6949. v = buf * 10^decimal_exponent
  6950. len is the length of the buffer (number of decimal digits)
  6951. The buffer must be large enough, i.e. >= max_digits10.
  6952. */
  6953. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  6954. diyfp m_minus, diyfp v, diyfp m_plus)
  6955. {
  6956. assert(m_plus.e == m_minus.e);
  6957. assert(m_plus.e == v.e);
  6958. // --------(-----------------------+-----------------------)-------- (A)
  6959. // m- v m+
  6960. //
  6961. // --------------------(-----------+-----------------------)-------- (B)
  6962. // m- v m+
  6963. //
  6964. // First scale v (and m- and m+) such that the exponent is in the range
  6965. // [alpha, gamma].
  6966. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  6967. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  6968. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  6969. const diyfp w = diyfp::mul(v, c_minus_k);
  6970. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  6971. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  6972. // ----(---+---)---------------(---+---)---------------(---+---)----
  6973. // w- w w+
  6974. // = c*m- = c*v = c*m+
  6975. //
  6976. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  6977. // w+ are now off by a small amount.
  6978. // In fact:
  6979. //
  6980. // w - v * 10^k < 1 ulp
  6981. //
  6982. // To account for this inaccuracy, add resp. subtract 1 ulp.
  6983. //
  6984. // --------+---[---------------(---+---)---------------]---+--------
  6985. // w- M- w M+ w+
  6986. //
  6987. // Now any number in [M-, M+] (bounds included) will round to w when input,
  6988. // regardless of how the input rounding algorithm breaks ties.
  6989. //
  6990. // And digit_gen generates the shortest possible such number in [M-, M+].
  6991. // Note that this does not mean that Grisu2 always generates the shortest
  6992. // possible number in the interval (m-, m+).
  6993. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  6994. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  6995. decimal_exponent = -cached.k; // = -(-k) = k
  6996. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  6997. }
  6998. /*!
  6999. v = buf * 10^decimal_exponent
  7000. len is the length of the buffer (number of decimal digits)
  7001. The buffer must be large enough, i.e. >= max_digits10.
  7002. */
  7003. template <typename FloatType>
  7004. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  7005. {
  7006. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  7007. "internal error: not enough precision");
  7008. assert(std::isfinite(value));
  7009. assert(value > 0);
  7010. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  7011. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  7012. // decimal representations are not exactly "short".
  7013. //
  7014. // The documentation for 'std::to_chars' (http://en.cppreference.com/w/cpp/utility/to_chars)
  7015. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  7016. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  7017. // does.
  7018. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  7019. // representation using the corresponding std::from_chars function recovers value exactly". That
  7020. // indicates that single precision floating-point numbers should be recovered using
  7021. // 'std::strtof'.
  7022. //
  7023. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  7024. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  7025. // value is off by 1 ulp.
  7026. #if 0
  7027. const boundaries w = compute_boundaries(static_cast<double>(value));
  7028. #else
  7029. const boundaries w = compute_boundaries(value);
  7030. #endif
  7031. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  7032. }
  7033. /*!
  7034. @brief appends a decimal representation of e to buf
  7035. @return a pointer to the element following the exponent.
  7036. @pre -1000 < e < 1000
  7037. */
  7038. inline char* append_exponent(char* buf, int e)
  7039. {
  7040. assert(e > -1000);
  7041. assert(e < 1000);
  7042. if (e < 0)
  7043. {
  7044. e = -e;
  7045. *buf++ = '-';
  7046. }
  7047. else
  7048. {
  7049. *buf++ = '+';
  7050. }
  7051. uint32_t k = static_cast<uint32_t>(e);
  7052. if (k < 10)
  7053. {
  7054. // Always print at least two digits in the exponent.
  7055. // This is for compatibility with printf("%g").
  7056. *buf++ = '0';
  7057. *buf++ = static_cast<char>('0' + k);
  7058. }
  7059. else if (k < 100)
  7060. {
  7061. *buf++ = static_cast<char>('0' + k / 10);
  7062. k %= 10;
  7063. *buf++ = static_cast<char>('0' + k);
  7064. }
  7065. else
  7066. {
  7067. *buf++ = static_cast<char>('0' + k / 100);
  7068. k %= 100;
  7069. *buf++ = static_cast<char>('0' + k / 10);
  7070. k %= 10;
  7071. *buf++ = static_cast<char>('0' + k);
  7072. }
  7073. return buf;
  7074. }
  7075. /*!
  7076. @brief prettify v = buf * 10^decimal_exponent
  7077. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  7078. notation. Otherwise it will be printed in exponential notation.
  7079. @pre min_exp < 0
  7080. @pre max_exp > 0
  7081. */
  7082. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  7083. int min_exp, int max_exp)
  7084. {
  7085. assert(min_exp < 0);
  7086. assert(max_exp > 0);
  7087. const int k = len;
  7088. const int n = len + decimal_exponent;
  7089. // v = buf * 10^(n-k)
  7090. // k is the length of the buffer (number of decimal digits)
  7091. // n is the position of the decimal point relative to the start of the buffer.
  7092. if (k <= n and n <= max_exp)
  7093. {
  7094. // digits[000]
  7095. // len <= max_exp + 2
  7096. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  7097. // Make it look like a floating-point number (#362, #378)
  7098. buf[n + 0] = '.';
  7099. buf[n + 1] = '0';
  7100. return buf + (n + 2);
  7101. }
  7102. if (0 < n and n <= max_exp)
  7103. {
  7104. // dig.its
  7105. // len <= max_digits10 + 1
  7106. assert(k > n);
  7107. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  7108. buf[n] = '.';
  7109. return buf + (k + 1);
  7110. }
  7111. if (min_exp < n and n <= 0)
  7112. {
  7113. // 0.[000]digits
  7114. // len <= 2 + (-min_exp - 1) + max_digits10
  7115. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  7116. buf[0] = '0';
  7117. buf[1] = '.';
  7118. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  7119. return buf + (2 + (-n) + k);
  7120. }
  7121. if (k == 1)
  7122. {
  7123. // dE+123
  7124. // len <= 1 + 5
  7125. buf += 1;
  7126. }
  7127. else
  7128. {
  7129. // d.igitsE+123
  7130. // len <= max_digits10 + 1 + 5
  7131. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  7132. buf[1] = '.';
  7133. buf += 1 + k;
  7134. }
  7135. *buf++ = 'e';
  7136. return append_exponent(buf, n - 1);
  7137. }
  7138. } // namespace dtoa_impl
  7139. /*!
  7140. @brief generates a decimal representation of the floating-point number value in [first, last).
  7141. The format of the resulting decimal representation is similar to printf's %g
  7142. format. Returns an iterator pointing past-the-end of the decimal representation.
  7143. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  7144. @note The buffer must be large enough.
  7145. @note The result is NOT null-terminated.
  7146. */
  7147. template <typename FloatType>
  7148. char* to_chars(char* first, char* last, FloatType value)
  7149. {
  7150. static_cast<void>(last); // maybe unused - fix warning
  7151. assert(std::isfinite(value));
  7152. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  7153. if (std::signbit(value))
  7154. {
  7155. value = -value;
  7156. *first++ = '-';
  7157. }
  7158. if (value == 0) // +-0
  7159. {
  7160. *first++ = '0';
  7161. // Make it look like a floating-point number (#362, #378)
  7162. *first++ = '.';
  7163. *first++ = '0';
  7164. return first;
  7165. }
  7166. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  7167. // Compute v = buffer * 10^decimal_exponent.
  7168. // The decimal digits are stored in the buffer, which needs to be interpreted
  7169. // as an unsigned decimal integer.
  7170. // len is the length of the buffer, i.e. the number of decimal digits.
  7171. int len = 0;
  7172. int decimal_exponent = 0;
  7173. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  7174. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  7175. // Format the buffer like printf("%.*g", prec, value)
  7176. constexpr int kMinExp = -4;
  7177. // Use digits10 here to increase compatibility with version 2.
  7178. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  7179. assert(last - first >= kMaxExp + 2);
  7180. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  7181. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  7182. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  7183. }
  7184. } // namespace detail
  7185. } // namespace nlohmann
  7186. // #include <nlohmann/detail/macro_scope.hpp>
  7187. // #include <nlohmann/detail/meta.hpp>
  7188. // #include <nlohmann/detail/output/output_adapters.hpp>
  7189. // #include <nlohmann/detail/value_t.hpp>
  7190. namespace nlohmann
  7191. {
  7192. namespace detail
  7193. {
  7194. ///////////////////
  7195. // serialization //
  7196. ///////////////////
  7197. template<typename BasicJsonType>
  7198. class serializer
  7199. {
  7200. using string_t = typename BasicJsonType::string_t;
  7201. using number_float_t = typename BasicJsonType::number_float_t;
  7202. using number_integer_t = typename BasicJsonType::number_integer_t;
  7203. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7204. static constexpr uint8_t UTF8_ACCEPT = 0;
  7205. static constexpr uint8_t UTF8_REJECT = 1;
  7206. public:
  7207. /*!
  7208. @param[in] s output stream to serialize to
  7209. @param[in] ichar indentation character to use
  7210. */
  7211. serializer(output_adapter_t<char> s, const char ichar)
  7212. : o(std::move(s)), loc(std::localeconv()),
  7213. thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
  7214. decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
  7215. indent_char(ichar), indent_string(512, indent_char)
  7216. {}
  7217. // delete because of pointer members
  7218. serializer(const serializer&) = delete;
  7219. serializer& operator=(const serializer&) = delete;
  7220. /*!
  7221. @brief internal implementation of the serialization function
  7222. This function is called by the public member function dump and organizes
  7223. the serialization internally. The indentation level is propagated as
  7224. additional parameter. In case of arrays and objects, the function is
  7225. called recursively.
  7226. - strings and object keys are escaped using `escape_string()`
  7227. - integer numbers are converted implicitly via `operator<<`
  7228. - floating-point numbers are converted to a string using `"%g"` format
  7229. @param[in] val value to serialize
  7230. @param[in] pretty_print whether the output shall be pretty-printed
  7231. @param[in] indent_step the indent level
  7232. @param[in] current_indent the current indent level (only used internally)
  7233. */
  7234. void dump(const BasicJsonType& val, const bool pretty_print,
  7235. const bool ensure_ascii,
  7236. const unsigned int indent_step,
  7237. const unsigned int current_indent = 0)
  7238. {
  7239. switch (val.m_type)
  7240. {
  7241. case value_t::object:
  7242. {
  7243. if (val.m_value.object->empty())
  7244. {
  7245. o->write_characters("{}", 2);
  7246. return;
  7247. }
  7248. if (pretty_print)
  7249. {
  7250. o->write_characters("{\n", 2);
  7251. // variable to hold indentation for recursive calls
  7252. const auto new_indent = current_indent + indent_step;
  7253. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  7254. {
  7255. indent_string.resize(indent_string.size() * 2, ' ');
  7256. }
  7257. // first n-1 elements
  7258. auto i = val.m_value.object->cbegin();
  7259. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  7260. {
  7261. o->write_characters(indent_string.c_str(), new_indent);
  7262. o->write_character('\"');
  7263. dump_escaped(i->first, ensure_ascii);
  7264. o->write_characters("\": ", 3);
  7265. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  7266. o->write_characters(",\n", 2);
  7267. }
  7268. // last element
  7269. assert(i != val.m_value.object->cend());
  7270. assert(std::next(i) == val.m_value.object->cend());
  7271. o->write_characters(indent_string.c_str(), new_indent);
  7272. o->write_character('\"');
  7273. dump_escaped(i->first, ensure_ascii);
  7274. o->write_characters("\": ", 3);
  7275. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  7276. o->write_character('\n');
  7277. o->write_characters(indent_string.c_str(), current_indent);
  7278. o->write_character('}');
  7279. }
  7280. else
  7281. {
  7282. o->write_character('{');
  7283. // first n-1 elements
  7284. auto i = val.m_value.object->cbegin();
  7285. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  7286. {
  7287. o->write_character('\"');
  7288. dump_escaped(i->first, ensure_ascii);
  7289. o->write_characters("\":", 2);
  7290. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  7291. o->write_character(',');
  7292. }
  7293. // last element
  7294. assert(i != val.m_value.object->cend());
  7295. assert(std::next(i) == val.m_value.object->cend());
  7296. o->write_character('\"');
  7297. dump_escaped(i->first, ensure_ascii);
  7298. o->write_characters("\":", 2);
  7299. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  7300. o->write_character('}');
  7301. }
  7302. return;
  7303. }
  7304. case value_t::array:
  7305. {
  7306. if (val.m_value.array->empty())
  7307. {
  7308. o->write_characters("[]", 2);
  7309. return;
  7310. }
  7311. if (pretty_print)
  7312. {
  7313. o->write_characters("[\n", 2);
  7314. // variable to hold indentation for recursive calls
  7315. const auto new_indent = current_indent + indent_step;
  7316. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  7317. {
  7318. indent_string.resize(indent_string.size() * 2, ' ');
  7319. }
  7320. // first n-1 elements
  7321. for (auto i = val.m_value.array->cbegin();
  7322. i != val.m_value.array->cend() - 1; ++i)
  7323. {
  7324. o->write_characters(indent_string.c_str(), new_indent);
  7325. dump(*i, true, ensure_ascii, indent_step, new_indent);
  7326. o->write_characters(",\n", 2);
  7327. }
  7328. // last element
  7329. assert(not val.m_value.array->empty());
  7330. o->write_characters(indent_string.c_str(), new_indent);
  7331. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  7332. o->write_character('\n');
  7333. o->write_characters(indent_string.c_str(), current_indent);
  7334. o->write_character(']');
  7335. }
  7336. else
  7337. {
  7338. o->write_character('[');
  7339. // first n-1 elements
  7340. for (auto i = val.m_value.array->cbegin();
  7341. i != val.m_value.array->cend() - 1; ++i)
  7342. {
  7343. dump(*i, false, ensure_ascii, indent_step, current_indent);
  7344. o->write_character(',');
  7345. }
  7346. // last element
  7347. assert(not val.m_value.array->empty());
  7348. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  7349. o->write_character(']');
  7350. }
  7351. return;
  7352. }
  7353. case value_t::string:
  7354. {
  7355. o->write_character('\"');
  7356. dump_escaped(*val.m_value.string, ensure_ascii);
  7357. o->write_character('\"');
  7358. return;
  7359. }
  7360. case value_t::boolean:
  7361. {
  7362. if (val.m_value.boolean)
  7363. {
  7364. o->write_characters("true", 4);
  7365. }
  7366. else
  7367. {
  7368. o->write_characters("false", 5);
  7369. }
  7370. return;
  7371. }
  7372. case value_t::number_integer:
  7373. {
  7374. dump_integer(val.m_value.number_integer);
  7375. return;
  7376. }
  7377. case value_t::number_unsigned:
  7378. {
  7379. dump_integer(val.m_value.number_unsigned);
  7380. return;
  7381. }
  7382. case value_t::number_float:
  7383. {
  7384. dump_float(val.m_value.number_float);
  7385. return;
  7386. }
  7387. case value_t::discarded:
  7388. {
  7389. o->write_characters("<discarded>", 11);
  7390. return;
  7391. }
  7392. case value_t::null:
  7393. {
  7394. o->write_characters("null", 4);
  7395. return;
  7396. }
  7397. }
  7398. }
  7399. private:
  7400. /*!
  7401. @brief dump escaped string
  7402. Escape a string by replacing certain special characters by a sequence of an
  7403. escape character (backslash) and another character and other control
  7404. characters by a sequence of "\u" followed by a four-digit hex
  7405. representation. The escaped string is written to output stream @a o.
  7406. @param[in] s the string to escape
  7407. @param[in] ensure_ascii whether to escape non-ASCII characters with
  7408. \uXXXX sequences
  7409. @complexity Linear in the length of string @a s.
  7410. */
  7411. void dump_escaped(const string_t& s, const bool ensure_ascii)
  7412. {
  7413. uint32_t codepoint;
  7414. uint8_t state = UTF8_ACCEPT;
  7415. std::size_t bytes = 0; // number of bytes written to string_buffer
  7416. for (std::size_t i = 0; i < s.size(); ++i)
  7417. {
  7418. const auto byte = static_cast<uint8_t>(s[i]);
  7419. switch (decode(state, codepoint, byte))
  7420. {
  7421. case UTF8_ACCEPT: // decode found a new code point
  7422. {
  7423. switch (codepoint)
  7424. {
  7425. case 0x08: // backspace
  7426. {
  7427. string_buffer[bytes++] = '\\';
  7428. string_buffer[bytes++] = 'b';
  7429. break;
  7430. }
  7431. case 0x09: // horizontal tab
  7432. {
  7433. string_buffer[bytes++] = '\\';
  7434. string_buffer[bytes++] = 't';
  7435. break;
  7436. }
  7437. case 0x0A: // newline
  7438. {
  7439. string_buffer[bytes++] = '\\';
  7440. string_buffer[bytes++] = 'n';
  7441. break;
  7442. }
  7443. case 0x0C: // formfeed
  7444. {
  7445. string_buffer[bytes++] = '\\';
  7446. string_buffer[bytes++] = 'f';
  7447. break;
  7448. }
  7449. case 0x0D: // carriage return
  7450. {
  7451. string_buffer[bytes++] = '\\';
  7452. string_buffer[bytes++] = 'r';
  7453. break;
  7454. }
  7455. case 0x22: // quotation mark
  7456. {
  7457. string_buffer[bytes++] = '\\';
  7458. string_buffer[bytes++] = '\"';
  7459. break;
  7460. }
  7461. case 0x5C: // reverse solidus
  7462. {
  7463. string_buffer[bytes++] = '\\';
  7464. string_buffer[bytes++] = '\\';
  7465. break;
  7466. }
  7467. default:
  7468. {
  7469. // escape control characters (0x00..0x1F) or, if
  7470. // ensure_ascii parameter is used, non-ASCII characters
  7471. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  7472. {
  7473. if (codepoint <= 0xFFFF)
  7474. {
  7475. std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x",
  7476. static_cast<uint16_t>(codepoint));
  7477. bytes += 6;
  7478. }
  7479. else
  7480. {
  7481. std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  7482. static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)),
  7483. static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF)));
  7484. bytes += 12;
  7485. }
  7486. }
  7487. else
  7488. {
  7489. // copy byte to buffer (all previous bytes
  7490. // been copied have in default case above)
  7491. string_buffer[bytes++] = s[i];
  7492. }
  7493. break;
  7494. }
  7495. }
  7496. // write buffer and reset index; there must be 13 bytes
  7497. // left, as this is the maximal number of bytes to be
  7498. // written ("\uxxxx\uxxxx\0") for one code point
  7499. if (string_buffer.size() - bytes < 13)
  7500. {
  7501. o->write_characters(string_buffer.data(), bytes);
  7502. bytes = 0;
  7503. }
  7504. break;
  7505. }
  7506. case UTF8_REJECT: // decode found invalid UTF-8 byte
  7507. {
  7508. std::stringstream ss;
  7509. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte);
  7510. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str()));
  7511. }
  7512. default: // decode found yet incomplete multi-byte code point
  7513. {
  7514. if (not ensure_ascii)
  7515. {
  7516. // code point will not be escaped - copy byte to buffer
  7517. string_buffer[bytes++] = s[i];
  7518. }
  7519. break;
  7520. }
  7521. }
  7522. }
  7523. if (JSON_LIKELY(state == UTF8_ACCEPT))
  7524. {
  7525. // write buffer
  7526. if (bytes > 0)
  7527. {
  7528. o->write_characters(string_buffer.data(), bytes);
  7529. }
  7530. }
  7531. else
  7532. {
  7533. // we finish reading, but do not accept: string was incomplete
  7534. std::stringstream ss;
  7535. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(s.back()));
  7536. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str()));
  7537. }
  7538. }
  7539. /*!
  7540. @brief dump an integer
  7541. Dump a given integer to output stream @a o. Works internally with
  7542. @a number_buffer.
  7543. @param[in] x integer number (signed or unsigned) to dump
  7544. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  7545. */
  7546. template<typename NumberType, detail::enable_if_t<
  7547. std::is_same<NumberType, number_unsigned_t>::value or
  7548. std::is_same<NumberType, number_integer_t>::value,
  7549. int> = 0>
  7550. void dump_integer(NumberType x)
  7551. {
  7552. // special case for "0"
  7553. if (x == 0)
  7554. {
  7555. o->write_character('0');
  7556. return;
  7557. }
  7558. const bool is_negative = (x <= 0) and (x != 0); // see issue #755
  7559. std::size_t i = 0;
  7560. while (x != 0)
  7561. {
  7562. // spare 1 byte for '\0'
  7563. assert(i < number_buffer.size() - 1);
  7564. const auto digit = std::labs(static_cast<long>(x % 10));
  7565. number_buffer[i++] = static_cast<char>('0' + digit);
  7566. x /= 10;
  7567. }
  7568. if (is_negative)
  7569. {
  7570. // make sure there is capacity for the '-'
  7571. assert(i < number_buffer.size() - 2);
  7572. number_buffer[i++] = '-';
  7573. }
  7574. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  7575. o->write_characters(number_buffer.data(), i);
  7576. }
  7577. /*!
  7578. @brief dump a floating-point number
  7579. Dump a given floating-point number to output stream @a o. Works internally
  7580. with @a number_buffer.
  7581. @param[in] x floating-point number to dump
  7582. */
  7583. void dump_float(number_float_t x)
  7584. {
  7585. // NaN / inf
  7586. if (not std::isfinite(x))
  7587. {
  7588. o->write_characters("null", 4);
  7589. return;
  7590. }
  7591. // If number_float_t is an IEEE-754 single or double precision number,
  7592. // use the Grisu2 algorithm to produce short numbers which are
  7593. // guaranteed to round-trip, using strtof and strtod, resp.
  7594. //
  7595. // NB: The test below works if <long double> == <double>.
  7596. static constexpr bool is_ieee_single_or_double
  7597. = (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
  7598. (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);
  7599. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  7600. }
  7601. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  7602. {
  7603. char* begin = number_buffer.data();
  7604. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  7605. o->write_characters(begin, static_cast<size_t>(end - begin));
  7606. }
  7607. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  7608. {
  7609. // get number of digits for a float -> text -> float round-trip
  7610. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  7611. // the actual conversion
  7612. std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  7613. // negative value indicates an error
  7614. assert(len > 0);
  7615. // check if buffer was large enough
  7616. assert(static_cast<std::size_t>(len) < number_buffer.size());
  7617. // erase thousands separator
  7618. if (thousands_sep != '\0')
  7619. {
  7620. const auto end = std::remove(number_buffer.begin(),
  7621. number_buffer.begin() + len, thousands_sep);
  7622. std::fill(end, number_buffer.end(), '\0');
  7623. assert((end - number_buffer.begin()) <= len);
  7624. len = (end - number_buffer.begin());
  7625. }
  7626. // convert decimal point to '.'
  7627. if (decimal_point != '\0' and decimal_point != '.')
  7628. {
  7629. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  7630. if (dec_pos != number_buffer.end())
  7631. {
  7632. *dec_pos = '.';
  7633. }
  7634. }
  7635. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  7636. // determine if need to append ".0"
  7637. const bool value_is_int_like =
  7638. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  7639. [](char c)
  7640. {
  7641. return (c == '.' or c == 'e');
  7642. });
  7643. if (value_is_int_like)
  7644. {
  7645. o->write_characters(".0", 2);
  7646. }
  7647. }
  7648. /*!
  7649. @brief check whether a string is UTF-8 encoded
  7650. The function checks each byte of a string whether it is UTF-8 encoded. The
  7651. result of the check is stored in the @a state parameter. The function must
  7652. be called initially with state 0 (accept). State 1 means the string must
  7653. be rejected, because the current byte is not allowed. If the string is
  7654. completely processed, but the state is non-zero, the string ended
  7655. prematurely; that is, the last byte indicated more bytes should have
  7656. followed.
  7657. @param[in,out] state the state of the decoding
  7658. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  7659. @param[in] byte next byte to decode
  7660. @return new state
  7661. @note The function has been edited: a std::array is used.
  7662. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  7663. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  7664. */
  7665. static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept
  7666. {
  7667. static const std::array<uint8_t, 400> utf8d =
  7668. {
  7669. {
  7670. 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
  7671. 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
  7672. 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
  7673. 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
  7674. 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
  7675. 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
  7676. 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
  7677. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  7678. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  7679. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  7680. 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
  7681. 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
  7682. 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
  7683. 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
  7684. }
  7685. };
  7686. const uint8_t type = utf8d[byte];
  7687. codep = (state != UTF8_ACCEPT)
  7688. ? (byte & 0x3fu) | (codep << 6)
  7689. : static_cast<uint32_t>(0xff >> type) & (byte);
  7690. state = utf8d[256u + state * 16u + type];
  7691. return state;
  7692. }
  7693. private:
  7694. /// the output of the serializer
  7695. output_adapter_t<char> o = nullptr;
  7696. /// a (hopefully) large enough character buffer
  7697. std::array<char, 64> number_buffer{{}};
  7698. /// the locale
  7699. const std::lconv* loc = nullptr;
  7700. /// the locale's thousand separator character
  7701. const char thousands_sep = '\0';
  7702. /// the locale's decimal point character
  7703. const char decimal_point = '\0';
  7704. /// string buffer
  7705. std::array<char, 512> string_buffer{{}};
  7706. /// the indentation character
  7707. const char indent_char;
  7708. /// the indentation string
  7709. string_t indent_string;
  7710. };
  7711. }
  7712. }
  7713. // #include <nlohmann/detail/json_ref.hpp>
  7714. #include <initializer_list>
  7715. #include <utility>
  7716. namespace nlohmann
  7717. {
  7718. namespace detail
  7719. {
  7720. template<typename BasicJsonType>
  7721. class json_ref
  7722. {
  7723. public:
  7724. using value_type = BasicJsonType;
  7725. json_ref(value_type&& value)
  7726. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  7727. {}
  7728. json_ref(const value_type& value)
  7729. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  7730. {}
  7731. json_ref(std::initializer_list<json_ref> init)
  7732. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  7733. {}
  7734. template<class... Args>
  7735. json_ref(Args&& ... args)
  7736. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)
  7737. {}
  7738. // class should be movable only
  7739. json_ref(json_ref&&) = default;
  7740. json_ref(const json_ref&) = delete;
  7741. json_ref& operator=(const json_ref&) = delete;
  7742. value_type moved_or_copied() const
  7743. {
  7744. if (is_rvalue)
  7745. {
  7746. return std::move(*value_ref);
  7747. }
  7748. return *value_ref;
  7749. }
  7750. value_type const& operator*() const
  7751. {
  7752. return *static_cast<value_type const*>(value_ref);
  7753. }
  7754. value_type const* operator->() const
  7755. {
  7756. return static_cast<value_type const*>(value_ref);
  7757. }
  7758. private:
  7759. mutable value_type owned_value = nullptr;
  7760. value_type* value_ref = nullptr;
  7761. const bool is_rvalue;
  7762. };
  7763. }
  7764. }
  7765. // #include <nlohmann/detail/json_pointer.hpp>
  7766. #include <cassert> // assert
  7767. #include <numeric> // accumulate
  7768. #include <string> // string
  7769. #include <vector> // vector
  7770. // #include <nlohmann/detail/macro_scope.hpp>
  7771. // #include <nlohmann/detail/exceptions.hpp>
  7772. // #include <nlohmann/detail/value_t.hpp>
  7773. namespace nlohmann
  7774. {
  7775. template<typename BasicJsonType>
  7776. class json_pointer
  7777. {
  7778. // allow basic_json to access private members
  7779. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  7780. friend class basic_json;
  7781. public:
  7782. /*!
  7783. @brief create JSON pointer
  7784. Create a JSON pointer according to the syntax described in
  7785. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  7786. @param[in] s string representing the JSON pointer; if omitted, the empty
  7787. string is assumed which references the whole JSON value
  7788. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  7789. not begin with a slash (`/`); see example below
  7790. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  7791. not followed by `0` (representing `~`) or `1` (representing `/`); see
  7792. example below
  7793. @liveexample{The example shows the construction several valid JSON pointers
  7794. as well as the exceptional behavior.,json_pointer}
  7795. @since version 2.0.0
  7796. */
  7797. explicit json_pointer(const std::string& s = "")
  7798. : reference_tokens(split(s))
  7799. {}
  7800. /*!
  7801. @brief return a string representation of the JSON pointer
  7802. @invariant For each JSON pointer `ptr`, it holds:
  7803. @code {.cpp}
  7804. ptr == json_pointer(ptr.to_string());
  7805. @endcode
  7806. @return a string representation of the JSON pointer
  7807. @liveexample{The example shows the result of `to_string`.,
  7808. json_pointer__to_string}
  7809. @since version 2.0.0
  7810. */
  7811. std::string to_string() const noexcept
  7812. {
  7813. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  7814. std::string{},
  7815. [](const std::string & a, const std::string & b)
  7816. {
  7817. return a + "/" + escape(b);
  7818. });
  7819. }
  7820. /// @copydoc to_string()
  7821. operator std::string() const
  7822. {
  7823. return to_string();
  7824. }
  7825. /*!
  7826. @param[in] s reference token to be converted into an array index
  7827. @return integer representation of @a s
  7828. @throw out_of_range.404 if string @a s could not be converted to an integer
  7829. */
  7830. static int array_index(const std::string& s)
  7831. {
  7832. std::size_t processed_chars = 0;
  7833. const int res = std::stoi(s, &processed_chars);
  7834. // check if the string was completely read
  7835. if (JSON_UNLIKELY(processed_chars != s.size()))
  7836. {
  7837. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  7838. }
  7839. return res;
  7840. }
  7841. private:
  7842. /*!
  7843. @brief remove and return last reference pointer
  7844. @throw out_of_range.405 if JSON pointer has no parent
  7845. */
  7846. std::string pop_back()
  7847. {
  7848. if (JSON_UNLIKELY(is_root()))
  7849. {
  7850. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7851. }
  7852. auto last = reference_tokens.back();
  7853. reference_tokens.pop_back();
  7854. return last;
  7855. }
  7856. /// return whether pointer points to the root document
  7857. bool is_root() const
  7858. {
  7859. return reference_tokens.empty();
  7860. }
  7861. json_pointer top() const
  7862. {
  7863. if (JSON_UNLIKELY(is_root()))
  7864. {
  7865. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7866. }
  7867. json_pointer result = *this;
  7868. result.reference_tokens = {reference_tokens[0]};
  7869. return result;
  7870. }
  7871. /*!
  7872. @brief create and return a reference to the pointed to value
  7873. @complexity Linear in the number of reference tokens.
  7874. @throw parse_error.109 if array index is not a number
  7875. @throw type_error.313 if value cannot be unflattened
  7876. */
  7877. BasicJsonType& get_and_create(BasicJsonType& j) const
  7878. {
  7879. using size_type = typename BasicJsonType::size_type;
  7880. auto result = &j;
  7881. // in case no reference tokens exist, return a reference to the JSON value
  7882. // j which will be overwritten by a primitive value
  7883. for (const auto& reference_token : reference_tokens)
  7884. {
  7885. switch (result->m_type)
  7886. {
  7887. case detail::value_t::null:
  7888. {
  7889. if (reference_token == "0")
  7890. {
  7891. // start a new array if reference token is 0
  7892. result = &result->operator[](0);
  7893. }
  7894. else
  7895. {
  7896. // start a new object otherwise
  7897. result = &result->operator[](reference_token);
  7898. }
  7899. break;
  7900. }
  7901. case detail::value_t::object:
  7902. {
  7903. // create an entry in the object
  7904. result = &result->operator[](reference_token);
  7905. break;
  7906. }
  7907. case detail::value_t::array:
  7908. {
  7909. // create an entry in the array
  7910. JSON_TRY
  7911. {
  7912. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  7913. }
  7914. JSON_CATCH(std::invalid_argument&)
  7915. {
  7916. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7917. }
  7918. break;
  7919. }
  7920. /*
  7921. The following code is only reached if there exists a reference
  7922. token _and_ the current value is primitive. In this case, we have
  7923. an error situation, because primitive values may only occur as
  7924. single value; that is, with an empty list of reference tokens.
  7925. */
  7926. default:
  7927. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  7928. }
  7929. }
  7930. return *result;
  7931. }
  7932. /*!
  7933. @brief return a reference to the pointed to value
  7934. @note This version does not throw if a value is not present, but tries to
  7935. create nested values instead. For instance, calling this function
  7936. with pointer `"/this/that"` on a null value is equivalent to calling
  7937. `operator[]("this").operator[]("that")` on that value, effectively
  7938. changing the null value to an object.
  7939. @param[in] ptr a JSON value
  7940. @return reference to the JSON value pointed to by the JSON pointer
  7941. @complexity Linear in the length of the JSON pointer.
  7942. @throw parse_error.106 if an array index begins with '0'
  7943. @throw parse_error.109 if an array index was not a number
  7944. @throw out_of_range.404 if the JSON pointer can not be resolved
  7945. */
  7946. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  7947. {
  7948. using size_type = typename BasicJsonType::size_type;
  7949. for (const auto& reference_token : reference_tokens)
  7950. {
  7951. // convert null values to arrays or objects before continuing
  7952. if (ptr->m_type == detail::value_t::null)
  7953. {
  7954. // check if reference token is a number
  7955. const bool nums =
  7956. std::all_of(reference_token.begin(), reference_token.end(),
  7957. [](const char x)
  7958. {
  7959. return (x >= '0' and x <= '9');
  7960. });
  7961. // change value to array for numbers or "-" or to object otherwise
  7962. *ptr = (nums or reference_token == "-")
  7963. ? detail::value_t::array
  7964. : detail::value_t::object;
  7965. }
  7966. switch (ptr->m_type)
  7967. {
  7968. case detail::value_t::object:
  7969. {
  7970. // use unchecked object access
  7971. ptr = &ptr->operator[](reference_token);
  7972. break;
  7973. }
  7974. case detail::value_t::array:
  7975. {
  7976. // error condition (cf. RFC 6901, Sect. 4)
  7977. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7978. {
  7979. JSON_THROW(detail::parse_error::create(106, 0,
  7980. "array index '" + reference_token +
  7981. "' must not begin with '0'"));
  7982. }
  7983. if (reference_token == "-")
  7984. {
  7985. // explicitly treat "-" as index beyond the end
  7986. ptr = &ptr->operator[](ptr->m_value.array->size());
  7987. }
  7988. else
  7989. {
  7990. // convert array index to number; unchecked access
  7991. JSON_TRY
  7992. {
  7993. ptr = &ptr->operator[](
  7994. static_cast<size_type>(array_index(reference_token)));
  7995. }
  7996. JSON_CATCH(std::invalid_argument&)
  7997. {
  7998. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7999. }
  8000. }
  8001. break;
  8002. }
  8003. default:
  8004. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  8005. }
  8006. }
  8007. return *ptr;
  8008. }
  8009. /*!
  8010. @throw parse_error.106 if an array index begins with '0'
  8011. @throw parse_error.109 if an array index was not a number
  8012. @throw out_of_range.402 if the array index '-' is used
  8013. @throw out_of_range.404 if the JSON pointer can not be resolved
  8014. */
  8015. BasicJsonType& get_checked(BasicJsonType* ptr) const
  8016. {
  8017. using size_type = typename BasicJsonType::size_type;
  8018. for (const auto& reference_token : reference_tokens)
  8019. {
  8020. switch (ptr->m_type)
  8021. {
  8022. case detail::value_t::object:
  8023. {
  8024. // note: at performs range check
  8025. ptr = &ptr->at(reference_token);
  8026. break;
  8027. }
  8028. case detail::value_t::array:
  8029. {
  8030. if (JSON_UNLIKELY(reference_token == "-"))
  8031. {
  8032. // "-" always fails the range check
  8033. JSON_THROW(detail::out_of_range::create(402,
  8034. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  8035. ") is out of range"));
  8036. }
  8037. // error condition (cf. RFC 6901, Sect. 4)
  8038. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  8039. {
  8040. JSON_THROW(detail::parse_error::create(106, 0,
  8041. "array index '" + reference_token +
  8042. "' must not begin with '0'"));
  8043. }
  8044. // note: at performs range check
  8045. JSON_TRY
  8046. {
  8047. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  8048. }
  8049. JSON_CATCH(std::invalid_argument&)
  8050. {
  8051. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  8052. }
  8053. break;
  8054. }
  8055. default:
  8056. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  8057. }
  8058. }
  8059. return *ptr;
  8060. }
  8061. /*!
  8062. @brief return a const reference to the pointed to value
  8063. @param[in] ptr a JSON value
  8064. @return const reference to the JSON value pointed to by the JSON
  8065. pointer
  8066. @throw parse_error.106 if an array index begins with '0'
  8067. @throw parse_error.109 if an array index was not a number
  8068. @throw out_of_range.402 if the array index '-' is used
  8069. @throw out_of_range.404 if the JSON pointer can not be resolved
  8070. */
  8071. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  8072. {
  8073. using size_type = typename BasicJsonType::size_type;
  8074. for (const auto& reference_token : reference_tokens)
  8075. {
  8076. switch (ptr->m_type)
  8077. {
  8078. case detail::value_t::object:
  8079. {
  8080. // use unchecked object access
  8081. ptr = &ptr->operator[](reference_token);
  8082. break;
  8083. }
  8084. case detail::value_t::array:
  8085. {
  8086. if (JSON_UNLIKELY(reference_token == "-"))
  8087. {
  8088. // "-" cannot be used for const access
  8089. JSON_THROW(detail::out_of_range::create(402,
  8090. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  8091. ") is out of range"));
  8092. }
  8093. // error condition (cf. RFC 6901, Sect. 4)
  8094. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  8095. {
  8096. JSON_THROW(detail::parse_error::create(106, 0,
  8097. "array index '" + reference_token +
  8098. "' must not begin with '0'"));
  8099. }
  8100. // use unchecked array access
  8101. JSON_TRY
  8102. {
  8103. ptr = &ptr->operator[](
  8104. static_cast<size_type>(array_index(reference_token)));
  8105. }
  8106. JSON_CATCH(std::invalid_argument&)
  8107. {
  8108. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  8109. }
  8110. break;
  8111. }
  8112. default:
  8113. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  8114. }
  8115. }
  8116. return *ptr;
  8117. }
  8118. /*!
  8119. @throw parse_error.106 if an array index begins with '0'
  8120. @throw parse_error.109 if an array index was not a number
  8121. @throw out_of_range.402 if the array index '-' is used
  8122. @throw out_of_range.404 if the JSON pointer can not be resolved
  8123. */
  8124. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  8125. {
  8126. using size_type = typename BasicJsonType::size_type;
  8127. for (const auto& reference_token : reference_tokens)
  8128. {
  8129. switch (ptr->m_type)
  8130. {
  8131. case detail::value_t::object:
  8132. {
  8133. // note: at performs range check
  8134. ptr = &ptr->at(reference_token);
  8135. break;
  8136. }
  8137. case detail::value_t::array:
  8138. {
  8139. if (JSON_UNLIKELY(reference_token == "-"))
  8140. {
  8141. // "-" always fails the range check
  8142. JSON_THROW(detail::out_of_range::create(402,
  8143. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  8144. ") is out of range"));
  8145. }
  8146. // error condition (cf. RFC 6901, Sect. 4)
  8147. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  8148. {
  8149. JSON_THROW(detail::parse_error::create(106, 0,
  8150. "array index '" + reference_token +
  8151. "' must not begin with '0'"));
  8152. }
  8153. // note: at performs range check
  8154. JSON_TRY
  8155. {
  8156. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  8157. }
  8158. JSON_CATCH(std::invalid_argument&)
  8159. {
  8160. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  8161. }
  8162. break;
  8163. }
  8164. default:
  8165. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  8166. }
  8167. }
  8168. return *ptr;
  8169. }
  8170. /*!
  8171. @brief split the string input to reference tokens
  8172. @note This function is only called by the json_pointer constructor.
  8173. All exceptions below are documented there.
  8174. @throw parse_error.107 if the pointer is not empty or begins with '/'
  8175. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  8176. */
  8177. static std::vector<std::string> split(const std::string& reference_string)
  8178. {
  8179. std::vector<std::string> result;
  8180. // special case: empty reference string -> no reference tokens
  8181. if (reference_string.empty())
  8182. {
  8183. return result;
  8184. }
  8185. // check if nonempty reference string begins with slash
  8186. if (JSON_UNLIKELY(reference_string[0] != '/'))
  8187. {
  8188. JSON_THROW(detail::parse_error::create(107, 1,
  8189. "JSON pointer must be empty or begin with '/' - was: '" +
  8190. reference_string + "'"));
  8191. }
  8192. // extract the reference tokens:
  8193. // - slash: position of the last read slash (or end of string)
  8194. // - start: position after the previous slash
  8195. for (
  8196. // search for the first slash after the first character
  8197. std::size_t slash = reference_string.find_first_of('/', 1),
  8198. // set the beginning of the first reference token
  8199. start = 1;
  8200. // we can stop if start == string::npos+1 = 0
  8201. start != 0;
  8202. // set the beginning of the next reference token
  8203. // (will eventually be 0 if slash == std::string::npos)
  8204. start = slash + 1,
  8205. // find next slash
  8206. slash = reference_string.find_first_of('/', start))
  8207. {
  8208. // use the text between the beginning of the reference token
  8209. // (start) and the last slash (slash).
  8210. auto reference_token = reference_string.substr(start, slash - start);
  8211. // check reference tokens are properly escaped
  8212. for (std::size_t pos = reference_token.find_first_of('~');
  8213. pos != std::string::npos;
  8214. pos = reference_token.find_first_of('~', pos + 1))
  8215. {
  8216. assert(reference_token[pos] == '~');
  8217. // ~ must be followed by 0 or 1
  8218. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  8219. (reference_token[pos + 1] != '0' and
  8220. reference_token[pos + 1] != '1')))
  8221. {
  8222. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  8223. }
  8224. }
  8225. // finally, store the reference token
  8226. unescape(reference_token);
  8227. result.push_back(reference_token);
  8228. }
  8229. return result;
  8230. }
  8231. /*!
  8232. @brief replace all occurrences of a substring by another string
  8233. @param[in,out] s the string to manipulate; changed so that all
  8234. occurrences of @a f are replaced with @a t
  8235. @param[in] f the substring to replace with @a t
  8236. @param[in] t the string to replace @a f
  8237. @pre The search string @a f must not be empty. **This precondition is
  8238. enforced with an assertion.**
  8239. @since version 2.0.0
  8240. */
  8241. static void replace_substring(std::string& s, const std::string& f,
  8242. const std::string& t)
  8243. {
  8244. assert(not f.empty());
  8245. for (auto pos = s.find(f); // find first occurrence of f
  8246. pos != std::string::npos; // make sure f was found
  8247. s.replace(pos, f.size(), t), // replace with t, and
  8248. pos = s.find(f, pos + t.size())) // find next occurrence of f
  8249. {}
  8250. }
  8251. /// escape "~"" to "~0" and "/" to "~1"
  8252. static std::string escape(std::string s)
  8253. {
  8254. replace_substring(s, "~", "~0");
  8255. replace_substring(s, "/", "~1");
  8256. return s;
  8257. }
  8258. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  8259. static void unescape(std::string& s)
  8260. {
  8261. replace_substring(s, "~1", "/");
  8262. replace_substring(s, "~0", "~");
  8263. }
  8264. /*!
  8265. @param[in] reference_string the reference string to the current value
  8266. @param[in] value the value to consider
  8267. @param[in,out] result the result object to insert values to
  8268. @note Empty objects or arrays are flattened to `null`.
  8269. */
  8270. static void flatten(const std::string& reference_string,
  8271. const BasicJsonType& value,
  8272. BasicJsonType& result)
  8273. {
  8274. switch (value.m_type)
  8275. {
  8276. case detail::value_t::array:
  8277. {
  8278. if (value.m_value.array->empty())
  8279. {
  8280. // flatten empty array as null
  8281. result[reference_string] = nullptr;
  8282. }
  8283. else
  8284. {
  8285. // iterate array and use index as reference string
  8286. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  8287. {
  8288. flatten(reference_string + "/" + std::to_string(i),
  8289. value.m_value.array->operator[](i), result);
  8290. }
  8291. }
  8292. break;
  8293. }
  8294. case detail::value_t::object:
  8295. {
  8296. if (value.m_value.object->empty())
  8297. {
  8298. // flatten empty object as null
  8299. result[reference_string] = nullptr;
  8300. }
  8301. else
  8302. {
  8303. // iterate object and use keys as reference string
  8304. for (const auto& element : *value.m_value.object)
  8305. {
  8306. flatten(reference_string + "/" + escape(element.first), element.second, result);
  8307. }
  8308. }
  8309. break;
  8310. }
  8311. default:
  8312. {
  8313. // add primitive value with its reference string
  8314. result[reference_string] = value;
  8315. break;
  8316. }
  8317. }
  8318. }
  8319. /*!
  8320. @param[in] value flattened JSON
  8321. @return unflattened JSON
  8322. @throw parse_error.109 if array index is not a number
  8323. @throw type_error.314 if value is not an object
  8324. @throw type_error.315 if object values are not primitive
  8325. @throw type_error.313 if value cannot be unflattened
  8326. */
  8327. static BasicJsonType
  8328. unflatten(const BasicJsonType& value)
  8329. {
  8330. if (JSON_UNLIKELY(not value.is_object()))
  8331. {
  8332. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  8333. }
  8334. BasicJsonType result;
  8335. // iterate the JSON object values
  8336. for (const auto& element : *value.m_value.object)
  8337. {
  8338. if (JSON_UNLIKELY(not element.second.is_primitive()))
  8339. {
  8340. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  8341. }
  8342. // assign value to reference pointed to by JSON pointer; Note that if
  8343. // the JSON pointer is "" (i.e., points to the whole value), function
  8344. // get_and_create returns a reference to result itself. An assignment
  8345. // will then create a primitive value.
  8346. json_pointer(element.first).get_and_create(result) = element.second;
  8347. }
  8348. return result;
  8349. }
  8350. friend bool operator==(json_pointer const& lhs,
  8351. json_pointer const& rhs) noexcept
  8352. {
  8353. return (lhs.reference_tokens == rhs.reference_tokens);
  8354. }
  8355. friend bool operator!=(json_pointer const& lhs,
  8356. json_pointer const& rhs) noexcept
  8357. {
  8358. return not (lhs == rhs);
  8359. }
  8360. /// the reference tokens
  8361. std::vector<std::string> reference_tokens;
  8362. };
  8363. }
  8364. // #include <nlohmann/adl_serializer.hpp>
  8365. #include <utility>
  8366. // #include <nlohmann/detail/conversions/from_json.hpp>
  8367. // #include <nlohmann/detail/conversions/to_json.hpp>
  8368. namespace nlohmann
  8369. {
  8370. template<typename, typename>
  8371. struct adl_serializer
  8372. {
  8373. /*!
  8374. @brief convert a JSON value to any value type
  8375. This function is usually called by the `get()` function of the
  8376. @ref basic_json class (either explicit or via conversion operators).
  8377. @param[in] j JSON value to read from
  8378. @param[in,out] val value to write to
  8379. */
  8380. template<typename BasicJsonType, typename ValueType>
  8381. static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
  8382. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  8383. {
  8384. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  8385. }
  8386. /*!
  8387. @brief convert any value type to a JSON value
  8388. This function is usually called by the constructors of the @ref basic_json
  8389. class.
  8390. @param[in,out] j JSON value to write to
  8391. @param[in] val value to read from
  8392. */
  8393. template<typename BasicJsonType, typename ValueType>
  8394. static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
  8395. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  8396. {
  8397. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  8398. }
  8399. };
  8400. }
  8401. /*!
  8402. @brief namespace for Niels Lohmann
  8403. @see https://github.com/nlohmann
  8404. @since version 1.0.0
  8405. */
  8406. namespace nlohmann
  8407. {
  8408. /*!
  8409. @brief a class to store JSON values
  8410. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  8411. in @ref object_t)
  8412. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  8413. in @ref array_t)
  8414. @tparam StringType type for JSON strings and object keys (`std::string` by
  8415. default; will be used in @ref string_t)
  8416. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  8417. in @ref boolean_t)
  8418. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  8419. default; will be used in @ref number_integer_t)
  8420. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  8421. `uint64_t` by default; will be used in @ref number_unsigned_t)
  8422. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  8423. default; will be used in @ref number_float_t)
  8424. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  8425. default)
  8426. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  8427. and `from_json()` (@ref adl_serializer by default)
  8428. @requirement The class satisfies the following concept requirements:
  8429. - Basic
  8430. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  8431. JSON values can be default constructed. The result will be a JSON null
  8432. value.
  8433. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  8434. A JSON value can be constructed from an rvalue argument.
  8435. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  8436. A JSON value can be copy-constructed from an lvalue expression.
  8437. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  8438. A JSON value van be assigned from an rvalue argument.
  8439. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  8440. A JSON value can be copy-assigned from an lvalue expression.
  8441. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  8442. JSON values can be destructed.
  8443. - Layout
  8444. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  8445. JSON values have
  8446. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  8447. All non-static data members are private and standard layout types, the
  8448. class has no virtual functions or (virtual) base classes.
  8449. - Library-wide
  8450. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  8451. JSON values can be compared with `==`, see @ref
  8452. operator==(const_reference,const_reference).
  8453. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  8454. JSON values can be compared with `<`, see @ref
  8455. operator<(const_reference,const_reference).
  8456. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  8457. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  8458. other compatible types, using unqualified function call @ref swap().
  8459. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  8460. JSON values can be compared against `std::nullptr_t` objects which are used
  8461. to model the `null` value.
  8462. - Container
  8463. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  8464. JSON values can be used like STL containers and provide iterator access.
  8465. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  8466. JSON values can be used like STL containers and provide reverse iterator
  8467. access.
  8468. @invariant The member variables @a m_value and @a m_type have the following
  8469. relationship:
  8470. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  8471. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  8472. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  8473. The invariants are checked by member function assert_invariant().
  8474. @internal
  8475. @note ObjectType trick from http://stackoverflow.com/a/9860911
  8476. @endinternal
  8477. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  8478. Format](http://rfc7159.net/rfc7159)
  8479. @since version 1.0.0
  8480. @nosubgrouping
  8481. */
  8482. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  8483. class basic_json
  8484. {
  8485. private:
  8486. template<detail::value_t> friend struct detail::external_constructor;
  8487. friend ::nlohmann::json_pointer<basic_json>;
  8488. friend ::nlohmann::detail::parser<basic_json>;
  8489. friend ::nlohmann::detail::serializer<basic_json>;
  8490. template<typename BasicJsonType>
  8491. friend class ::nlohmann::detail::iter_impl;
  8492. template<typename BasicJsonType, typename CharType>
  8493. friend class ::nlohmann::detail::binary_writer;
  8494. template<typename BasicJsonType>
  8495. friend class ::nlohmann::detail::binary_reader;
  8496. /// workaround type for MSVC
  8497. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  8498. // convenience aliases for types residing in namespace detail;
  8499. using lexer = ::nlohmann::detail::lexer<basic_json>;
  8500. using parser = ::nlohmann::detail::parser<basic_json>;
  8501. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  8502. template<typename BasicJsonType>
  8503. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  8504. template<typename BasicJsonType>
  8505. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  8506. template<typename Iterator>
  8507. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  8508. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  8509. template<typename CharType>
  8510. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  8511. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  8512. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  8513. using serializer = ::nlohmann::detail::serializer<basic_json>;
  8514. public:
  8515. using value_t = detail::value_t;
  8516. /// @copydoc nlohmann::json_pointer
  8517. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  8518. template<typename T, typename SFINAE>
  8519. using json_serializer = JSONSerializer<T, SFINAE>;
  8520. /// helper type for initializer lists of basic_json values
  8521. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  8522. ////////////////
  8523. // exceptions //
  8524. ////////////////
  8525. /// @name exceptions
  8526. /// Classes to implement user-defined exceptions.
  8527. /// @{
  8528. /// @copydoc detail::exception
  8529. using exception = detail::exception;
  8530. /// @copydoc detail::parse_error
  8531. using parse_error = detail::parse_error;
  8532. /// @copydoc detail::invalid_iterator
  8533. using invalid_iterator = detail::invalid_iterator;
  8534. /// @copydoc detail::type_error
  8535. using type_error = detail::type_error;
  8536. /// @copydoc detail::out_of_range
  8537. using out_of_range = detail::out_of_range;
  8538. /// @copydoc detail::other_error
  8539. using other_error = detail::other_error;
  8540. /// @}
  8541. /////////////////////
  8542. // container types //
  8543. /////////////////////
  8544. /// @name container types
  8545. /// The canonic container types to use @ref basic_json like any other STL
  8546. /// container.
  8547. /// @{
  8548. /// the type of elements in a basic_json container
  8549. using value_type = basic_json;
  8550. /// the type of an element reference
  8551. using reference = value_type&;
  8552. /// the type of an element const reference
  8553. using const_reference = const value_type&;
  8554. /// a type to represent differences between iterators
  8555. using difference_type = std::ptrdiff_t;
  8556. /// a type to represent container sizes
  8557. using size_type = std::size_t;
  8558. /// the allocator type
  8559. using allocator_type = AllocatorType<basic_json>;
  8560. /// the type of an element pointer
  8561. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  8562. /// the type of an element const pointer
  8563. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  8564. /// an iterator for a basic_json container
  8565. using iterator = iter_impl<basic_json>;
  8566. /// a const iterator for a basic_json container
  8567. using const_iterator = iter_impl<const basic_json>;
  8568. /// a reverse iterator for a basic_json container
  8569. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  8570. /// a const reverse iterator for a basic_json container
  8571. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  8572. /// @}
  8573. /*!
  8574. @brief returns the allocator associated with the container
  8575. */
  8576. static allocator_type get_allocator()
  8577. {
  8578. return allocator_type();
  8579. }
  8580. /*!
  8581. @brief returns version information on the library
  8582. This function returns a JSON object with information about the library,
  8583. including the version number and information on the platform and compiler.
  8584. @return JSON object holding version information
  8585. key | description
  8586. ----------- | ---------------
  8587. `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).
  8588. `copyright` | The copyright line for the library as string.
  8589. `name` | The name of the library as string.
  8590. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  8591. `url` | The URL of the project as string.
  8592. `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).
  8593. @liveexample{The following code shows an example output of the `meta()`
  8594. function.,meta}
  8595. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8596. changes to any JSON value.
  8597. @complexity Constant.
  8598. @since 2.1.0
  8599. */
  8600. static basic_json meta()
  8601. {
  8602. basic_json result;
  8603. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  8604. result["name"] = "JSON for Modern C++";
  8605. result["url"] = "https://github.com/nlohmann/json";
  8606. result["version"]["string"] =
  8607. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  8608. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  8609. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  8610. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  8611. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  8612. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  8613. #ifdef _WIN32
  8614. result["platform"] = "win32";
  8615. #elif defined __linux__
  8616. result["platform"] = "linux";
  8617. #elif defined __APPLE__
  8618. result["platform"] = "apple";
  8619. #elif defined __unix__
  8620. result["platform"] = "unix";
  8621. #else
  8622. result["platform"] = "unknown";
  8623. #endif
  8624. #if defined(__ICC) || defined(__INTEL_COMPILER)
  8625. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  8626. #elif defined(__clang__)
  8627. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  8628. #elif defined(__GNUC__) || defined(__GNUG__)
  8629. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  8630. #elif defined(__HP_cc) || defined(__HP_aCC)
  8631. result["compiler"] = "hp"
  8632. #elif defined(__IBMCPP__)
  8633. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  8634. #elif defined(_MSC_VER)
  8635. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  8636. #elif defined(__PGI)
  8637. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  8638. #elif defined(__SUNPRO_CC)
  8639. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  8640. #else
  8641. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  8642. #endif
  8643. #ifdef __cplusplus
  8644. result["compiler"]["c++"] = std::to_string(__cplusplus);
  8645. #else
  8646. result["compiler"]["c++"] = "unknown";
  8647. #endif
  8648. return result;
  8649. }
  8650. ///////////////////////////
  8651. // JSON value data types //
  8652. ///////////////////////////
  8653. /// @name JSON value data types
  8654. /// The data types to store a JSON value. These types are derived from
  8655. /// the template arguments passed to class @ref basic_json.
  8656. /// @{
  8657. #if defined(JSON_HAS_CPP_14)
  8658. // Use transparent comparator if possible, combined with perfect forwarding
  8659. // on find() and count() calls prevents unnecessary string construction.
  8660. using object_comparator_t = std::less<>;
  8661. #else
  8662. using object_comparator_t = std::less<StringType>;
  8663. #endif
  8664. /*!
  8665. @brief a type for an object
  8666. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  8667. > An object is an unordered collection of zero or more name/value pairs,
  8668. > where a name is a string and a value is a string, number, boolean, null,
  8669. > object, or array.
  8670. To store objects in C++, a type is defined by the template parameters
  8671. described below.
  8672. @tparam ObjectType the container to store objects (e.g., `std::map` or
  8673. `std::unordered_map`)
  8674. @tparam StringType the type of the keys or names (e.g., `std::string`).
  8675. The comparison function `std::less<StringType>` is used to order elements
  8676. inside the container.
  8677. @tparam AllocatorType the allocator to use for objects (e.g.,
  8678. `std::allocator`)
  8679. #### Default type
  8680. With the default values for @a ObjectType (`std::map`), @a StringType
  8681. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  8682. value for @a object_t is:
  8683. @code {.cpp}
  8684. std::map<
  8685. std::string, // key_type
  8686. basic_json, // value_type
  8687. std::less<std::string>, // key_compare
  8688. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  8689. >
  8690. @endcode
  8691. #### Behavior
  8692. The choice of @a object_t influences the behavior of the JSON class. With
  8693. the default type, objects have the following behavior:
  8694. - When all names are unique, objects will be interoperable in the sense
  8695. that all software implementations receiving that object will agree on
  8696. the name-value mappings.
  8697. - When the names within an object are not unique, it is unspecified which
  8698. one of the values for a given key will be chosen. For instance,
  8699. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  8700. `{"key": 2}`.
  8701. - Internally, name/value pairs are stored in lexicographical order of the
  8702. names. Objects will also be serialized (see @ref dump) in this order.
  8703. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  8704. and serialized as `{"a": 2, "b": 1}`.
  8705. - When comparing objects, the order of the name/value pairs is irrelevant.
  8706. This makes objects interoperable in the sense that they will not be
  8707. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  8708. `{"a": 2, "b": 1}` will be treated as equal.
  8709. #### Limits
  8710. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  8711. > An implementation may set limits on the maximum depth of nesting.
  8712. In this class, the object's limit of nesting is not explicitly constrained.
  8713. However, a maximum depth of nesting may be introduced by the compiler or
  8714. runtime environment. A theoretical limit can be queried by calling the
  8715. @ref max_size function of a JSON object.
  8716. #### Storage
  8717. Objects are stored as pointers in a @ref basic_json type. That is, for any
  8718. access to object values, a pointer of type `object_t*` must be
  8719. dereferenced.
  8720. @sa @ref array_t -- type for an array value
  8721. @since version 1.0.0
  8722. @note The order name/value pairs are added to the object is *not*
  8723. preserved by the library. Therefore, iterating an object may return
  8724. name/value pairs in a different order than they were originally stored. In
  8725. fact, keys will be traversed in alphabetical order as `std::map` with
  8726. `std::less` is used by default. Please note this behavior conforms to [RFC
  8727. 7159](http://rfc7159.net/rfc7159), because any order implements the
  8728. specified "unordered" nature of JSON objects.
  8729. */
  8730. using object_t = ObjectType<StringType,
  8731. basic_json,
  8732. object_comparator_t,
  8733. AllocatorType<std::pair<const StringType,
  8734. basic_json>>>;
  8735. /*!
  8736. @brief a type for an array
  8737. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  8738. > An array is an ordered sequence of zero or more values.
  8739. To store objects in C++, a type is defined by the template parameters
  8740. explained below.
  8741. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  8742. `std::list`)
  8743. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  8744. #### Default type
  8745. With the default values for @a ArrayType (`std::vector`) and @a
  8746. AllocatorType (`std::allocator`), the default value for @a array_t is:
  8747. @code {.cpp}
  8748. std::vector<
  8749. basic_json, // value_type
  8750. std::allocator<basic_json> // allocator_type
  8751. >
  8752. @endcode
  8753. #### Limits
  8754. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  8755. > An implementation may set limits on the maximum depth of nesting.
  8756. In this class, the array's limit of nesting is not explicitly constrained.
  8757. However, a maximum depth of nesting may be introduced by the compiler or
  8758. runtime environment. A theoretical limit can be queried by calling the
  8759. @ref max_size function of a JSON array.
  8760. #### Storage
  8761. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  8762. access to array values, a pointer of type `array_t*` must be dereferenced.
  8763. @sa @ref object_t -- type for an object value
  8764. @since version 1.0.0
  8765. */
  8766. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  8767. /*!
  8768. @brief a type for a string
  8769. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  8770. > A string is a sequence of zero or more Unicode characters.
  8771. To store objects in C++, a type is defined by the template parameter
  8772. described below. Unicode values are split by the JSON class into
  8773. byte-sized characters during deserialization.
  8774. @tparam StringType the container to store strings (e.g., `std::string`).
  8775. Note this container is used for keys/names in objects, see @ref object_t.
  8776. #### Default type
  8777. With the default values for @a StringType (`std::string`), the default
  8778. value for @a string_t is:
  8779. @code {.cpp}
  8780. std::string
  8781. @endcode
  8782. #### Encoding
  8783. Strings are stored in UTF-8 encoding. Therefore, functions like
  8784. `std::string::size()` or `std::string::length()` return the number of
  8785. bytes in the string rather than the number of characters or glyphs.
  8786. #### String comparison
  8787. [RFC 7159](http://rfc7159.net/rfc7159) states:
  8788. > Software implementations are typically required to test names of object
  8789. > members for equality. Implementations that transform the textual
  8790. > representation into sequences of Unicode code units and then perform the
  8791. > comparison numerically, code unit by code unit, are interoperable in the
  8792. > sense that implementations will agree in all cases on equality or
  8793. > inequality of two strings. For example, implementations that compare
  8794. > strings with escaped characters unconverted may incorrectly find that
  8795. > `"a\\b"` and `"a\u005Cb"` are not equal.
  8796. This implementation is interoperable as it does compare strings code unit
  8797. by code unit.
  8798. #### Storage
  8799. String values are stored as pointers in a @ref basic_json type. That is,
  8800. for any access to string values, a pointer of type `string_t*` must be
  8801. dereferenced.
  8802. @since version 1.0.0
  8803. */
  8804. using string_t = StringType;
  8805. /*!
  8806. @brief a type for a boolean
  8807. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  8808. type which differentiates the two literals `true` and `false`.
  8809. To store objects in C++, a type is defined by the template parameter @a
  8810. BooleanType which chooses the type to use.
  8811. #### Default type
  8812. With the default values for @a BooleanType (`bool`), the default value for
  8813. @a boolean_t is:
  8814. @code {.cpp}
  8815. bool
  8816. @endcode
  8817. #### Storage
  8818. Boolean values are stored directly inside a @ref basic_json type.
  8819. @since version 1.0.0
  8820. */
  8821. using boolean_t = BooleanType;
  8822. /*!
  8823. @brief a type for a number (integer)
  8824. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  8825. > The representation of numbers is similar to that used in most
  8826. > programming languages. A number is represented in base 10 using decimal
  8827. > digits. It contains an integer component that may be prefixed with an
  8828. > optional minus sign, which may be followed by a fraction part and/or an
  8829. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  8830. > cannot be represented in the grammar below (such as Infinity and NaN)
  8831. > are not permitted.
  8832. This description includes both integer and floating-point numbers.
  8833. However, C++ allows more precise storage if it is known whether the number
  8834. is a signed integer, an unsigned integer or a floating-point number.
  8835. Therefore, three different types, @ref number_integer_t, @ref
  8836. number_unsigned_t and @ref number_float_t are used.
  8837. To store integer numbers in C++, a type is defined by the template
  8838. parameter @a NumberIntegerType which chooses the type to use.
  8839. #### Default type
  8840. With the default values for @a NumberIntegerType (`int64_t`), the default
  8841. value for @a number_integer_t is:
  8842. @code {.cpp}
  8843. int64_t
  8844. @endcode
  8845. #### Default behavior
  8846. - The restrictions about leading zeros is not enforced in C++. Instead,
  8847. leading zeros in integer literals lead to an interpretation as octal
  8848. number. Internally, the value will be stored as decimal number. For
  8849. instance, the C++ integer literal `010` will be serialized to `8`.
  8850. During deserialization, leading zeros yield an error.
  8851. - Not-a-number (NaN) values will be serialized to `null`.
  8852. #### Limits
  8853. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  8854. > An implementation may set limits on the range and precision of numbers.
  8855. When the default type is used, the maximal integer number that can be
  8856. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  8857. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  8858. that are out of range will yield over/underflow when used in a
  8859. constructor. During deserialization, too large or small integer numbers
  8860. will be automatically be stored as @ref number_unsigned_t or @ref
  8861. number_float_t.
  8862. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  8863. > Note that when such software is used, numbers that are integers and are
  8864. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  8865. > that implementations will agree exactly on their numeric values.
  8866. As this range is a subrange of the exactly supported range [INT64_MIN,
  8867. INT64_MAX], this class's integer type is interoperable.
  8868. #### Storage
  8869. Integer number values are stored directly inside a @ref basic_json type.
  8870. @sa @ref number_float_t -- type for number values (floating-point)
  8871. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  8872. @since version 1.0.0
  8873. */
  8874. using number_integer_t = NumberIntegerType;
  8875. /*!
  8876. @brief a type for a number (unsigned)
  8877. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  8878. > The representation of numbers is similar to that used in most
  8879. > programming languages. A number is represented in base 10 using decimal
  8880. > digits. It contains an integer component that may be prefixed with an
  8881. > optional minus sign, which may be followed by a fraction part and/or an
  8882. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  8883. > cannot be represented in the grammar below (such as Infinity and NaN)
  8884. > are not permitted.
  8885. This description includes both integer and floating-point numbers.
  8886. However, C++ allows more precise storage if it is known whether the number
  8887. is a signed integer, an unsigned integer or a floating-point number.
  8888. Therefore, three different types, @ref number_integer_t, @ref
  8889. number_unsigned_t and @ref number_float_t are used.
  8890. To store unsigned integer numbers in C++, a type is defined by the
  8891. template parameter @a NumberUnsignedType which chooses the type to use.
  8892. #### Default type
  8893. With the default values for @a NumberUnsignedType (`uint64_t`), the
  8894. default value for @a number_unsigned_t is:
  8895. @code {.cpp}
  8896. uint64_t
  8897. @endcode
  8898. #### Default behavior
  8899. - The restrictions about leading zeros is not enforced in C++. Instead,
  8900. leading zeros in integer literals lead to an interpretation as octal
  8901. number. Internally, the value will be stored as decimal number. For
  8902. instance, the C++ integer literal `010` will be serialized to `8`.
  8903. During deserialization, leading zeros yield an error.
  8904. - Not-a-number (NaN) values will be serialized to `null`.
  8905. #### Limits
  8906. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  8907. > An implementation may set limits on the range and precision of numbers.
  8908. When the default type is used, the maximal integer number that can be
  8909. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  8910. number that can be stored is `0`. Integer numbers that are out of range
  8911. will yield over/underflow when used in a constructor. During
  8912. deserialization, too large or small integer numbers will be automatically
  8913. be stored as @ref number_integer_t or @ref number_float_t.
  8914. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  8915. > Note that when such software is used, numbers that are integers and are
  8916. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  8917. > that implementations will agree exactly on their numeric values.
  8918. As this range is a subrange (when considered in conjunction with the
  8919. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  8920. this class's integer type is interoperable.
  8921. #### Storage
  8922. Integer number values are stored directly inside a @ref basic_json type.
  8923. @sa @ref number_float_t -- type for number values (floating-point)
  8924. @sa @ref number_integer_t -- type for number values (integer)
  8925. @since version 2.0.0
  8926. */
  8927. using number_unsigned_t = NumberUnsignedType;
  8928. /*!
  8929. @brief a type for a number (floating-point)
  8930. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  8931. > The representation of numbers is similar to that used in most
  8932. > programming languages. A number is represented in base 10 using decimal
  8933. > digits. It contains an integer component that may be prefixed with an
  8934. > optional minus sign, which may be followed by a fraction part and/or an
  8935. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  8936. > cannot be represented in the grammar below (such as Infinity and NaN)
  8937. > are not permitted.
  8938. This description includes both integer and floating-point numbers.
  8939. However, C++ allows more precise storage if it is known whether the number
  8940. is a signed integer, an unsigned integer or a floating-point number.
  8941. Therefore, three different types, @ref number_integer_t, @ref
  8942. number_unsigned_t and @ref number_float_t are used.
  8943. To store floating-point numbers in C++, a type is defined by the template
  8944. parameter @a NumberFloatType which chooses the type to use.
  8945. #### Default type
  8946. With the default values for @a NumberFloatType (`double`), the default
  8947. value for @a number_float_t is:
  8948. @code {.cpp}
  8949. double
  8950. @endcode
  8951. #### Default behavior
  8952. - The restrictions about leading zeros is not enforced in C++. Instead,
  8953. leading zeros in floating-point literals will be ignored. Internally,
  8954. the value will be stored as decimal number. For instance, the C++
  8955. floating-point literal `01.2` will be serialized to `1.2`. During
  8956. deserialization, leading zeros yield an error.
  8957. - Not-a-number (NaN) values will be serialized to `null`.
  8958. #### Limits
  8959. [RFC 7159](http://rfc7159.net/rfc7159) states:
  8960. > This specification allows implementations to set limits on the range and
  8961. > precision of numbers accepted. Since software that implements IEEE
  8962. > 754-2008 binary64 (double precision) numbers is generally available and
  8963. > widely used, good interoperability can be achieved by implementations
  8964. > that expect no more precision or range than these provide, in the sense
  8965. > that implementations will approximate JSON numbers within the expected
  8966. > precision.
  8967. This implementation does exactly follow this approach, as it uses double
  8968. precision floating-point numbers. Note values smaller than
  8969. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  8970. will be stored as NaN internally and be serialized to `null`.
  8971. #### Storage
  8972. Floating-point number values are stored directly inside a @ref basic_json
  8973. type.
  8974. @sa @ref number_integer_t -- type for number values (integer)
  8975. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  8976. @since version 1.0.0
  8977. */
  8978. using number_float_t = NumberFloatType;
  8979. /// @}
  8980. private:
  8981. /// helper for exception-safe object creation
  8982. template<typename T, typename... Args>
  8983. static T* create(Args&& ... args)
  8984. {
  8985. AllocatorType<T> alloc;
  8986. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  8987. auto deleter = [&](T * object)
  8988. {
  8989. AllocatorTraits::deallocate(alloc, object, 1);
  8990. };
  8991. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  8992. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  8993. assert(object != nullptr);
  8994. return object.release();
  8995. }
  8996. ////////////////////////
  8997. // JSON value storage //
  8998. ////////////////////////
  8999. /*!
  9000. @brief a JSON value
  9001. The actual storage for a JSON value of the @ref basic_json class. This
  9002. union combines the different storage types for the JSON value types
  9003. defined in @ref value_t.
  9004. JSON type | value_t type | used type
  9005. --------- | --------------- | ------------------------
  9006. object | object | pointer to @ref object_t
  9007. array | array | pointer to @ref array_t
  9008. string | string | pointer to @ref string_t
  9009. boolean | boolean | @ref boolean_t
  9010. number | number_integer | @ref number_integer_t
  9011. number | number_unsigned | @ref number_unsigned_t
  9012. number | number_float | @ref number_float_t
  9013. null | null | *no value is stored*
  9014. @note Variable-length types (objects, arrays, and strings) are stored as
  9015. pointers. The size of the union should not exceed 64 bits if the default
  9016. value types are used.
  9017. @since version 1.0.0
  9018. */
  9019. union json_value
  9020. {
  9021. /// object (stored with pointer to save storage)
  9022. object_t* object;
  9023. /// array (stored with pointer to save storage)
  9024. array_t* array;
  9025. /// string (stored with pointer to save storage)
  9026. string_t* string;
  9027. /// boolean
  9028. boolean_t boolean;
  9029. /// number (integer)
  9030. number_integer_t number_integer;
  9031. /// number (unsigned integer)
  9032. number_unsigned_t number_unsigned;
  9033. /// number (floating-point)
  9034. number_float_t number_float;
  9035. /// default constructor (for null values)
  9036. json_value() = default;
  9037. /// constructor for booleans
  9038. json_value(boolean_t v) noexcept : boolean(v) {}
  9039. /// constructor for numbers (integer)
  9040. json_value(number_integer_t v) noexcept : number_integer(v) {}
  9041. /// constructor for numbers (unsigned)
  9042. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  9043. /// constructor for numbers (floating-point)
  9044. json_value(number_float_t v) noexcept : number_float(v) {}
  9045. /// constructor for empty values of a given type
  9046. json_value(value_t t)
  9047. {
  9048. switch (t)
  9049. {
  9050. case value_t::object:
  9051. {
  9052. object = create<object_t>();
  9053. break;
  9054. }
  9055. case value_t::array:
  9056. {
  9057. array = create<array_t>();
  9058. break;
  9059. }
  9060. case value_t::string:
  9061. {
  9062. string = create<string_t>("");
  9063. break;
  9064. }
  9065. case value_t::boolean:
  9066. {
  9067. boolean = boolean_t(false);
  9068. break;
  9069. }
  9070. case value_t::number_integer:
  9071. {
  9072. number_integer = number_integer_t(0);
  9073. break;
  9074. }
  9075. case value_t::number_unsigned:
  9076. {
  9077. number_unsigned = number_unsigned_t(0);
  9078. break;
  9079. }
  9080. case value_t::number_float:
  9081. {
  9082. number_float = number_float_t(0.0);
  9083. break;
  9084. }
  9085. case value_t::null:
  9086. {
  9087. object = nullptr; // silence warning, see #821
  9088. break;
  9089. }
  9090. default:
  9091. {
  9092. object = nullptr; // silence warning, see #821
  9093. if (JSON_UNLIKELY(t == value_t::null))
  9094. {
  9095. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.1.2")); // LCOV_EXCL_LINE
  9096. }
  9097. break;
  9098. }
  9099. }
  9100. }
  9101. /// constructor for strings
  9102. json_value(const string_t& value)
  9103. {
  9104. string = create<string_t>(value);
  9105. }
  9106. /// constructor for rvalue strings
  9107. json_value(string_t&& value)
  9108. {
  9109. string = create<string_t>(std::move(value));
  9110. }
  9111. /// constructor for objects
  9112. json_value(const object_t& value)
  9113. {
  9114. object = create<object_t>(value);
  9115. }
  9116. /// constructor for rvalue objects
  9117. json_value(object_t&& value)
  9118. {
  9119. object = create<object_t>(std::move(value));
  9120. }
  9121. /// constructor for arrays
  9122. json_value(const array_t& value)
  9123. {
  9124. array = create<array_t>(value);
  9125. }
  9126. /// constructor for rvalue arrays
  9127. json_value(array_t&& value)
  9128. {
  9129. array = create<array_t>(std::move(value));
  9130. }
  9131. void destroy(value_t t) noexcept
  9132. {
  9133. switch (t)
  9134. {
  9135. case value_t::object:
  9136. {
  9137. AllocatorType<object_t> alloc;
  9138. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  9139. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  9140. break;
  9141. }
  9142. case value_t::array:
  9143. {
  9144. AllocatorType<array_t> alloc;
  9145. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  9146. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  9147. break;
  9148. }
  9149. case value_t::string:
  9150. {
  9151. AllocatorType<string_t> alloc;
  9152. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  9153. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  9154. break;
  9155. }
  9156. default:
  9157. {
  9158. break;
  9159. }
  9160. }
  9161. }
  9162. };
  9163. /*!
  9164. @brief checks the class invariants
  9165. This function asserts the class invariants. It needs to be called at the
  9166. end of every constructor to make sure that created objects respect the
  9167. invariant. Furthermore, it has to be called each time the type of a JSON
  9168. value is changed, because the invariant expresses a relationship between
  9169. @a m_type and @a m_value.
  9170. */
  9171. void assert_invariant() const noexcept
  9172. {
  9173. assert(m_type != value_t::object or m_value.object != nullptr);
  9174. assert(m_type != value_t::array or m_value.array != nullptr);
  9175. assert(m_type != value_t::string or m_value.string != nullptr);
  9176. }
  9177. public:
  9178. //////////////////////////
  9179. // JSON parser callback //
  9180. //////////////////////////
  9181. /*!
  9182. @brief parser event types
  9183. The parser callback distinguishes the following events:
  9184. - `object_start`: the parser read `{` and started to process a JSON object
  9185. - `key`: the parser read a key of a value in an object
  9186. - `object_end`: the parser read `}` and finished processing a JSON object
  9187. - `array_start`: the parser read `[` and started to process a JSON array
  9188. - `array_end`: the parser read `]` and finished processing a JSON array
  9189. - `value`: the parser finished reading a JSON value
  9190. @image html callback_events.png "Example when certain parse events are triggered"
  9191. @sa @ref parser_callback_t for more information and examples
  9192. */
  9193. using parse_event_t = typename parser::parse_event_t;
  9194. /*!
  9195. @brief per-element parser callback type
  9196. With a parser callback function, the result of parsing a JSON text can be
  9197. influenced. When passed to @ref parse, it is called on certain events
  9198. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  9199. depth @a depth and context JSON value @a parsed. The return value of the
  9200. callback function is a boolean indicating whether the element that emitted
  9201. the callback shall be kept or not.
  9202. We distinguish six scenarios (determined by the event type) in which the
  9203. callback function can be called. The following table describes the values
  9204. of the parameters @a depth, @a event, and @a parsed.
  9205. parameter @a event | description | parameter @a depth | parameter @a parsed
  9206. ------------------ | ----------- | ------------------ | -------------------
  9207. 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
  9208. 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
  9209. 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
  9210. 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
  9211. 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
  9212. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  9213. @image html callback_events.png "Example when certain parse events are triggered"
  9214. Discarding a value (i.e., returning `false`) has different effects
  9215. depending on the context in which function was called:
  9216. - Discarded values in structured types are skipped. That is, the parser
  9217. will behave as if the discarded value was never read.
  9218. - In case a value outside a structured type is skipped, it is replaced
  9219. with `null`. This case happens if the top-level element is skipped.
  9220. @param[in] depth the depth of the recursion during parsing
  9221. @param[in] event an event of type parse_event_t indicating the context in
  9222. the callback function has been called
  9223. @param[in,out] parsed the current intermediate parse result; note that
  9224. writing to this value has no effect for parse_event_t::key events
  9225. @return Whether the JSON value which called the function during parsing
  9226. should be kept (`true`) or not (`false`). In the latter case, it is either
  9227. skipped completely or replaced by an empty discarded object.
  9228. @sa @ref parse for examples
  9229. @since version 1.0.0
  9230. */
  9231. using parser_callback_t = typename parser::parser_callback_t;
  9232. //////////////////
  9233. // constructors //
  9234. //////////////////
  9235. /// @name constructors and destructors
  9236. /// Constructors of class @ref basic_json, copy/move constructor, copy
  9237. /// assignment, static functions creating objects, and the destructor.
  9238. /// @{
  9239. /*!
  9240. @brief create an empty value with a given type
  9241. Create an empty JSON value with a given type. The value will be default
  9242. initialized with an empty value which depends on the type:
  9243. Value type | initial value
  9244. ----------- | -------------
  9245. null | `null`
  9246. boolean | `false`
  9247. string | `""`
  9248. number | `0`
  9249. object | `{}`
  9250. array | `[]`
  9251. @param[in] v the type of the value to create
  9252. @complexity Constant.
  9253. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9254. changes to any JSON value.
  9255. @liveexample{The following code shows the constructor for different @ref
  9256. value_t values,basic_json__value_t}
  9257. @sa @ref clear() -- restores the postcondition of this constructor
  9258. @since version 1.0.0
  9259. */
  9260. basic_json(const value_t v)
  9261. : m_type(v), m_value(v)
  9262. {
  9263. assert_invariant();
  9264. }
  9265. /*!
  9266. @brief create a null object
  9267. Create a `null` JSON value. It either takes a null pointer as parameter
  9268. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  9269. The passed null pointer itself is not read -- it is only used to choose
  9270. the right constructor.
  9271. @complexity Constant.
  9272. @exceptionsafety No-throw guarantee: this constructor never throws
  9273. exceptions.
  9274. @liveexample{The following code shows the constructor with and without a
  9275. null pointer parameter.,basic_json__nullptr_t}
  9276. @since version 1.0.0
  9277. */
  9278. basic_json(std::nullptr_t = nullptr) noexcept
  9279. : basic_json(value_t::null)
  9280. {
  9281. assert_invariant();
  9282. }
  9283. /*!
  9284. @brief create a JSON value
  9285. This is a "catch all" constructor for all compatible JSON types; that is,
  9286. types for which a `to_json()` method exists. The constructor forwards the
  9287. parameter @a val to that method (to `json_serializer<U>::to_json` method
  9288. with `U = uncvref_t<CompatibleType>`, to be exact).
  9289. Template type @a CompatibleType includes, but is not limited to, the
  9290. following types:
  9291. - **arrays**: @ref array_t and all kinds of compatible containers such as
  9292. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  9293. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  9294. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  9295. which a @ref basic_json value can be constructed.
  9296. - **objects**: @ref object_t and all kinds of compatible associative
  9297. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  9298. and `std::unordered_multimap` with a `key_type` compatible to
  9299. @ref string_t and a `value_type` from which a @ref basic_json value can
  9300. be constructed.
  9301. - **strings**: @ref string_t, string literals, and all compatible string
  9302. containers can be used.
  9303. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  9304. @ref number_float_t, and all convertible number types such as `int`,
  9305. `size_t`, `int64_t`, `float` or `double` can be used.
  9306. - **boolean**: @ref boolean_t / `bool` can be used.
  9307. See the examples below.
  9308. @tparam CompatibleType a type such that:
  9309. - @a CompatibleType is not derived from `std::istream`,
  9310. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  9311. constructors),
  9312. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  9313. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  9314. @ref json_pointer, @ref iterator, etc ...)
  9315. - @ref @ref json_serializer<U> has a
  9316. `to_json(basic_json_t&, CompatibleType&&)` method
  9317. @tparam U = `uncvref_t<CompatibleType>`
  9318. @param[in] val the value to be forwarded to the respective constructor
  9319. @complexity Usually linear in the size of the passed @a val, also
  9320. depending on the implementation of the called `to_json()`
  9321. method.
  9322. @exceptionsafety Depends on the called constructor. For types directly
  9323. supported by the library (i.e., all types for which no `to_json()` function
  9324. was provided), strong guarantee holds: if an exception is thrown, there are
  9325. no changes to any JSON value.
  9326. @liveexample{The following code shows the constructor with several
  9327. compatible types.,basic_json__CompatibleType}
  9328. @since version 2.1.0
  9329. */
  9330. template <typename CompatibleType,
  9331. typename U = detail::uncvref_t<CompatibleType>,
  9332. detail::enable_if_t<
  9333. detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  9334. basic_json(CompatibleType && val) noexcept(noexcept(
  9335. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  9336. std::forward<CompatibleType>(val))))
  9337. {
  9338. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  9339. assert_invariant();
  9340. }
  9341. /*!
  9342. @brief create a JSON value from an existing one
  9343. This is a constructor for existing @ref basic_json types.
  9344. It does not hijack copy/move constructors, since the parameter has different
  9345. template arguments than the current ones.
  9346. The constructor tries to convert the internal @ref m_value of the parameter.
  9347. @tparam BasicJsonType a type such that:
  9348. - @a BasicJsonType is a @ref basic_json type.
  9349. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  9350. @param[in] val the @ref basic_json value to be converted.
  9351. @complexity Usually linear in the size of the passed @a val, also
  9352. depending on the implementation of the called `to_json()`
  9353. method.
  9354. @exceptionsafety Depends on the called constructor. For types directly
  9355. supported by the library (i.e., all types for which no `to_json()` function
  9356. was provided), strong guarantee holds: if an exception is thrown, there are
  9357. no changes to any JSON value.
  9358. @since version 3.1.2
  9359. */
  9360. template <typename BasicJsonType,
  9361. detail::enable_if_t<
  9362. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  9363. basic_json(const BasicJsonType& val)
  9364. {
  9365. using other_boolean_t = typename BasicJsonType::boolean_t;
  9366. using other_number_float_t = typename BasicJsonType::number_float_t;
  9367. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  9368. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  9369. using other_string_t = typename BasicJsonType::string_t;
  9370. using other_object_t = typename BasicJsonType::object_t;
  9371. using other_array_t = typename BasicJsonType::array_t;
  9372. switch (val.type())
  9373. {
  9374. case value_t::boolean:
  9375. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  9376. break;
  9377. case value_t::number_float:
  9378. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  9379. break;
  9380. case value_t::number_integer:
  9381. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  9382. break;
  9383. case value_t::number_unsigned:
  9384. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  9385. break;
  9386. case value_t::string:
  9387. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  9388. break;
  9389. case value_t::object:
  9390. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  9391. break;
  9392. case value_t::array:
  9393. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  9394. break;
  9395. case value_t::null:
  9396. *this = nullptr;
  9397. break;
  9398. case value_t::discarded:
  9399. m_type = value_t::discarded;
  9400. break;
  9401. }
  9402. assert_invariant();
  9403. }
  9404. /*!
  9405. @brief create a container (array or object) from an initializer list
  9406. Creates a JSON value of type array or object from the passed initializer
  9407. list @a init. In case @a type_deduction is `true` (default), the type of
  9408. the JSON value to be created is deducted from the initializer list @a init
  9409. according to the following rules:
  9410. 1. If the list is empty, an empty JSON object value `{}` is created.
  9411. 2. If the list consists of pairs whose first element is a string, a JSON
  9412. object value is created where the first elements of the pairs are
  9413. treated as keys and the second elements are as values.
  9414. 3. In all other cases, an array is created.
  9415. The rules aim to create the best fit between a C++ initializer list and
  9416. JSON values. The rationale is as follows:
  9417. 1. The empty initializer list is written as `{}` which is exactly an empty
  9418. JSON object.
  9419. 2. C++ has no way of describing mapped types other than to list a list of
  9420. pairs. As JSON requires that keys must be of type string, rule 2 is the
  9421. weakest constraint one can pose on initializer lists to interpret them
  9422. as an object.
  9423. 3. In all other cases, the initializer list could not be interpreted as
  9424. JSON object type, so interpreting it as JSON array type is safe.
  9425. With the rules described above, the following JSON values cannot be
  9426. expressed by an initializer list:
  9427. - the empty array (`[]`): use @ref array(initializer_list_t)
  9428. with an empty initializer list in this case
  9429. - arrays whose elements satisfy rule 2: use @ref
  9430. array(initializer_list_t) with the same initializer list
  9431. in this case
  9432. @note When used without parentheses around an empty initializer list, @ref
  9433. basic_json() is called instead of this function, yielding the JSON null
  9434. value.
  9435. @param[in] init initializer list with JSON values
  9436. @param[in] type_deduction internal parameter; when set to `true`, the type
  9437. of the JSON value is deducted from the initializer list @a init; when set
  9438. to `false`, the type provided via @a manual_type is forced. This mode is
  9439. used by the functions @ref array(initializer_list_t) and
  9440. @ref object(initializer_list_t).
  9441. @param[in] manual_type internal parameter; when @a type_deduction is set
  9442. to `false`, the created JSON value will use the provided type (only @ref
  9443. value_t::array and @ref value_t::object are valid); when @a type_deduction
  9444. is set to `true`, this parameter has no effect
  9445. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  9446. `value_t::object`, but @a init contains an element which is not a pair
  9447. whose first element is a string. In this case, the constructor could not
  9448. create an object. If @a type_deduction would have be `true`, an array
  9449. would have been created. See @ref object(initializer_list_t)
  9450. for an example.
  9451. @complexity Linear in the size of the initializer list @a init.
  9452. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9453. changes to any JSON value.
  9454. @liveexample{The example below shows how JSON values are created from
  9455. initializer lists.,basic_json__list_init_t}
  9456. @sa @ref array(initializer_list_t) -- create a JSON array
  9457. value from an initializer list
  9458. @sa @ref object(initializer_list_t) -- create a JSON object
  9459. value from an initializer list
  9460. @since version 1.0.0
  9461. */
  9462. basic_json(initializer_list_t init,
  9463. bool type_deduction = true,
  9464. value_t manual_type = value_t::array)
  9465. {
  9466. // check if each element is an array with two elements whose first
  9467. // element is a string
  9468. bool is_an_object = std::all_of(init.begin(), init.end(),
  9469. [](const detail::json_ref<basic_json>& element_ref)
  9470. {
  9471. return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
  9472. });
  9473. // adjust type if type deduction is not wanted
  9474. if (not type_deduction)
  9475. {
  9476. // if array is wanted, do not create an object though possible
  9477. if (manual_type == value_t::array)
  9478. {
  9479. is_an_object = false;
  9480. }
  9481. // if object is wanted but impossible, throw an exception
  9482. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  9483. {
  9484. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  9485. }
  9486. }
  9487. if (is_an_object)
  9488. {
  9489. // the initializer list is a list of pairs -> create object
  9490. m_type = value_t::object;
  9491. m_value = value_t::object;
  9492. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  9493. {
  9494. auto element = element_ref.moved_or_copied();
  9495. m_value.object->emplace(
  9496. std::move(*((*element.m_value.array)[0].m_value.string)),
  9497. std::move((*element.m_value.array)[1]));
  9498. });
  9499. }
  9500. else
  9501. {
  9502. // the initializer list describes an array -> create array
  9503. m_type = value_t::array;
  9504. m_value.array = create<array_t>(init.begin(), init.end());
  9505. }
  9506. assert_invariant();
  9507. }
  9508. /*!
  9509. @brief explicitly create an array from an initializer list
  9510. Creates a JSON array value from a given initializer list. That is, given a
  9511. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  9512. initializer list is empty, the empty array `[]` is created.
  9513. @note This function is only needed to express two edge cases that cannot
  9514. be realized with the initializer list constructor (@ref
  9515. basic_json(initializer_list_t, bool, value_t)). These cases
  9516. are:
  9517. 1. creating an array whose elements are all pairs whose first element is a
  9518. string -- in this case, the initializer list constructor would create an
  9519. object, taking the first elements as keys
  9520. 2. creating an empty array -- passing the empty initializer list to the
  9521. initializer list constructor yields an empty object
  9522. @param[in] init initializer list with JSON values to create an array from
  9523. (optional)
  9524. @return JSON array value
  9525. @complexity Linear in the size of @a init.
  9526. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9527. changes to any JSON value.
  9528. @liveexample{The following code shows an example for the `array`
  9529. function.,array}
  9530. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  9531. create a JSON value from an initializer list
  9532. @sa @ref object(initializer_list_t) -- create a JSON object
  9533. value from an initializer list
  9534. @since version 1.0.0
  9535. */
  9536. static basic_json array(initializer_list_t init = {})
  9537. {
  9538. return basic_json(init, false, value_t::array);
  9539. }
  9540. /*!
  9541. @brief explicitly create an object from an initializer list
  9542. Creates a JSON object value from a given initializer list. The initializer
  9543. lists elements must be pairs, and their first elements must be strings. If
  9544. the initializer list is empty, the empty object `{}` is created.
  9545. @note This function is only added for symmetry reasons. In contrast to the
  9546. related function @ref array(initializer_list_t), there are
  9547. no cases which can only be expressed by this function. That is, any
  9548. initializer list @a init can also be passed to the initializer list
  9549. constructor @ref basic_json(initializer_list_t, bool, value_t).
  9550. @param[in] init initializer list to create an object from (optional)
  9551. @return JSON object value
  9552. @throw type_error.301 if @a init is not a list of pairs whose first
  9553. elements are strings. In this case, no object can be created. When such a
  9554. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  9555. an array would have been created from the passed initializer list @a init.
  9556. See example below.
  9557. @complexity Linear in the size of @a init.
  9558. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9559. changes to any JSON value.
  9560. @liveexample{The following code shows an example for the `object`
  9561. function.,object}
  9562. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  9563. create a JSON value from an initializer list
  9564. @sa @ref array(initializer_list_t) -- create a JSON array
  9565. value from an initializer list
  9566. @since version 1.0.0
  9567. */
  9568. static basic_json object(initializer_list_t init = {})
  9569. {
  9570. return basic_json(init, false, value_t::object);
  9571. }
  9572. /*!
  9573. @brief construct an array with count copies of given value
  9574. Constructs a JSON array value by creating @a cnt copies of a passed value.
  9575. In case @a cnt is `0`, an empty array is created.
  9576. @param[in] cnt the number of JSON copies of @a val to create
  9577. @param[in] val the JSON value to copy
  9578. @post `std::distance(begin(),end()) == cnt` holds.
  9579. @complexity Linear in @a cnt.
  9580. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9581. changes to any JSON value.
  9582. @liveexample{The following code shows examples for the @ref
  9583. basic_json(size_type\, const basic_json&)
  9584. constructor.,basic_json__size_type_basic_json}
  9585. @since version 1.0.0
  9586. */
  9587. basic_json(size_type cnt, const basic_json& val)
  9588. : m_type(value_t::array)
  9589. {
  9590. m_value.array = create<array_t>(cnt, val);
  9591. assert_invariant();
  9592. }
  9593. /*!
  9594. @brief construct a JSON container given an iterator range
  9595. Constructs the JSON value with the contents of the range `[first, last)`.
  9596. The semantics depends on the different types a JSON value can have:
  9597. - In case of a null type, invalid_iterator.206 is thrown.
  9598. - In case of other primitive types (number, boolean, or string), @a first
  9599. must be `begin()` and @a last must be `end()`. In this case, the value is
  9600. copied. Otherwise, invalid_iterator.204 is thrown.
  9601. - In case of structured types (array, object), the constructor behaves as
  9602. similar versions for `std::vector` or `std::map`; that is, a JSON array
  9603. or object is constructed from the values in the range.
  9604. @tparam InputIT an input iterator type (@ref iterator or @ref
  9605. const_iterator)
  9606. @param[in] first begin of the range to copy from (included)
  9607. @param[in] last end of the range to copy from (excluded)
  9608. @pre Iterators @a first and @a last must be initialized. **This
  9609. precondition is enforced with an assertion (see warning).** If
  9610. assertions are switched off, a violation of this precondition yields
  9611. undefined behavior.
  9612. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  9613. checked efficiently. Only certain edge cases are detected; see the
  9614. description of the exceptions below. A violation of this precondition
  9615. yields undefined behavior.
  9616. @warning A precondition is enforced with a runtime assertion that will
  9617. result in calling `std::abort` if this precondition is not met.
  9618. Assertions can be disabled by defining `NDEBUG` at compile time.
  9619. See http://en.cppreference.com/w/cpp/error/assert for more
  9620. information.
  9621. @throw invalid_iterator.201 if iterators @a first and @a last are not
  9622. compatible (i.e., do not belong to the same JSON value). In this case,
  9623. the range `[first, last)` is undefined.
  9624. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  9625. primitive type (number, boolean, or string), but @a first does not point
  9626. to the first element any more. In this case, the range `[first, last)` is
  9627. undefined. See example code below.
  9628. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  9629. null value. In this case, the range `[first, last)` is undefined.
  9630. @complexity Linear in distance between @a first and @a last.
  9631. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9632. changes to any JSON value.
  9633. @liveexample{The example below shows several ways to create JSON values by
  9634. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  9635. @since version 1.0.0
  9636. */
  9637. template<class InputIT, typename std::enable_if<
  9638. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  9639. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  9640. basic_json(InputIT first, InputIT last)
  9641. {
  9642. assert(first.m_object != nullptr);
  9643. assert(last.m_object != nullptr);
  9644. // make sure iterator fits the current value
  9645. if (JSON_UNLIKELY(first.m_object != last.m_object))
  9646. {
  9647. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  9648. }
  9649. // copy type from first iterator
  9650. m_type = first.m_object->m_type;
  9651. // check if iterator range is complete for primitive values
  9652. switch (m_type)
  9653. {
  9654. case value_t::boolean:
  9655. case value_t::number_float:
  9656. case value_t::number_integer:
  9657. case value_t::number_unsigned:
  9658. case value_t::string:
  9659. {
  9660. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  9661. or not last.m_it.primitive_iterator.is_end()))
  9662. {
  9663. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  9664. }
  9665. break;
  9666. }
  9667. default:
  9668. break;
  9669. }
  9670. switch (m_type)
  9671. {
  9672. case value_t::number_integer:
  9673. {
  9674. m_value.number_integer = first.m_object->m_value.number_integer;
  9675. break;
  9676. }
  9677. case value_t::number_unsigned:
  9678. {
  9679. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  9680. break;
  9681. }
  9682. case value_t::number_float:
  9683. {
  9684. m_value.number_float = first.m_object->m_value.number_float;
  9685. break;
  9686. }
  9687. case value_t::boolean:
  9688. {
  9689. m_value.boolean = first.m_object->m_value.boolean;
  9690. break;
  9691. }
  9692. case value_t::string:
  9693. {
  9694. m_value = *first.m_object->m_value.string;
  9695. break;
  9696. }
  9697. case value_t::object:
  9698. {
  9699. m_value.object = create<object_t>(first.m_it.object_iterator,
  9700. last.m_it.object_iterator);
  9701. break;
  9702. }
  9703. case value_t::array:
  9704. {
  9705. m_value.array = create<array_t>(first.m_it.array_iterator,
  9706. last.m_it.array_iterator);
  9707. break;
  9708. }
  9709. default:
  9710. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  9711. std::string(first.m_object->type_name())));
  9712. }
  9713. assert_invariant();
  9714. }
  9715. ///////////////////////////////////////
  9716. // other constructors and destructor //
  9717. ///////////////////////////////////////
  9718. /// @private
  9719. basic_json(const detail::json_ref<basic_json>& ref)
  9720. : basic_json(ref.moved_or_copied())
  9721. {}
  9722. /*!
  9723. @brief copy constructor
  9724. Creates a copy of a given JSON value.
  9725. @param[in] other the JSON value to copy
  9726. @post `*this == other`
  9727. @complexity Linear in the size of @a other.
  9728. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9729. changes to any JSON value.
  9730. @requirement This function helps `basic_json` satisfying the
  9731. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9732. requirements:
  9733. - The complexity is linear.
  9734. - As postcondition, it holds: `other == basic_json(other)`.
  9735. @liveexample{The following code shows an example for the copy
  9736. constructor.,basic_json__basic_json}
  9737. @since version 1.0.0
  9738. */
  9739. basic_json(const basic_json& other)
  9740. : m_type(other.m_type)
  9741. {
  9742. // check of passed value is valid
  9743. other.assert_invariant();
  9744. switch (m_type)
  9745. {
  9746. case value_t::object:
  9747. {
  9748. m_value = *other.m_value.object;
  9749. break;
  9750. }
  9751. case value_t::array:
  9752. {
  9753. m_value = *other.m_value.array;
  9754. break;
  9755. }
  9756. case value_t::string:
  9757. {
  9758. m_value = *other.m_value.string;
  9759. break;
  9760. }
  9761. case value_t::boolean:
  9762. {
  9763. m_value = other.m_value.boolean;
  9764. break;
  9765. }
  9766. case value_t::number_integer:
  9767. {
  9768. m_value = other.m_value.number_integer;
  9769. break;
  9770. }
  9771. case value_t::number_unsigned:
  9772. {
  9773. m_value = other.m_value.number_unsigned;
  9774. break;
  9775. }
  9776. case value_t::number_float:
  9777. {
  9778. m_value = other.m_value.number_float;
  9779. break;
  9780. }
  9781. default:
  9782. break;
  9783. }
  9784. assert_invariant();
  9785. }
  9786. /*!
  9787. @brief move constructor
  9788. Move constructor. Constructs a JSON value with the contents of the given
  9789. value @a other using move semantics. It "steals" the resources from @a
  9790. other and leaves it as JSON null value.
  9791. @param[in,out] other value to move to this object
  9792. @post `*this` has the same value as @a other before the call.
  9793. @post @a other is a JSON null value.
  9794. @complexity Constant.
  9795. @exceptionsafety No-throw guarantee: this constructor never throws
  9796. exceptions.
  9797. @requirement This function helps `basic_json` satisfying the
  9798. [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
  9799. requirements.
  9800. @liveexample{The code below shows the move constructor explicitly called
  9801. via std::move.,basic_json__moveconstructor}
  9802. @since version 1.0.0
  9803. */
  9804. basic_json(basic_json&& other) noexcept
  9805. : m_type(std::move(other.m_type)),
  9806. m_value(std::move(other.m_value))
  9807. {
  9808. // check that passed value is valid
  9809. other.assert_invariant();
  9810. // invalidate payload
  9811. other.m_type = value_t::null;
  9812. other.m_value = {};
  9813. assert_invariant();
  9814. }
  9815. /*!
  9816. @brief copy assignment
  9817. Copy assignment operator. Copies a JSON value via the "copy and swap"
  9818. strategy: It is expressed in terms of the copy constructor, destructor,
  9819. and the `swap()` member function.
  9820. @param[in] other value to copy from
  9821. @complexity Linear.
  9822. @requirement This function helps `basic_json` satisfying the
  9823. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9824. requirements:
  9825. - The complexity is linear.
  9826. @liveexample{The code below shows and example for the copy assignment. It
  9827. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  9828. copy of `a` (which is the null value after the swap) is
  9829. destroyed.,basic_json__copyassignment}
  9830. @since version 1.0.0
  9831. */
  9832. reference& operator=(basic_json other) noexcept (
  9833. std::is_nothrow_move_constructible<value_t>::value and
  9834. std::is_nothrow_move_assignable<value_t>::value and
  9835. std::is_nothrow_move_constructible<json_value>::value and
  9836. std::is_nothrow_move_assignable<json_value>::value
  9837. )
  9838. {
  9839. // check that passed value is valid
  9840. other.assert_invariant();
  9841. using std::swap;
  9842. swap(m_type, other.m_type);
  9843. swap(m_value, other.m_value);
  9844. assert_invariant();
  9845. return *this;
  9846. }
  9847. /*!
  9848. @brief destructor
  9849. Destroys the JSON value and frees all allocated memory.
  9850. @complexity Linear.
  9851. @requirement This function helps `basic_json` satisfying the
  9852. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9853. requirements:
  9854. - The complexity is linear.
  9855. - All stored elements are destroyed and all memory is freed.
  9856. @since version 1.0.0
  9857. */
  9858. ~basic_json() noexcept
  9859. {
  9860. assert_invariant();
  9861. m_value.destroy(m_type);
  9862. }
  9863. /// @}
  9864. public:
  9865. ///////////////////////
  9866. // object inspection //
  9867. ///////////////////////
  9868. /// @name object inspection
  9869. /// Functions to inspect the type of a JSON value.
  9870. /// @{
  9871. /*!
  9872. @brief serialization
  9873. Serialization function for JSON values. The function tries to mimic
  9874. Python's `json.dumps()` function, and currently supports its @a indent
  9875. and @a ensure_ascii parameters.
  9876. @param[in] indent If indent is nonnegative, then array elements and object
  9877. members will be pretty-printed with that indent level. An indent level of
  9878. `0` will only insert newlines. `-1` (the default) selects the most compact
  9879. representation.
  9880. @param[in] indent_char The character to use for indentation if @a indent is
  9881. greater than `0`. The default is ` ` (space).
  9882. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  9883. in the output are escaped with `\uXXXX` sequences, and the result consists
  9884. of ASCII characters only.
  9885. @return string containing the serialization of the JSON value
  9886. @throw type_error.316 if a string stored inside the JSON value is not
  9887. UTF-8 encoded
  9888. @complexity Linear.
  9889. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9890. changes in the JSON value.
  9891. @liveexample{The following example shows the effect of different @a indent\,
  9892. @a indent_char\, and @a ensure_ascii parameters to the result of the
  9893. serialization.,dump}
  9894. @see https://docs.python.org/2/library/json.html#json.dump
  9895. @since version 1.0.0; indentation character @a indent_char, option
  9896. @a ensure_ascii and exceptions added in version 3.0.0
  9897. */
  9898. string_t dump(const int indent = -1, const char indent_char = ' ',
  9899. const bool ensure_ascii = false) const
  9900. {
  9901. string_t result;
  9902. serializer s(detail::output_adapter<char, string_t>(result), indent_char);
  9903. if (indent >= 0)
  9904. {
  9905. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  9906. }
  9907. else
  9908. {
  9909. s.dump(*this, false, ensure_ascii, 0);
  9910. }
  9911. return result;
  9912. }
  9913. /*!
  9914. @brief return the type of the JSON value (explicit)
  9915. Return the type of the JSON value as a value from the @ref value_t
  9916. enumeration.
  9917. @return the type of the JSON value
  9918. Value type | return value
  9919. ------------------------- | -------------------------
  9920. null | value_t::null
  9921. boolean | value_t::boolean
  9922. string | value_t::string
  9923. number (integer) | value_t::number_integer
  9924. number (unsigned integer) | value_t::number_unsigned
  9925. number (floating-point) | value_t::number_float
  9926. object | value_t::object
  9927. array | value_t::array
  9928. discarded | value_t::discarded
  9929. @complexity Constant.
  9930. @exceptionsafety No-throw guarantee: this member function never throws
  9931. exceptions.
  9932. @liveexample{The following code exemplifies `type()` for all JSON
  9933. types.,type}
  9934. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  9935. @sa @ref type_name() -- return the type as string
  9936. @since version 1.0.0
  9937. */
  9938. constexpr value_t type() const noexcept
  9939. {
  9940. return m_type;
  9941. }
  9942. /*!
  9943. @brief return whether type is primitive
  9944. This function returns true if and only if the JSON type is primitive
  9945. (string, number, boolean, or null).
  9946. @return `true` if type is primitive (string, number, boolean, or null),
  9947. `false` otherwise.
  9948. @complexity Constant.
  9949. @exceptionsafety No-throw guarantee: this member function never throws
  9950. exceptions.
  9951. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  9952. types.,is_primitive}
  9953. @sa @ref is_structured() -- returns whether JSON value is structured
  9954. @sa @ref is_null() -- returns whether JSON value is `null`
  9955. @sa @ref is_string() -- returns whether JSON value is a string
  9956. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  9957. @sa @ref is_number() -- returns whether JSON value is a number
  9958. @since version 1.0.0
  9959. */
  9960. constexpr bool is_primitive() const noexcept
  9961. {
  9962. return is_null() or is_string() or is_boolean() or is_number();
  9963. }
  9964. /*!
  9965. @brief return whether type is structured
  9966. This function returns true if and only if the JSON type is structured
  9967. (array or object).
  9968. @return `true` if type is structured (array or object), `false` otherwise.
  9969. @complexity Constant.
  9970. @exceptionsafety No-throw guarantee: this member function never throws
  9971. exceptions.
  9972. @liveexample{The following code exemplifies `is_structured()` for all JSON
  9973. types.,is_structured}
  9974. @sa @ref is_primitive() -- returns whether value is primitive
  9975. @sa @ref is_array() -- returns whether value is an array
  9976. @sa @ref is_object() -- returns whether value is an object
  9977. @since version 1.0.0
  9978. */
  9979. constexpr bool is_structured() const noexcept
  9980. {
  9981. return is_array() or is_object();
  9982. }
  9983. /*!
  9984. @brief return whether value is null
  9985. This function returns true if and only if the JSON value is null.
  9986. @return `true` if type is null, `false` otherwise.
  9987. @complexity Constant.
  9988. @exceptionsafety No-throw guarantee: this member function never throws
  9989. exceptions.
  9990. @liveexample{The following code exemplifies `is_null()` for all JSON
  9991. types.,is_null}
  9992. @since version 1.0.0
  9993. */
  9994. constexpr bool is_null() const noexcept
  9995. {
  9996. return (m_type == value_t::null);
  9997. }
  9998. /*!
  9999. @brief return whether value is a boolean
  10000. This function returns true if and only if the JSON value is a boolean.
  10001. @return `true` if type is boolean, `false` otherwise.
  10002. @complexity Constant.
  10003. @exceptionsafety No-throw guarantee: this member function never throws
  10004. exceptions.
  10005. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  10006. types.,is_boolean}
  10007. @since version 1.0.0
  10008. */
  10009. constexpr bool is_boolean() const noexcept
  10010. {
  10011. return (m_type == value_t::boolean);
  10012. }
  10013. /*!
  10014. @brief return whether value is a number
  10015. This function returns true if and only if the JSON value is a number. This
  10016. includes both integer (signed and unsigned) and floating-point values.
  10017. @return `true` if type is number (regardless whether integer, unsigned
  10018. integer or floating-type), `false` otherwise.
  10019. @complexity Constant.
  10020. @exceptionsafety No-throw guarantee: this member function never throws
  10021. exceptions.
  10022. @liveexample{The following code exemplifies `is_number()` for all JSON
  10023. types.,is_number}
  10024. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  10025. integer number
  10026. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  10027. number
  10028. @sa @ref is_number_float() -- check if value is a floating-point number
  10029. @since version 1.0.0
  10030. */
  10031. constexpr bool is_number() const noexcept
  10032. {
  10033. return is_number_integer() or is_number_float();
  10034. }
  10035. /*!
  10036. @brief return whether value is an integer number
  10037. This function returns true if and only if the JSON value is a signed or
  10038. unsigned integer number. This excludes floating-point values.
  10039. @return `true` if type is an integer or unsigned integer number, `false`
  10040. otherwise.
  10041. @complexity Constant.
  10042. @exceptionsafety No-throw guarantee: this member function never throws
  10043. exceptions.
  10044. @liveexample{The following code exemplifies `is_number_integer()` for all
  10045. JSON types.,is_number_integer}
  10046. @sa @ref is_number() -- check if value is a number
  10047. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  10048. number
  10049. @sa @ref is_number_float() -- check if value is a floating-point number
  10050. @since version 1.0.0
  10051. */
  10052. constexpr bool is_number_integer() const noexcept
  10053. {
  10054. return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
  10055. }
  10056. /*!
  10057. @brief return whether value is an unsigned integer number
  10058. This function returns true if and only if the JSON value is an unsigned
  10059. integer number. This excludes floating-point and signed integer values.
  10060. @return `true` if type is an unsigned integer number, `false` otherwise.
  10061. @complexity Constant.
  10062. @exceptionsafety No-throw guarantee: this member function never throws
  10063. exceptions.
  10064. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  10065. JSON types.,is_number_unsigned}
  10066. @sa @ref is_number() -- check if value is a number
  10067. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  10068. integer number
  10069. @sa @ref is_number_float() -- check if value is a floating-point number
  10070. @since version 2.0.0
  10071. */
  10072. constexpr bool is_number_unsigned() const noexcept
  10073. {
  10074. return (m_type == value_t::number_unsigned);
  10075. }
  10076. /*!
  10077. @brief return whether value is a floating-point number
  10078. This function returns true if and only if the JSON value is a
  10079. floating-point number. This excludes signed and unsigned integer values.
  10080. @return `true` if type is a floating-point number, `false` otherwise.
  10081. @complexity Constant.
  10082. @exceptionsafety No-throw guarantee: this member function never throws
  10083. exceptions.
  10084. @liveexample{The following code exemplifies `is_number_float()` for all
  10085. JSON types.,is_number_float}
  10086. @sa @ref is_number() -- check if value is number
  10087. @sa @ref is_number_integer() -- check if value is an integer number
  10088. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  10089. number
  10090. @since version 1.0.0
  10091. */
  10092. constexpr bool is_number_float() const noexcept
  10093. {
  10094. return (m_type == value_t::number_float);
  10095. }
  10096. /*!
  10097. @brief return whether value is an object
  10098. This function returns true if and only if the JSON value is an object.
  10099. @return `true` if type is object, `false` otherwise.
  10100. @complexity Constant.
  10101. @exceptionsafety No-throw guarantee: this member function never throws
  10102. exceptions.
  10103. @liveexample{The following code exemplifies `is_object()` for all JSON
  10104. types.,is_object}
  10105. @since version 1.0.0
  10106. */
  10107. constexpr bool is_object() const noexcept
  10108. {
  10109. return (m_type == value_t::object);
  10110. }
  10111. /*!
  10112. @brief return whether value is an array
  10113. This function returns true if and only if the JSON value is an array.
  10114. @return `true` if type is array, `false` otherwise.
  10115. @complexity Constant.
  10116. @exceptionsafety No-throw guarantee: this member function never throws
  10117. exceptions.
  10118. @liveexample{The following code exemplifies `is_array()` for all JSON
  10119. types.,is_array}
  10120. @since version 1.0.0
  10121. */
  10122. constexpr bool is_array() const noexcept
  10123. {
  10124. return (m_type == value_t::array);
  10125. }
  10126. /*!
  10127. @brief return whether value is a string
  10128. This function returns true if and only if the JSON value is a string.
  10129. @return `true` if type is string, `false` otherwise.
  10130. @complexity Constant.
  10131. @exceptionsafety No-throw guarantee: this member function never throws
  10132. exceptions.
  10133. @liveexample{The following code exemplifies `is_string()` for all JSON
  10134. types.,is_string}
  10135. @since version 1.0.0
  10136. */
  10137. constexpr bool is_string() const noexcept
  10138. {
  10139. return (m_type == value_t::string);
  10140. }
  10141. /*!
  10142. @brief return whether value is discarded
  10143. This function returns true if and only if the JSON value was discarded
  10144. during parsing with a callback function (see @ref parser_callback_t).
  10145. @note This function will always be `false` for JSON values after parsing.
  10146. That is, discarded values can only occur during parsing, but will be
  10147. removed when inside a structured value or replaced by null in other cases.
  10148. @return `true` if type is discarded, `false` otherwise.
  10149. @complexity Constant.
  10150. @exceptionsafety No-throw guarantee: this member function never throws
  10151. exceptions.
  10152. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  10153. types.,is_discarded}
  10154. @since version 1.0.0
  10155. */
  10156. constexpr bool is_discarded() const noexcept
  10157. {
  10158. return (m_type == value_t::discarded);
  10159. }
  10160. /*!
  10161. @brief return the type of the JSON value (implicit)
  10162. Implicitly return the type of the JSON value as a value from the @ref
  10163. value_t enumeration.
  10164. @return the type of the JSON value
  10165. @complexity Constant.
  10166. @exceptionsafety No-throw guarantee: this member function never throws
  10167. exceptions.
  10168. @liveexample{The following code exemplifies the @ref value_t operator for
  10169. all JSON types.,operator__value_t}
  10170. @sa @ref type() -- return the type of the JSON value (explicit)
  10171. @sa @ref type_name() -- return the type as string
  10172. @since version 1.0.0
  10173. */
  10174. constexpr operator value_t() const noexcept
  10175. {
  10176. return m_type;
  10177. }
  10178. /// @}
  10179. private:
  10180. //////////////////
  10181. // value access //
  10182. //////////////////
  10183. /// get a boolean (explicit)
  10184. boolean_t get_impl(boolean_t* /*unused*/) const
  10185. {
  10186. if (JSON_LIKELY(is_boolean()))
  10187. {
  10188. return m_value.boolean;
  10189. }
  10190. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  10191. }
  10192. /// get a pointer to the value (object)
  10193. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  10194. {
  10195. return is_object() ? m_value.object : nullptr;
  10196. }
  10197. /// get a pointer to the value (object)
  10198. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  10199. {
  10200. return is_object() ? m_value.object : nullptr;
  10201. }
  10202. /// get a pointer to the value (array)
  10203. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  10204. {
  10205. return is_array() ? m_value.array : nullptr;
  10206. }
  10207. /// get a pointer to the value (array)
  10208. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  10209. {
  10210. return is_array() ? m_value.array : nullptr;
  10211. }
  10212. /// get a pointer to the value (string)
  10213. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  10214. {
  10215. return is_string() ? m_value.string : nullptr;
  10216. }
  10217. /// get a pointer to the value (string)
  10218. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  10219. {
  10220. return is_string() ? m_value.string : nullptr;
  10221. }
  10222. /// get a pointer to the value (boolean)
  10223. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  10224. {
  10225. return is_boolean() ? &m_value.boolean : nullptr;
  10226. }
  10227. /// get a pointer to the value (boolean)
  10228. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  10229. {
  10230. return is_boolean() ? &m_value.boolean : nullptr;
  10231. }
  10232. /// get a pointer to the value (integer number)
  10233. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  10234. {
  10235. return is_number_integer() ? &m_value.number_integer : nullptr;
  10236. }
  10237. /// get a pointer to the value (integer number)
  10238. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  10239. {
  10240. return is_number_integer() ? &m_value.number_integer : nullptr;
  10241. }
  10242. /// get a pointer to the value (unsigned number)
  10243. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  10244. {
  10245. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  10246. }
  10247. /// get a pointer to the value (unsigned number)
  10248. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  10249. {
  10250. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  10251. }
  10252. /// get a pointer to the value (floating-point number)
  10253. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  10254. {
  10255. return is_number_float() ? &m_value.number_float : nullptr;
  10256. }
  10257. /// get a pointer to the value (floating-point number)
  10258. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  10259. {
  10260. return is_number_float() ? &m_value.number_float : nullptr;
  10261. }
  10262. /*!
  10263. @brief helper function to implement get_ref()
  10264. This function helps to implement get_ref() without code duplication for
  10265. const and non-const overloads
  10266. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  10267. @throw type_error.303 if ReferenceType does not match underlying value
  10268. type of the current JSON
  10269. */
  10270. template<typename ReferenceType, typename ThisType>
  10271. static ReferenceType get_ref_impl(ThisType& obj)
  10272. {
  10273. // delegate the call to get_ptr<>()
  10274. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  10275. if (JSON_LIKELY(ptr != nullptr))
  10276. {
  10277. return *ptr;
  10278. }
  10279. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  10280. }
  10281. public:
  10282. /// @name value access
  10283. /// Direct access to the stored value of a JSON value.
  10284. /// @{
  10285. /*!
  10286. @brief get special-case overload
  10287. This overloads avoids a lot of template boilerplate, it can be seen as the
  10288. identity method
  10289. @tparam BasicJsonType == @ref basic_json
  10290. @return a copy of *this
  10291. @complexity Constant.
  10292. @since version 2.1.0
  10293. */
  10294. template<typename BasicJsonType, detail::enable_if_t<
  10295. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  10296. int> = 0>
  10297. basic_json get() const
  10298. {
  10299. return *this;
  10300. }
  10301. /*!
  10302. @brief get special-case overload
  10303. This overloads converts the current @ref basic_json in a different
  10304. @ref basic_json type
  10305. @tparam BasicJsonType == @ref basic_json
  10306. @return a copy of *this, converted into @tparam BasicJsonType
  10307. @complexity Depending on the implementation of the called `from_json()`
  10308. method.
  10309. @since version 3.1.2
  10310. */
  10311. template<typename BasicJsonType, detail::enable_if_t<
  10312. not std::is_same<BasicJsonType, basic_json>::value and
  10313. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  10314. BasicJsonType get() const
  10315. {
  10316. return *this;
  10317. }
  10318. /*!
  10319. @brief get a value (explicit)
  10320. Explicit type conversion between the JSON value and a compatible value
  10321. which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  10322. and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  10323. The value is converted by calling the @ref json_serializer<ValueType>
  10324. `from_json()` method.
  10325. The function is equivalent to executing
  10326. @code {.cpp}
  10327. ValueType ret;
  10328. JSONSerializer<ValueType>::from_json(*this, ret);
  10329. return ret;
  10330. @endcode
  10331. This overloads is chosen if:
  10332. - @a ValueType is not @ref basic_json,
  10333. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  10334. `void from_json(const basic_json&, ValueType&)`, and
  10335. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  10336. the form `ValueType from_json(const basic_json&)`
  10337. @tparam ValueTypeCV the provided value type
  10338. @tparam ValueType the returned value type
  10339. @return copy of the JSON value, converted to @a ValueType
  10340. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  10341. @liveexample{The example below shows several conversions from JSON values
  10342. to other types. There a few things to note: (1) Floating-point numbers can
  10343. be converted to integers\, (2) A JSON array can be converted to a standard
  10344. `std::vector<short>`\, (3) A JSON object can be converted to C++
  10345. associative containers such as `std::unordered_map<std::string\,
  10346. json>`.,get__ValueType_const}
  10347. @since version 2.1.0
  10348. */
  10349. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  10350. detail::enable_if_t <
  10351. not detail::is_basic_json<ValueType>::value and
  10352. detail::has_from_json<basic_json_t, ValueType>::value and
  10353. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  10354. int> = 0>
  10355. ValueType get() const noexcept(noexcept(
  10356. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  10357. {
  10358. // we cannot static_assert on ValueTypeCV being non-const, because
  10359. // there is support for get<const basic_json_t>(), which is why we
  10360. // still need the uncvref
  10361. static_assert(not std::is_reference<ValueTypeCV>::value,
  10362. "get() cannot be used with reference types, you might want to use get_ref()");
  10363. static_assert(std::is_default_constructible<ValueType>::value,
  10364. "types must be DefaultConstructible when used with get()");
  10365. ValueType ret;
  10366. JSONSerializer<ValueType>::from_json(*this, ret);
  10367. return ret;
  10368. }
  10369. /*!
  10370. @brief get a value (explicit); special case
  10371. Explicit type conversion between the JSON value and a compatible value
  10372. which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  10373. and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  10374. The value is converted by calling the @ref json_serializer<ValueType>
  10375. `from_json()` method.
  10376. The function is equivalent to executing
  10377. @code {.cpp}
  10378. return JSONSerializer<ValueTypeCV>::from_json(*this);
  10379. @endcode
  10380. This overloads is chosen if:
  10381. - @a ValueType is not @ref basic_json and
  10382. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  10383. `ValueType from_json(const basic_json&)`
  10384. @note If @ref json_serializer<ValueType> has both overloads of
  10385. `from_json()`, this one is chosen.
  10386. @tparam ValueTypeCV the provided value type
  10387. @tparam ValueType the returned value type
  10388. @return copy of the JSON value, converted to @a ValueType
  10389. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  10390. @since version 2.1.0
  10391. */
  10392. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  10393. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  10394. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  10395. int> = 0>
  10396. ValueType get() const noexcept(noexcept(
  10397. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  10398. {
  10399. static_assert(not std::is_reference<ValueTypeCV>::value,
  10400. "get() cannot be used with reference types, you might want to use get_ref()");
  10401. return JSONSerializer<ValueTypeCV>::from_json(*this);
  10402. }
  10403. /*!
  10404. @brief get a pointer value (explicit)
  10405. Explicit pointer access to the internally stored JSON value. No copies are
  10406. made.
  10407. @warning The pointer becomes invalid if the underlying JSON object
  10408. changes.
  10409. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  10410. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  10411. @ref number_unsigned_t, or @ref number_float_t.
  10412. @return pointer to the internally stored JSON value if the requested
  10413. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  10414. @complexity Constant.
  10415. @liveexample{The example below shows how pointers to internal values of a
  10416. JSON value can be requested. Note that no type conversions are made and a
  10417. `nullptr` is returned if the value and the requested pointer type does not
  10418. match.,get__PointerType}
  10419. @sa @ref get_ptr() for explicit pointer-member access
  10420. @since version 1.0.0
  10421. */
  10422. template<typename PointerType, typename std::enable_if<
  10423. std::is_pointer<PointerType>::value, int>::type = 0>
  10424. PointerType get() noexcept
  10425. {
  10426. // delegate the call to get_ptr
  10427. return get_ptr<PointerType>();
  10428. }
  10429. /*!
  10430. @brief get a pointer value (explicit)
  10431. @copydoc get()
  10432. */
  10433. template<typename PointerType, typename std::enable_if<
  10434. std::is_pointer<PointerType>::value, int>::type = 0>
  10435. constexpr const PointerType get() const noexcept
  10436. {
  10437. // delegate the call to get_ptr
  10438. return get_ptr<PointerType>();
  10439. }
  10440. /*!
  10441. @brief get a pointer value (implicit)
  10442. Implicit pointer access to the internally stored JSON value. No copies are
  10443. made.
  10444. @warning Writing data to the pointee of the result yields an undefined
  10445. state.
  10446. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  10447. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  10448. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  10449. assertion.
  10450. @return pointer to the internally stored JSON value if the requested
  10451. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  10452. @complexity Constant.
  10453. @liveexample{The example below shows how pointers to internal values of a
  10454. JSON value can be requested. Note that no type conversions are made and a
  10455. `nullptr` is returned if the value and the requested pointer type does not
  10456. match.,get_ptr}
  10457. @since version 1.0.0
  10458. */
  10459. template<typename PointerType, typename std::enable_if<
  10460. std::is_pointer<PointerType>::value, int>::type = 0>
  10461. PointerType get_ptr() noexcept
  10462. {
  10463. // get the type of the PointerType (remove pointer and const)
  10464. using pointee_t = typename std::remove_const<typename
  10465. std::remove_pointer<typename
  10466. std::remove_const<PointerType>::type>::type>::type;
  10467. // make sure the type matches the allowed types
  10468. static_assert(
  10469. std::is_same<object_t, pointee_t>::value
  10470. or std::is_same<array_t, pointee_t>::value
  10471. or std::is_same<string_t, pointee_t>::value
  10472. or std::is_same<boolean_t, pointee_t>::value
  10473. or std::is_same<number_integer_t, pointee_t>::value
  10474. or std::is_same<number_unsigned_t, pointee_t>::value
  10475. or std::is_same<number_float_t, pointee_t>::value
  10476. , "incompatible pointer type");
  10477. // delegate the call to get_impl_ptr<>()
  10478. return get_impl_ptr(static_cast<PointerType>(nullptr));
  10479. }
  10480. /*!
  10481. @brief get a pointer value (implicit)
  10482. @copydoc get_ptr()
  10483. */
  10484. template<typename PointerType, typename std::enable_if<
  10485. std::is_pointer<PointerType>::value and
  10486. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  10487. constexpr const PointerType get_ptr() const noexcept
  10488. {
  10489. // get the type of the PointerType (remove pointer and const)
  10490. using pointee_t = typename std::remove_const<typename
  10491. std::remove_pointer<typename
  10492. std::remove_const<PointerType>::type>::type>::type;
  10493. // make sure the type matches the allowed types
  10494. static_assert(
  10495. std::is_same<object_t, pointee_t>::value
  10496. or std::is_same<array_t, pointee_t>::value
  10497. or std::is_same<string_t, pointee_t>::value
  10498. or std::is_same<boolean_t, pointee_t>::value
  10499. or std::is_same<number_integer_t, pointee_t>::value
  10500. or std::is_same<number_unsigned_t, pointee_t>::value
  10501. or std::is_same<number_float_t, pointee_t>::value
  10502. , "incompatible pointer type");
  10503. // delegate the call to get_impl_ptr<>() const
  10504. return get_impl_ptr(static_cast<PointerType>(nullptr));
  10505. }
  10506. /*!
  10507. @brief get a reference value (implicit)
  10508. Implicit reference access to the internally stored JSON value. No copies
  10509. are made.
  10510. @warning Writing data to the referee of the result yields an undefined
  10511. state.
  10512. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  10513. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  10514. @ref number_float_t. Enforced by static assertion.
  10515. @return reference to the internally stored JSON value if the requested
  10516. reference type @a ReferenceType fits to the JSON value; throws
  10517. type_error.303 otherwise
  10518. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  10519. with the stored JSON value; see example below
  10520. @complexity Constant.
  10521. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  10522. @since version 1.1.0
  10523. */
  10524. template<typename ReferenceType, typename std::enable_if<
  10525. std::is_reference<ReferenceType>::value, int>::type = 0>
  10526. ReferenceType get_ref()
  10527. {
  10528. // delegate call to get_ref_impl
  10529. return get_ref_impl<ReferenceType>(*this);
  10530. }
  10531. /*!
  10532. @brief get a reference value (implicit)
  10533. @copydoc get_ref()
  10534. */
  10535. template<typename ReferenceType, typename std::enable_if<
  10536. std::is_reference<ReferenceType>::value and
  10537. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  10538. ReferenceType get_ref() const
  10539. {
  10540. // delegate call to get_ref_impl
  10541. return get_ref_impl<ReferenceType>(*this);
  10542. }
  10543. /*!
  10544. @brief get a value (implicit)
  10545. Implicit type conversion between the JSON value and a compatible value.
  10546. The call is realized by calling @ref get() const.
  10547. @tparam ValueType non-pointer type compatible to the JSON value, for
  10548. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  10549. `std::vector` types for JSON arrays. The character type of @ref string_t
  10550. as well as an initializer list of this type is excluded to avoid
  10551. ambiguities as these types implicitly convert to `std::string`.
  10552. @return copy of the JSON value, converted to type @a ValueType
  10553. @throw type_error.302 in case passed type @a ValueType is incompatible
  10554. to the JSON value type (e.g., the JSON value is of type boolean, but a
  10555. string is requested); see example below
  10556. @complexity Linear in the size of the JSON value.
  10557. @liveexample{The example below shows several conversions from JSON values
  10558. to other types. There a few things to note: (1) Floating-point numbers can
  10559. be converted to integers\, (2) A JSON array can be converted to a standard
  10560. `std::vector<short>`\, (3) A JSON object can be converted to C++
  10561. associative containers such as `std::unordered_map<std::string\,
  10562. json>`.,operator__ValueType}
  10563. @since version 1.0.0
  10564. */
  10565. template < typename ValueType, typename std::enable_if <
  10566. not std::is_pointer<ValueType>::value and
  10567. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  10568. not std::is_same<ValueType, typename string_t::value_type>::value and
  10569. not detail::is_basic_json<ValueType>::value
  10570. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  10571. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  10572. #endif
  10573. #if defined(JSON_HAS_CPP_17)
  10574. and not std::is_same<ValueType, typename std::string_view>::value
  10575. #endif
  10576. , int >::type = 0 >
  10577. operator ValueType() const
  10578. {
  10579. // delegate the call to get<>() const
  10580. return get<ValueType>();
  10581. }
  10582. /// @}
  10583. ////////////////////
  10584. // element access //
  10585. ////////////////////
  10586. /// @name element access
  10587. /// Access to the JSON value.
  10588. /// @{
  10589. /*!
  10590. @brief access specified array element with bounds checking
  10591. Returns a reference to the element at specified location @a idx, with
  10592. bounds checking.
  10593. @param[in] idx index of the element to access
  10594. @return reference to the element at index @a idx
  10595. @throw type_error.304 if the JSON value is not an array; in this case,
  10596. calling `at` with an index makes no sense. See example below.
  10597. @throw out_of_range.401 if the index @a idx is out of range of the array;
  10598. that is, `idx >= size()`. See example below.
  10599. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10600. changes in the JSON value.
  10601. @complexity Constant.
  10602. @since version 1.0.0
  10603. @liveexample{The example below shows how array elements can be read and
  10604. written using `at()`. It also demonstrates the different exceptions that
  10605. can be thrown.,at__size_type}
  10606. */
  10607. reference at(size_type idx)
  10608. {
  10609. // at only works for arrays
  10610. if (JSON_LIKELY(is_array()))
  10611. {
  10612. JSON_TRY
  10613. {
  10614. return m_value.array->at(idx);
  10615. }
  10616. JSON_CATCH (std::out_of_range&)
  10617. {
  10618. // create better exception explanation
  10619. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  10620. }
  10621. }
  10622. else
  10623. {
  10624. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  10625. }
  10626. }
  10627. /*!
  10628. @brief access specified array element with bounds checking
  10629. Returns a const reference to the element at specified location @a idx,
  10630. with bounds checking.
  10631. @param[in] idx index of the element to access
  10632. @return const reference to the element at index @a idx
  10633. @throw type_error.304 if the JSON value is not an array; in this case,
  10634. calling `at` with an index makes no sense. See example below.
  10635. @throw out_of_range.401 if the index @a idx is out of range of the array;
  10636. that is, `idx >= size()`. See example below.
  10637. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10638. changes in the JSON value.
  10639. @complexity Constant.
  10640. @since version 1.0.0
  10641. @liveexample{The example below shows how array elements can be read using
  10642. `at()`. It also demonstrates the different exceptions that can be thrown.,
  10643. at__size_type_const}
  10644. */
  10645. const_reference at(size_type idx) const
  10646. {
  10647. // at only works for arrays
  10648. if (JSON_LIKELY(is_array()))
  10649. {
  10650. JSON_TRY
  10651. {
  10652. return m_value.array->at(idx);
  10653. }
  10654. JSON_CATCH (std::out_of_range&)
  10655. {
  10656. // create better exception explanation
  10657. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  10658. }
  10659. }
  10660. else
  10661. {
  10662. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  10663. }
  10664. }
  10665. /*!
  10666. @brief access specified object element with bounds checking
  10667. Returns a reference to the element at with specified key @a key, with
  10668. bounds checking.
  10669. @param[in] key key of the element to access
  10670. @return reference to the element at key @a key
  10671. @throw type_error.304 if the JSON value is not an object; in this case,
  10672. calling `at` with a key makes no sense. See example below.
  10673. @throw out_of_range.403 if the key @a key is is not stored in the object;
  10674. that is, `find(key) == end()`. See example below.
  10675. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10676. changes in the JSON value.
  10677. @complexity Logarithmic in the size of the container.
  10678. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  10679. access by reference
  10680. @sa @ref value() for access by value with a default value
  10681. @since version 1.0.0
  10682. @liveexample{The example below shows how object elements can be read and
  10683. written using `at()`. It also demonstrates the different exceptions that
  10684. can be thrown.,at__object_t_key_type}
  10685. */
  10686. reference at(const typename object_t::key_type& key)
  10687. {
  10688. // at only works for objects
  10689. if (JSON_LIKELY(is_object()))
  10690. {
  10691. JSON_TRY
  10692. {
  10693. return m_value.object->at(key);
  10694. }
  10695. JSON_CATCH (std::out_of_range&)
  10696. {
  10697. // create better exception explanation
  10698. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  10699. }
  10700. }
  10701. else
  10702. {
  10703. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  10704. }
  10705. }
  10706. /*!
  10707. @brief access specified object element with bounds checking
  10708. Returns a const reference to the element at with specified key @a key,
  10709. with bounds checking.
  10710. @param[in] key key of the element to access
  10711. @return const reference to the element at key @a key
  10712. @throw type_error.304 if the JSON value is not an object; in this case,
  10713. calling `at` with a key makes no sense. See example below.
  10714. @throw out_of_range.403 if the key @a key is is not stored in the object;
  10715. that is, `find(key) == end()`. See example below.
  10716. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10717. changes in the JSON value.
  10718. @complexity Logarithmic in the size of the container.
  10719. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  10720. access by reference
  10721. @sa @ref value() for access by value with a default value
  10722. @since version 1.0.0
  10723. @liveexample{The example below shows how object elements can be read using
  10724. `at()`. It also demonstrates the different exceptions that can be thrown.,
  10725. at__object_t_key_type_const}
  10726. */
  10727. const_reference at(const typename object_t::key_type& key) const
  10728. {
  10729. // at only works for objects
  10730. if (JSON_LIKELY(is_object()))
  10731. {
  10732. JSON_TRY
  10733. {
  10734. return m_value.object->at(key);
  10735. }
  10736. JSON_CATCH (std::out_of_range&)
  10737. {
  10738. // create better exception explanation
  10739. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  10740. }
  10741. }
  10742. else
  10743. {
  10744. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  10745. }
  10746. }
  10747. /*!
  10748. @brief access specified array element
  10749. Returns a reference to the element at specified location @a idx.
  10750. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  10751. then the array is silently filled up with `null` values to make `idx` a
  10752. valid reference to the last stored element.
  10753. @param[in] idx index of the element to access
  10754. @return reference to the element at index @a idx
  10755. @throw type_error.305 if the JSON value is not an array or null; in that
  10756. cases, using the [] operator with an index makes no sense.
  10757. @complexity Constant if @a idx is in the range of the array. Otherwise
  10758. linear in `idx - size()`.
  10759. @liveexample{The example below shows how array elements can be read and
  10760. written using `[]` operator. Note the addition of `null`
  10761. values.,operatorarray__size_type}
  10762. @since version 1.0.0
  10763. */
  10764. reference operator[](size_type idx)
  10765. {
  10766. // implicitly convert null value to an empty array
  10767. if (is_null())
  10768. {
  10769. m_type = value_t::array;
  10770. m_value.array = create<array_t>();
  10771. assert_invariant();
  10772. }
  10773. // operator[] only works for arrays
  10774. if (JSON_LIKELY(is_array()))
  10775. {
  10776. // fill up array with null values if given idx is outside range
  10777. if (idx >= m_value.array->size())
  10778. {
  10779. m_value.array->insert(m_value.array->end(),
  10780. idx - m_value.array->size() + 1,
  10781. basic_json());
  10782. }
  10783. return m_value.array->operator[](idx);
  10784. }
  10785. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  10786. }
  10787. /*!
  10788. @brief access specified array element
  10789. Returns a const reference to the element at specified location @a idx.
  10790. @param[in] idx index of the element to access
  10791. @return const reference to the element at index @a idx
  10792. @throw type_error.305 if the JSON value is not an array; in that case,
  10793. using the [] operator with an index makes no sense.
  10794. @complexity Constant.
  10795. @liveexample{The example below shows how array elements can be read using
  10796. the `[]` operator.,operatorarray__size_type_const}
  10797. @since version 1.0.0
  10798. */
  10799. const_reference operator[](size_type idx) const
  10800. {
  10801. // const operator[] only works for arrays
  10802. if (JSON_LIKELY(is_array()))
  10803. {
  10804. return m_value.array->operator[](idx);
  10805. }
  10806. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  10807. }
  10808. /*!
  10809. @brief access specified object element
  10810. Returns a reference to the element at with specified key @a key.
  10811. @note If @a key is not found in the object, then it is silently added to
  10812. the object and filled with a `null` value to make `key` a valid reference.
  10813. In case the value was `null` before, it is converted to an object.
  10814. @param[in] key key of the element to access
  10815. @return reference to the element at key @a key
  10816. @throw type_error.305 if the JSON value is not an object or null; in that
  10817. cases, using the [] operator with a key makes no sense.
  10818. @complexity Logarithmic in the size of the container.
  10819. @liveexample{The example below shows how object elements can be read and
  10820. written using the `[]` operator.,operatorarray__key_type}
  10821. @sa @ref at(const typename object_t::key_type&) for access by reference
  10822. with range checking
  10823. @sa @ref value() for access by value with a default value
  10824. @since version 1.0.0
  10825. */
  10826. reference operator[](const typename object_t::key_type& key)
  10827. {
  10828. // implicitly convert null value to an empty object
  10829. if (is_null())
  10830. {
  10831. m_type = value_t::object;
  10832. m_value.object = create<object_t>();
  10833. assert_invariant();
  10834. }
  10835. // operator[] only works for objects
  10836. if (JSON_LIKELY(is_object()))
  10837. {
  10838. return m_value.object->operator[](key);
  10839. }
  10840. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  10841. }
  10842. /*!
  10843. @brief read-only access specified object element
  10844. Returns a const reference to the element at with specified key @a key. No
  10845. bounds checking is performed.
  10846. @warning If the element with key @a key does not exist, the behavior is
  10847. undefined.
  10848. @param[in] key key of the element to access
  10849. @return const reference to the element at key @a key
  10850. @pre The element with key @a key must exist. **This precondition is
  10851. enforced with an assertion.**
  10852. @throw type_error.305 if the JSON value is not an object; in that case,
  10853. using the [] operator with a key makes no sense.
  10854. @complexity Logarithmic in the size of the container.
  10855. @liveexample{The example below shows how object elements can be read using
  10856. the `[]` operator.,operatorarray__key_type_const}
  10857. @sa @ref at(const typename object_t::key_type&) for access by reference
  10858. with range checking
  10859. @sa @ref value() for access by value with a default value
  10860. @since version 1.0.0
  10861. */
  10862. const_reference operator[](const typename object_t::key_type& key) const
  10863. {
  10864. // const operator[] only works for objects
  10865. if (JSON_LIKELY(is_object()))
  10866. {
  10867. assert(m_value.object->find(key) != m_value.object->end());
  10868. return m_value.object->find(key)->second;
  10869. }
  10870. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  10871. }
  10872. /*!
  10873. @brief access specified object element
  10874. Returns a reference to the element at with specified key @a key.
  10875. @note If @a key is not found in the object, then it is silently added to
  10876. the object and filled with a `null` value to make `key` a valid reference.
  10877. In case the value was `null` before, it is converted to an object.
  10878. @param[in] key key of the element to access
  10879. @return reference to the element at key @a key
  10880. @throw type_error.305 if the JSON value is not an object or null; in that
  10881. cases, using the [] operator with a key makes no sense.
  10882. @complexity Logarithmic in the size of the container.
  10883. @liveexample{The example below shows how object elements can be read and
  10884. written using the `[]` operator.,operatorarray__key_type}
  10885. @sa @ref at(const typename object_t::key_type&) for access by reference
  10886. with range checking
  10887. @sa @ref value() for access by value with a default value
  10888. @since version 1.1.0
  10889. */
  10890. template<typename T>
  10891. reference operator[](T* key)
  10892. {
  10893. // implicitly convert null to object
  10894. if (is_null())
  10895. {
  10896. m_type = value_t::object;
  10897. m_value = value_t::object;
  10898. assert_invariant();
  10899. }
  10900. // at only works for objects
  10901. if (JSON_LIKELY(is_object()))
  10902. {
  10903. return m_value.object->operator[](key);
  10904. }
  10905. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  10906. }
  10907. /*!
  10908. @brief read-only access specified object element
  10909. Returns a const reference to the element at with specified key @a key. No
  10910. bounds checking is performed.
  10911. @warning If the element with key @a key does not exist, the behavior is
  10912. undefined.
  10913. @param[in] key key of the element to access
  10914. @return const reference to the element at key @a key
  10915. @pre The element with key @a key must exist. **This precondition is
  10916. enforced with an assertion.**
  10917. @throw type_error.305 if the JSON value is not an object; in that case,
  10918. using the [] operator with a key makes no sense.
  10919. @complexity Logarithmic in the size of the container.
  10920. @liveexample{The example below shows how object elements can be read using
  10921. the `[]` operator.,operatorarray__key_type_const}
  10922. @sa @ref at(const typename object_t::key_type&) for access by reference
  10923. with range checking
  10924. @sa @ref value() for access by value with a default value
  10925. @since version 1.1.0
  10926. */
  10927. template<typename T>
  10928. const_reference operator[](T* key) const
  10929. {
  10930. // at only works for objects
  10931. if (JSON_LIKELY(is_object()))
  10932. {
  10933. assert(m_value.object->find(key) != m_value.object->end());
  10934. return m_value.object->find(key)->second;
  10935. }
  10936. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  10937. }
  10938. /*!
  10939. @brief access specified object element with default value
  10940. Returns either a copy of an object's element at the specified key @a key
  10941. or a given default value if no element with key @a key exists.
  10942. The function is basically equivalent to executing
  10943. @code {.cpp}
  10944. try {
  10945. return at(key);
  10946. } catch(out_of_range) {
  10947. return default_value;
  10948. }
  10949. @endcode
  10950. @note Unlike @ref at(const typename object_t::key_type&), this function
  10951. does not throw if the given key @a key was not found.
  10952. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  10953. function does not implicitly add an element to the position defined by @a
  10954. key. This function is furthermore also applicable to const objects.
  10955. @param[in] key key of the element to access
  10956. @param[in] default_value the value to return if @a key is not found
  10957. @tparam ValueType type compatible to JSON values, for instance `int` for
  10958. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  10959. JSON arrays. Note the type of the expected value at @a key and the default
  10960. value @a default_value must be compatible.
  10961. @return copy of the element at key @a key or @a default_value if @a key
  10962. is not found
  10963. @throw type_error.306 if the JSON value is not an object; in that case,
  10964. using `value()` with a key makes no sense.
  10965. @complexity Logarithmic in the size of the container.
  10966. @liveexample{The example below shows how object elements can be queried
  10967. with a default value.,basic_json__value}
  10968. @sa @ref at(const typename object_t::key_type&) for access by reference
  10969. with range checking
  10970. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  10971. access by reference
  10972. @since version 1.0.0
  10973. */
  10974. template<class ValueType, typename std::enable_if<
  10975. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  10976. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  10977. {
  10978. // at only works for objects
  10979. if (JSON_LIKELY(is_object()))
  10980. {
  10981. // if key is found, return value and given default value otherwise
  10982. const auto it = find(key);
  10983. if (it != end())
  10984. {
  10985. return *it;
  10986. }
  10987. return default_value;
  10988. }
  10989. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  10990. }
  10991. /*!
  10992. @brief overload for a default value of type const char*
  10993. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  10994. */
  10995. string_t value(const typename object_t::key_type& key, const char* default_value) const
  10996. {
  10997. return value(key, string_t(default_value));
  10998. }
  10999. /*!
  11000. @brief access specified object element via JSON Pointer with default value
  11001. Returns either a copy of an object's element at the specified key @a key
  11002. or a given default value if no element with key @a key exists.
  11003. The function is basically equivalent to executing
  11004. @code {.cpp}
  11005. try {
  11006. return at(ptr);
  11007. } catch(out_of_range) {
  11008. return default_value;
  11009. }
  11010. @endcode
  11011. @note Unlike @ref at(const json_pointer&), this function does not throw
  11012. if the given key @a key was not found.
  11013. @param[in] ptr a JSON pointer to the element to access
  11014. @param[in] default_value the value to return if @a ptr found no value
  11015. @tparam ValueType type compatible to JSON values, for instance `int` for
  11016. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  11017. JSON arrays. Note the type of the expected value at @a key and the default
  11018. value @a default_value must be compatible.
  11019. @return copy of the element at key @a key or @a default_value if @a key
  11020. is not found
  11021. @throw type_error.306 if the JSON value is not an objec; in that case,
  11022. using `value()` with a key makes no sense.
  11023. @complexity Logarithmic in the size of the container.
  11024. @liveexample{The example below shows how object elements can be queried
  11025. with a default value.,basic_json__value_ptr}
  11026. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  11027. @since version 2.0.2
  11028. */
  11029. template<class ValueType, typename std::enable_if<
  11030. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  11031. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  11032. {
  11033. // at only works for objects
  11034. if (JSON_LIKELY(is_object()))
  11035. {
  11036. // if pointer resolves a value, return it or use default value
  11037. JSON_TRY
  11038. {
  11039. return ptr.get_checked(this);
  11040. }
  11041. JSON_CATCH (out_of_range&)
  11042. {
  11043. return default_value;
  11044. }
  11045. }
  11046. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  11047. }
  11048. /*!
  11049. @brief overload for a default value of type const char*
  11050. @copydoc basic_json::value(const json_pointer&, ValueType) const
  11051. */
  11052. string_t value(const json_pointer& ptr, const char* default_value) const
  11053. {
  11054. return value(ptr, string_t(default_value));
  11055. }
  11056. /*!
  11057. @brief access the first element
  11058. Returns a reference to the first element in the container. For a JSON
  11059. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  11060. @return In case of a structured type (array or object), a reference to the
  11061. first element is returned. In case of number, string, or boolean values, a
  11062. reference to the value is returned.
  11063. @complexity Constant.
  11064. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  11065. or an empty array or object (undefined behavior, **guarded by
  11066. assertions**).
  11067. @post The JSON value remains unchanged.
  11068. @throw invalid_iterator.214 when called on `null` value
  11069. @liveexample{The following code shows an example for `front()`.,front}
  11070. @sa @ref back() -- access the last element
  11071. @since version 1.0.0
  11072. */
  11073. reference front()
  11074. {
  11075. return *begin();
  11076. }
  11077. /*!
  11078. @copydoc basic_json::front()
  11079. */
  11080. const_reference front() const
  11081. {
  11082. return *cbegin();
  11083. }
  11084. /*!
  11085. @brief access the last element
  11086. Returns a reference to the last element in the container. For a JSON
  11087. container `c`, the expression `c.back()` is equivalent to
  11088. @code {.cpp}
  11089. auto tmp = c.end();
  11090. --tmp;
  11091. return *tmp;
  11092. @endcode
  11093. @return In case of a structured type (array or object), a reference to the
  11094. last element is returned. In case of number, string, or boolean values, a
  11095. reference to the value is returned.
  11096. @complexity Constant.
  11097. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  11098. or an empty array or object (undefined behavior, **guarded by
  11099. assertions**).
  11100. @post The JSON value remains unchanged.
  11101. @throw invalid_iterator.214 when called on a `null` value. See example
  11102. below.
  11103. @liveexample{The following code shows an example for `back()`.,back}
  11104. @sa @ref front() -- access the first element
  11105. @since version 1.0.0
  11106. */
  11107. reference back()
  11108. {
  11109. auto tmp = end();
  11110. --tmp;
  11111. return *tmp;
  11112. }
  11113. /*!
  11114. @copydoc basic_json::back()
  11115. */
  11116. const_reference back() const
  11117. {
  11118. auto tmp = cend();
  11119. --tmp;
  11120. return *tmp;
  11121. }
  11122. /*!
  11123. @brief remove element given an iterator
  11124. Removes the element specified by iterator @a pos. The iterator @a pos must
  11125. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  11126. but is not dereferenceable) cannot be used as a value for @a pos.
  11127. If called on a primitive type other than `null`, the resulting JSON value
  11128. will be `null`.
  11129. @param[in] pos iterator to the element to remove
  11130. @return Iterator following the last removed element. If the iterator @a
  11131. pos refers to the last element, the `end()` iterator is returned.
  11132. @tparam IteratorType an @ref iterator or @ref const_iterator
  11133. @post Invalidates iterators and references at or after the point of the
  11134. erase, including the `end()` iterator.
  11135. @throw type_error.307 if called on a `null` value; example: `"cannot use
  11136. erase() with null"`
  11137. @throw invalid_iterator.202 if called on an iterator which does not belong
  11138. to the current JSON value; example: `"iterator does not fit current
  11139. value"`
  11140. @throw invalid_iterator.205 if called on a primitive type with invalid
  11141. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  11142. out of range"`
  11143. @complexity The complexity depends on the type:
  11144. - objects: amortized constant
  11145. - arrays: linear in distance between @a pos and the end of the container
  11146. - strings: linear in the length of the string
  11147. - other types: constant
  11148. @liveexample{The example shows the result of `erase()` for different JSON
  11149. types.,erase__IteratorType}
  11150. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  11151. the given range
  11152. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  11153. from an object at the given key
  11154. @sa @ref erase(const size_type) -- removes the element from an array at
  11155. the given index
  11156. @since version 1.0.0
  11157. */
  11158. template<class IteratorType, typename std::enable_if<
  11159. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  11160. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  11161. = 0>
  11162. IteratorType erase(IteratorType pos)
  11163. {
  11164. // make sure iterator fits the current value
  11165. if (JSON_UNLIKELY(this != pos.m_object))
  11166. {
  11167. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  11168. }
  11169. IteratorType result = end();
  11170. switch (m_type)
  11171. {
  11172. case value_t::boolean:
  11173. case value_t::number_float:
  11174. case value_t::number_integer:
  11175. case value_t::number_unsigned:
  11176. case value_t::string:
  11177. {
  11178. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  11179. {
  11180. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  11181. }
  11182. if (is_string())
  11183. {
  11184. AllocatorType<string_t> alloc;
  11185. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  11186. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  11187. m_value.string = nullptr;
  11188. }
  11189. m_type = value_t::null;
  11190. assert_invariant();
  11191. break;
  11192. }
  11193. case value_t::object:
  11194. {
  11195. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  11196. break;
  11197. }
  11198. case value_t::array:
  11199. {
  11200. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  11201. break;
  11202. }
  11203. default:
  11204. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  11205. }
  11206. return result;
  11207. }
  11208. /*!
  11209. @brief remove elements given an iterator range
  11210. Removes the element specified by the range `[first; last)`. The iterator
  11211. @a first does not need to be dereferenceable if `first == last`: erasing
  11212. an empty range is a no-op.
  11213. If called on a primitive type other than `null`, the resulting JSON value
  11214. will be `null`.
  11215. @param[in] first iterator to the beginning of the range to remove
  11216. @param[in] last iterator past the end of the range to remove
  11217. @return Iterator following the last removed element. If the iterator @a
  11218. second refers to the last element, the `end()` iterator is returned.
  11219. @tparam IteratorType an @ref iterator or @ref const_iterator
  11220. @post Invalidates iterators and references at or after the point of the
  11221. erase, including the `end()` iterator.
  11222. @throw type_error.307 if called on a `null` value; example: `"cannot use
  11223. erase() with null"`
  11224. @throw invalid_iterator.203 if called on iterators which does not belong
  11225. to the current JSON value; example: `"iterators do not fit current value"`
  11226. @throw invalid_iterator.204 if called on a primitive type with invalid
  11227. iterators (i.e., if `first != begin()` and `last != end()`); example:
  11228. `"iterators out of range"`
  11229. @complexity The complexity depends on the type:
  11230. - objects: `log(size()) + std::distance(first, last)`
  11231. - arrays: linear in the distance between @a first and @a last, plus linear
  11232. in the distance between @a last and end of the container
  11233. - strings: linear in the length of the string
  11234. - other types: constant
  11235. @liveexample{The example shows the result of `erase()` for different JSON
  11236. types.,erase__IteratorType_IteratorType}
  11237. @sa @ref erase(IteratorType) -- removes the element at a given position
  11238. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  11239. from an object at the given key
  11240. @sa @ref erase(const size_type) -- removes the element from an array at
  11241. the given index
  11242. @since version 1.0.0
  11243. */
  11244. template<class IteratorType, typename std::enable_if<
  11245. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  11246. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  11247. = 0>
  11248. IteratorType erase(IteratorType first, IteratorType last)
  11249. {
  11250. // make sure iterator fits the current value
  11251. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  11252. {
  11253. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  11254. }
  11255. IteratorType result = end();
  11256. switch (m_type)
  11257. {
  11258. case value_t::boolean:
  11259. case value_t::number_float:
  11260. case value_t::number_integer:
  11261. case value_t::number_unsigned:
  11262. case value_t::string:
  11263. {
  11264. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  11265. or not last.m_it.primitive_iterator.is_end()))
  11266. {
  11267. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  11268. }
  11269. if (is_string())
  11270. {
  11271. AllocatorType<string_t> alloc;
  11272. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  11273. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  11274. m_value.string = nullptr;
  11275. }
  11276. m_type = value_t::null;
  11277. assert_invariant();
  11278. break;
  11279. }
  11280. case value_t::object:
  11281. {
  11282. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  11283. last.m_it.object_iterator);
  11284. break;
  11285. }
  11286. case value_t::array:
  11287. {
  11288. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  11289. last.m_it.array_iterator);
  11290. break;
  11291. }
  11292. default:
  11293. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  11294. }
  11295. return result;
  11296. }
  11297. /*!
  11298. @brief remove element from a JSON object given a key
  11299. Removes elements from a JSON object with the key value @a key.
  11300. @param[in] key value of the elements to remove
  11301. @return Number of elements removed. If @a ObjectType is the default
  11302. `std::map` type, the return value will always be `0` (@a key was not
  11303. found) or `1` (@a key was found).
  11304. @post References and iterators to the erased elements are invalidated.
  11305. Other references and iterators are not affected.
  11306. @throw type_error.307 when called on a type other than JSON object;
  11307. example: `"cannot use erase() with null"`
  11308. @complexity `log(size()) + count(key)`
  11309. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  11310. @sa @ref erase(IteratorType) -- removes the element at a given position
  11311. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  11312. the given range
  11313. @sa @ref erase(const size_type) -- removes the element from an array at
  11314. the given index
  11315. @since version 1.0.0
  11316. */
  11317. size_type erase(const typename object_t::key_type& key)
  11318. {
  11319. // this erase only works for objects
  11320. if (JSON_LIKELY(is_object()))
  11321. {
  11322. return m_value.object->erase(key);
  11323. }
  11324. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  11325. }
  11326. /*!
  11327. @brief remove element from a JSON array given an index
  11328. Removes element from a JSON array at the index @a idx.
  11329. @param[in] idx index of the element to remove
  11330. @throw type_error.307 when called on a type other than JSON object;
  11331. example: `"cannot use erase() with null"`
  11332. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  11333. is out of range"`
  11334. @complexity Linear in distance between @a idx and the end of the container.
  11335. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  11336. @sa @ref erase(IteratorType) -- removes the element at a given position
  11337. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  11338. the given range
  11339. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  11340. from an object at the given key
  11341. @since version 1.0.0
  11342. */
  11343. void erase(const size_type idx)
  11344. {
  11345. // this erase only works for arrays
  11346. if (JSON_LIKELY(is_array()))
  11347. {
  11348. if (JSON_UNLIKELY(idx >= size()))
  11349. {
  11350. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11351. }
  11352. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  11353. }
  11354. else
  11355. {
  11356. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  11357. }
  11358. }
  11359. /// @}
  11360. ////////////
  11361. // lookup //
  11362. ////////////
  11363. /// @name lookup
  11364. /// @{
  11365. /*!
  11366. @brief find an element in a JSON object
  11367. Finds an element in a JSON object with key equivalent to @a key. If the
  11368. element is not found or the JSON value is not an object, end() is
  11369. returned.
  11370. @note This method always returns @ref end() when executed on a JSON type
  11371. that is not an object.
  11372. @param[in] key key value of the element to search for.
  11373. @return Iterator to an element with key equivalent to @a key. If no such
  11374. element is found or the JSON value is not an object, past-the-end (see
  11375. @ref end()) iterator is returned.
  11376. @complexity Logarithmic in the size of the JSON object.
  11377. @liveexample{The example shows how `find()` is used.,find__key_type}
  11378. @since version 1.0.0
  11379. */
  11380. template<typename KeyT>
  11381. iterator find(KeyT&& key)
  11382. {
  11383. auto result = end();
  11384. if (is_object())
  11385. {
  11386. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  11387. }
  11388. return result;
  11389. }
  11390. /*!
  11391. @brief find an element in a JSON object
  11392. @copydoc find(KeyT&&)
  11393. */
  11394. template<typename KeyT>
  11395. const_iterator find(KeyT&& key) const
  11396. {
  11397. auto result = cend();
  11398. if (is_object())
  11399. {
  11400. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  11401. }
  11402. return result;
  11403. }
  11404. /*!
  11405. @brief returns the number of occurrences of a key in a JSON object
  11406. Returns the number of elements with key @a key. If ObjectType is the
  11407. default `std::map` type, the return value will always be `0` (@a key was
  11408. not found) or `1` (@a key was found).
  11409. @note This method always returns `0` when executed on a JSON type that is
  11410. not an object.
  11411. @param[in] key key value of the element to count
  11412. @return Number of elements with key @a key. If the JSON value is not an
  11413. object, the return value will be `0`.
  11414. @complexity Logarithmic in the size of the JSON object.
  11415. @liveexample{The example shows how `count()` is used.,count}
  11416. @since version 1.0.0
  11417. */
  11418. template<typename KeyT>
  11419. size_type count(KeyT&& key) const
  11420. {
  11421. // return 0 for all nonobject types
  11422. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  11423. }
  11424. /// @}
  11425. ///////////////
  11426. // iterators //
  11427. ///////////////
  11428. /// @name iterators
  11429. /// @{
  11430. /*!
  11431. @brief returns an iterator to the first element
  11432. Returns an iterator to the first element.
  11433. @image html range-begin-end.svg "Illustration from cppreference.com"
  11434. @return iterator to the first element
  11435. @complexity Constant.
  11436. @requirement This function helps `basic_json` satisfying the
  11437. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11438. requirements:
  11439. - The complexity is constant.
  11440. @liveexample{The following code shows an example for `begin()`.,begin}
  11441. @sa @ref cbegin() -- returns a const iterator to the beginning
  11442. @sa @ref end() -- returns an iterator to the end
  11443. @sa @ref cend() -- returns a const iterator to the end
  11444. @since version 1.0.0
  11445. */
  11446. iterator begin() noexcept
  11447. {
  11448. iterator result(this);
  11449. result.set_begin();
  11450. return result;
  11451. }
  11452. /*!
  11453. @copydoc basic_json::cbegin()
  11454. */
  11455. const_iterator begin() const noexcept
  11456. {
  11457. return cbegin();
  11458. }
  11459. /*!
  11460. @brief returns a const iterator to the first element
  11461. Returns a const iterator to the first element.
  11462. @image html range-begin-end.svg "Illustration from cppreference.com"
  11463. @return const iterator to the first element
  11464. @complexity Constant.
  11465. @requirement This function helps `basic_json` satisfying the
  11466. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11467. requirements:
  11468. - The complexity is constant.
  11469. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  11470. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  11471. @sa @ref begin() -- returns an iterator to the beginning
  11472. @sa @ref end() -- returns an iterator to the end
  11473. @sa @ref cend() -- returns a const iterator to the end
  11474. @since version 1.0.0
  11475. */
  11476. const_iterator cbegin() const noexcept
  11477. {
  11478. const_iterator result(this);
  11479. result.set_begin();
  11480. return result;
  11481. }
  11482. /*!
  11483. @brief returns an iterator to one past the last element
  11484. Returns an iterator to one past the last element.
  11485. @image html range-begin-end.svg "Illustration from cppreference.com"
  11486. @return iterator one past the last element
  11487. @complexity Constant.
  11488. @requirement This function helps `basic_json` satisfying the
  11489. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11490. requirements:
  11491. - The complexity is constant.
  11492. @liveexample{The following code shows an example for `end()`.,end}
  11493. @sa @ref cend() -- returns a const iterator to the end
  11494. @sa @ref begin() -- returns an iterator to the beginning
  11495. @sa @ref cbegin() -- returns a const iterator to the beginning
  11496. @since version 1.0.0
  11497. */
  11498. iterator end() noexcept
  11499. {
  11500. iterator result(this);
  11501. result.set_end();
  11502. return result;
  11503. }
  11504. /*!
  11505. @copydoc basic_json::cend()
  11506. */
  11507. const_iterator end() const noexcept
  11508. {
  11509. return cend();
  11510. }
  11511. /*!
  11512. @brief returns a const iterator to one past the last element
  11513. Returns a const iterator to one past the last element.
  11514. @image html range-begin-end.svg "Illustration from cppreference.com"
  11515. @return const iterator one past the last element
  11516. @complexity Constant.
  11517. @requirement This function helps `basic_json` satisfying the
  11518. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11519. requirements:
  11520. - The complexity is constant.
  11521. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  11522. @liveexample{The following code shows an example for `cend()`.,cend}
  11523. @sa @ref end() -- returns an iterator to the end
  11524. @sa @ref begin() -- returns an iterator to the beginning
  11525. @sa @ref cbegin() -- returns a const iterator to the beginning
  11526. @since version 1.0.0
  11527. */
  11528. const_iterator cend() const noexcept
  11529. {
  11530. const_iterator result(this);
  11531. result.set_end();
  11532. return result;
  11533. }
  11534. /*!
  11535. @brief returns an iterator to the reverse-beginning
  11536. Returns an iterator to the reverse-beginning; that is, the last element.
  11537. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  11538. @complexity Constant.
  11539. @requirement This function helps `basic_json` satisfying the
  11540. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  11541. requirements:
  11542. - The complexity is constant.
  11543. - Has the semantics of `reverse_iterator(end())`.
  11544. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  11545. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  11546. @sa @ref rend() -- returns a reverse iterator to the end
  11547. @sa @ref crend() -- returns a const reverse iterator to the end
  11548. @since version 1.0.0
  11549. */
  11550. reverse_iterator rbegin() noexcept
  11551. {
  11552. return reverse_iterator(end());
  11553. }
  11554. /*!
  11555. @copydoc basic_json::crbegin()
  11556. */
  11557. const_reverse_iterator rbegin() const noexcept
  11558. {
  11559. return crbegin();
  11560. }
  11561. /*!
  11562. @brief returns an iterator to the reverse-end
  11563. Returns an iterator to the reverse-end; that is, one before the first
  11564. element.
  11565. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  11566. @complexity Constant.
  11567. @requirement This function helps `basic_json` satisfying the
  11568. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  11569. requirements:
  11570. - The complexity is constant.
  11571. - Has the semantics of `reverse_iterator(begin())`.
  11572. @liveexample{The following code shows an example for `rend()`.,rend}
  11573. @sa @ref crend() -- returns a const reverse iterator to the end
  11574. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  11575. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  11576. @since version 1.0.0
  11577. */
  11578. reverse_iterator rend() noexcept
  11579. {
  11580. return reverse_iterator(begin());
  11581. }
  11582. /*!
  11583. @copydoc basic_json::crend()
  11584. */
  11585. const_reverse_iterator rend() const noexcept
  11586. {
  11587. return crend();
  11588. }
  11589. /*!
  11590. @brief returns a const reverse iterator to the last element
  11591. Returns a const iterator to the reverse-beginning; that is, the last
  11592. element.
  11593. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  11594. @complexity Constant.
  11595. @requirement This function helps `basic_json` satisfying the
  11596. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  11597. requirements:
  11598. - The complexity is constant.
  11599. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  11600. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  11601. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  11602. @sa @ref rend() -- returns a reverse iterator to the end
  11603. @sa @ref crend() -- returns a const reverse iterator to the end
  11604. @since version 1.0.0
  11605. */
  11606. const_reverse_iterator crbegin() const noexcept
  11607. {
  11608. return const_reverse_iterator(cend());
  11609. }
  11610. /*!
  11611. @brief returns a const reverse iterator to one before the first
  11612. Returns a const reverse iterator to the reverse-end; that is, one before
  11613. the first element.
  11614. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  11615. @complexity Constant.
  11616. @requirement This function helps `basic_json` satisfying the
  11617. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  11618. requirements:
  11619. - The complexity is constant.
  11620. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  11621. @liveexample{The following code shows an example for `crend()`.,crend}
  11622. @sa @ref rend() -- returns a reverse iterator to the end
  11623. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  11624. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  11625. @since version 1.0.0
  11626. */
  11627. const_reverse_iterator crend() const noexcept
  11628. {
  11629. return const_reverse_iterator(cbegin());
  11630. }
  11631. public:
  11632. /*!
  11633. @brief wrapper to access iterator member functions in range-based for
  11634. This function allows to access @ref iterator::key() and @ref
  11635. iterator::value() during range-based for loops. In these loops, a
  11636. reference to the JSON values is returned, so there is no access to the
  11637. underlying iterator.
  11638. For loop without iterator_wrapper:
  11639. @code{cpp}
  11640. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  11641. {
  11642. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  11643. }
  11644. @endcode
  11645. Range-based for loop without iterator proxy:
  11646. @code{cpp}
  11647. for (auto it : j_object)
  11648. {
  11649. // "it" is of type json::reference and has no key() member
  11650. std::cout << "value: " << it << '\n';
  11651. }
  11652. @endcode
  11653. Range-based for loop with iterator proxy:
  11654. @code{cpp}
  11655. for (auto it : json::iterator_wrapper(j_object))
  11656. {
  11657. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  11658. }
  11659. @endcode
  11660. @note When iterating over an array, `key()` will return the index of the
  11661. element as string (see example).
  11662. @param[in] ref reference to a JSON value
  11663. @return iteration proxy object wrapping @a ref with an interface to use in
  11664. range-based for loops
  11665. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  11666. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11667. changes in the JSON value.
  11668. @complexity Constant.
  11669. @note The name of this function is not yet final and may change in the
  11670. future.
  11671. @deprecated This stream operator is deprecated and will be removed in
  11672. future 4.0.0 of the library. Please use @ref items() instead;
  11673. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  11674. */
  11675. JSON_DEPRECATED
  11676. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  11677. {
  11678. return ref.items();
  11679. }
  11680. /*!
  11681. @copydoc iterator_wrapper(reference)
  11682. */
  11683. JSON_DEPRECATED
  11684. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  11685. {
  11686. return ref.items();
  11687. }
  11688. /*!
  11689. @brief helper to access iterator member functions in range-based for
  11690. This function allows to access @ref iterator::key() and @ref
  11691. iterator::value() during range-based for loops. In these loops, a
  11692. reference to the JSON values is returned, so there is no access to the
  11693. underlying iterator.
  11694. For loop without `items()` function:
  11695. @code{cpp}
  11696. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  11697. {
  11698. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  11699. }
  11700. @endcode
  11701. Range-based for loop without `items()` function:
  11702. @code{cpp}
  11703. for (auto it : j_object)
  11704. {
  11705. // "it" is of type json::reference and has no key() member
  11706. std::cout << "value: " << it << '\n';
  11707. }
  11708. @endcode
  11709. Range-based for loop with `items()` function:
  11710. @code{cpp}
  11711. for (auto it : j_object.items())
  11712. {
  11713. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  11714. }
  11715. @endcode
  11716. @note When iterating over an array, `key()` will return the index of the
  11717. element as string (see example). For primitive types (e.g., numbers),
  11718. `key()` returns an empty string.
  11719. @return iteration proxy object wrapping @a ref with an interface to use in
  11720. range-based for loops
  11721. @liveexample{The following code shows how the function is used.,items}
  11722. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11723. changes in the JSON value.
  11724. @complexity Constant.
  11725. @since version 3.x.x.
  11726. */
  11727. iteration_proxy<iterator> items() noexcept
  11728. {
  11729. return iteration_proxy<iterator>(*this);
  11730. }
  11731. /*!
  11732. @copydoc items()
  11733. */
  11734. iteration_proxy<const_iterator> items() const noexcept
  11735. {
  11736. return iteration_proxy<const_iterator>(*this);
  11737. }
  11738. /// @}
  11739. //////////////
  11740. // capacity //
  11741. //////////////
  11742. /// @name capacity
  11743. /// @{
  11744. /*!
  11745. @brief checks whether the container is empty.
  11746. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  11747. @return The return value depends on the different types and is
  11748. defined as follows:
  11749. Value type | return value
  11750. ----------- | -------------
  11751. null | `true`
  11752. boolean | `false`
  11753. string | `false`
  11754. number | `false`
  11755. object | result of function `object_t::empty()`
  11756. array | result of function `array_t::empty()`
  11757. @liveexample{The following code uses `empty()` to check if a JSON
  11758. object contains any elements.,empty}
  11759. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  11760. the Container concept; that is, their `empty()` functions have constant
  11761. complexity.
  11762. @iterators No changes.
  11763. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11764. @note This function does not return whether a string stored as JSON value
  11765. is empty - it returns whether the JSON container itself is empty which is
  11766. false in the case of a string.
  11767. @requirement This function helps `basic_json` satisfying the
  11768. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11769. requirements:
  11770. - The complexity is constant.
  11771. - Has the semantics of `begin() == end()`.
  11772. @sa @ref size() -- returns the number of elements
  11773. @since version 1.0.0
  11774. */
  11775. bool empty() const noexcept
  11776. {
  11777. switch (m_type)
  11778. {
  11779. case value_t::null:
  11780. {
  11781. // null values are empty
  11782. return true;
  11783. }
  11784. case value_t::array:
  11785. {
  11786. // delegate call to array_t::empty()
  11787. return m_value.array->empty();
  11788. }
  11789. case value_t::object:
  11790. {
  11791. // delegate call to object_t::empty()
  11792. return m_value.object->empty();
  11793. }
  11794. default:
  11795. {
  11796. // all other types are nonempty
  11797. return false;
  11798. }
  11799. }
  11800. }
  11801. /*!
  11802. @brief returns the number of elements
  11803. Returns the number of elements in a JSON value.
  11804. @return The return value depends on the different types and is
  11805. defined as follows:
  11806. Value type | return value
  11807. ----------- | -------------
  11808. null | `0`
  11809. boolean | `1`
  11810. string | `1`
  11811. number | `1`
  11812. object | result of function object_t::size()
  11813. array | result of function array_t::size()
  11814. @liveexample{The following code calls `size()` on the different value
  11815. types.,size}
  11816. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  11817. the Container concept; that is, their size() functions have constant
  11818. complexity.
  11819. @iterators No changes.
  11820. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11821. @note This function does not return the length of a string stored as JSON
  11822. value - it returns the number of elements in the JSON value which is 1 in
  11823. the case of a string.
  11824. @requirement This function helps `basic_json` satisfying the
  11825. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11826. requirements:
  11827. - The complexity is constant.
  11828. - Has the semantics of `std::distance(begin(), end())`.
  11829. @sa @ref empty() -- checks whether the container is empty
  11830. @sa @ref max_size() -- returns the maximal number of elements
  11831. @since version 1.0.0
  11832. */
  11833. size_type size() const noexcept
  11834. {
  11835. switch (m_type)
  11836. {
  11837. case value_t::null:
  11838. {
  11839. // null values are empty
  11840. return 0;
  11841. }
  11842. case value_t::array:
  11843. {
  11844. // delegate call to array_t::size()
  11845. return m_value.array->size();
  11846. }
  11847. case value_t::object:
  11848. {
  11849. // delegate call to object_t::size()
  11850. return m_value.object->size();
  11851. }
  11852. default:
  11853. {
  11854. // all other types have size 1
  11855. return 1;
  11856. }
  11857. }
  11858. }
  11859. /*!
  11860. @brief returns the maximum possible number of elements
  11861. Returns the maximum number of elements a JSON value is able to hold due to
  11862. system or library implementation limitations, i.e. `std::distance(begin(),
  11863. end())` for the JSON value.
  11864. @return The return value depends on the different types and is
  11865. defined as follows:
  11866. Value type | return value
  11867. ----------- | -------------
  11868. null | `0` (same as `size()`)
  11869. boolean | `1` (same as `size()`)
  11870. string | `1` (same as `size()`)
  11871. number | `1` (same as `size()`)
  11872. object | result of function `object_t::max_size()`
  11873. array | result of function `array_t::max_size()`
  11874. @liveexample{The following code calls `max_size()` on the different value
  11875. types. Note the output is implementation specific.,max_size}
  11876. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  11877. the Container concept; that is, their `max_size()` functions have constant
  11878. complexity.
  11879. @iterators No changes.
  11880. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11881. @requirement This function helps `basic_json` satisfying the
  11882. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  11883. requirements:
  11884. - The complexity is constant.
  11885. - Has the semantics of returning `b.size()` where `b` is the largest
  11886. possible JSON value.
  11887. @sa @ref size() -- returns the number of elements
  11888. @since version 1.0.0
  11889. */
  11890. size_type max_size() const noexcept
  11891. {
  11892. switch (m_type)
  11893. {
  11894. case value_t::array:
  11895. {
  11896. // delegate call to array_t::max_size()
  11897. return m_value.array->max_size();
  11898. }
  11899. case value_t::object:
  11900. {
  11901. // delegate call to object_t::max_size()
  11902. return m_value.object->max_size();
  11903. }
  11904. default:
  11905. {
  11906. // all other types have max_size() == size()
  11907. return size();
  11908. }
  11909. }
  11910. }
  11911. /// @}
  11912. ///////////////
  11913. // modifiers //
  11914. ///////////////
  11915. /// @name modifiers
  11916. /// @{
  11917. /*!
  11918. @brief clears the contents
  11919. Clears the content of a JSON value and resets it to the default value as
  11920. if @ref basic_json(value_t) would have been called with the current value
  11921. type from @ref type():
  11922. Value type | initial value
  11923. ----------- | -------------
  11924. null | `null`
  11925. boolean | `false`
  11926. string | `""`
  11927. number | `0`
  11928. object | `{}`
  11929. array | `[]`
  11930. @post Has the same effect as calling
  11931. @code {.cpp}
  11932. *this = basic_json(type());
  11933. @endcode
  11934. @liveexample{The example below shows the effect of `clear()` to different
  11935. JSON types.,clear}
  11936. @complexity Linear in the size of the JSON value.
  11937. @iterators All iterators, pointers and references related to this container
  11938. are invalidated.
  11939. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  11940. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  11941. same value than calling `clear()`
  11942. @since version 1.0.0
  11943. */
  11944. void clear() noexcept
  11945. {
  11946. switch (m_type)
  11947. {
  11948. case value_t::number_integer:
  11949. {
  11950. m_value.number_integer = 0;
  11951. break;
  11952. }
  11953. case value_t::number_unsigned:
  11954. {
  11955. m_value.number_unsigned = 0;
  11956. break;
  11957. }
  11958. case value_t::number_float:
  11959. {
  11960. m_value.number_float = 0.0;
  11961. break;
  11962. }
  11963. case value_t::boolean:
  11964. {
  11965. m_value.boolean = false;
  11966. break;
  11967. }
  11968. case value_t::string:
  11969. {
  11970. m_value.string->clear();
  11971. break;
  11972. }
  11973. case value_t::array:
  11974. {
  11975. m_value.array->clear();
  11976. break;
  11977. }
  11978. case value_t::object:
  11979. {
  11980. m_value.object->clear();
  11981. break;
  11982. }
  11983. default:
  11984. break;
  11985. }
  11986. }
  11987. /*!
  11988. @brief add an object to an array
  11989. Appends the given element @a val to the end of the JSON value. If the
  11990. function is called on a JSON null value, an empty array is created before
  11991. appending @a val.
  11992. @param[in] val the value to add to the JSON array
  11993. @throw type_error.308 when called on a type other than JSON array or
  11994. null; example: `"cannot use push_back() with number"`
  11995. @complexity Amortized constant.
  11996. @liveexample{The example shows how `push_back()` and `+=` can be used to
  11997. add elements to a JSON array. Note how the `null` value was silently
  11998. converted to a JSON array.,push_back}
  11999. @since version 1.0.0
  12000. */
  12001. void push_back(basic_json&& val)
  12002. {
  12003. // push_back only works for null objects or arrays
  12004. if (JSON_UNLIKELY(not(is_null() or is_array())))
  12005. {
  12006. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  12007. }
  12008. // transform null object into an array
  12009. if (is_null())
  12010. {
  12011. m_type = value_t::array;
  12012. m_value = value_t::array;
  12013. assert_invariant();
  12014. }
  12015. // add element to array (move semantics)
  12016. m_value.array->push_back(std::move(val));
  12017. // invalidate object
  12018. val.m_type = value_t::null;
  12019. }
  12020. /*!
  12021. @brief add an object to an array
  12022. @copydoc push_back(basic_json&&)
  12023. */
  12024. reference operator+=(basic_json&& val)
  12025. {
  12026. push_back(std::move(val));
  12027. return *this;
  12028. }
  12029. /*!
  12030. @brief add an object to an array
  12031. @copydoc push_back(basic_json&&)
  12032. */
  12033. void push_back(const basic_json& val)
  12034. {
  12035. // push_back only works for null objects or arrays
  12036. if (JSON_UNLIKELY(not(is_null() or is_array())))
  12037. {
  12038. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  12039. }
  12040. // transform null object into an array
  12041. if (is_null())
  12042. {
  12043. m_type = value_t::array;
  12044. m_value = value_t::array;
  12045. assert_invariant();
  12046. }
  12047. // add element to array
  12048. m_value.array->push_back(val);
  12049. }
  12050. /*!
  12051. @brief add an object to an array
  12052. @copydoc push_back(basic_json&&)
  12053. */
  12054. reference operator+=(const basic_json& val)
  12055. {
  12056. push_back(val);
  12057. return *this;
  12058. }
  12059. /*!
  12060. @brief add an object to an object
  12061. Inserts the given element @a val to the JSON object. If the function is
  12062. called on a JSON null value, an empty object is created before inserting
  12063. @a val.
  12064. @param[in] val the value to add to the JSON object
  12065. @throw type_error.308 when called on a type other than JSON object or
  12066. null; example: `"cannot use push_back() with number"`
  12067. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  12068. @liveexample{The example shows how `push_back()` and `+=` can be used to
  12069. add elements to a JSON object. Note how the `null` value was silently
  12070. converted to a JSON object.,push_back__object_t__value}
  12071. @since version 1.0.0
  12072. */
  12073. void push_back(const typename object_t::value_type& val)
  12074. {
  12075. // push_back only works for null objects or objects
  12076. if (JSON_UNLIKELY(not(is_null() or is_object())))
  12077. {
  12078. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  12079. }
  12080. // transform null object into an object
  12081. if (is_null())
  12082. {
  12083. m_type = value_t::object;
  12084. m_value = value_t::object;
  12085. assert_invariant();
  12086. }
  12087. // add element to array
  12088. m_value.object->insert(val);
  12089. }
  12090. /*!
  12091. @brief add an object to an object
  12092. @copydoc push_back(const typename object_t::value_type&)
  12093. */
  12094. reference operator+=(const typename object_t::value_type& val)
  12095. {
  12096. push_back(val);
  12097. return *this;
  12098. }
  12099. /*!
  12100. @brief add an object to an object
  12101. This function allows to use `push_back` with an initializer list. In case
  12102. 1. the current value is an object,
  12103. 2. the initializer list @a init contains only two elements, and
  12104. 3. the first element of @a init is a string,
  12105. @a init is converted into an object element and added using
  12106. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  12107. is converted to a JSON value and added using @ref push_back(basic_json&&).
  12108. @param[in] init an initializer list
  12109. @complexity Linear in the size of the initializer list @a init.
  12110. @note This function is required to resolve an ambiguous overload error,
  12111. because pairs like `{"key", "value"}` can be both interpreted as
  12112. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  12113. https://github.com/nlohmann/json/issues/235 for more information.
  12114. @liveexample{The example shows how initializer lists are treated as
  12115. objects when possible.,push_back__initializer_list}
  12116. */
  12117. void push_back(initializer_list_t init)
  12118. {
  12119. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  12120. {
  12121. basic_json&& key = init.begin()->moved_or_copied();
  12122. push_back(typename object_t::value_type(
  12123. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  12124. }
  12125. else
  12126. {
  12127. push_back(basic_json(init));
  12128. }
  12129. }
  12130. /*!
  12131. @brief add an object to an object
  12132. @copydoc push_back(initializer_list_t)
  12133. */
  12134. reference operator+=(initializer_list_t init)
  12135. {
  12136. push_back(init);
  12137. return *this;
  12138. }
  12139. /*!
  12140. @brief add an object to an array
  12141. Creates a JSON value from the passed parameters @a args to the end of the
  12142. JSON value. If the function is called on a JSON null value, an empty array
  12143. is created before appending the value created from @a args.
  12144. @param[in] args arguments to forward to a constructor of @ref basic_json
  12145. @tparam Args compatible types to create a @ref basic_json object
  12146. @throw type_error.311 when called on a type other than JSON array or
  12147. null; example: `"cannot use emplace_back() with number"`
  12148. @complexity Amortized constant.
  12149. @liveexample{The example shows how `push_back()` can be used to add
  12150. elements to a JSON array. Note how the `null` value was silently converted
  12151. to a JSON array.,emplace_back}
  12152. @since version 2.0.8
  12153. */
  12154. template<class... Args>
  12155. void emplace_back(Args&& ... args)
  12156. {
  12157. // emplace_back only works for null objects or arrays
  12158. if (JSON_UNLIKELY(not(is_null() or is_array())))
  12159. {
  12160. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  12161. }
  12162. // transform null object into an array
  12163. if (is_null())
  12164. {
  12165. m_type = value_t::array;
  12166. m_value = value_t::array;
  12167. assert_invariant();
  12168. }
  12169. // add element to array (perfect forwarding)
  12170. m_value.array->emplace_back(std::forward<Args>(args)...);
  12171. }
  12172. /*!
  12173. @brief add an object to an object if key does not exist
  12174. Inserts a new element into a JSON object constructed in-place with the
  12175. given @a args if there is no element with the key in the container. If the
  12176. function is called on a JSON null value, an empty object is created before
  12177. appending the value created from @a args.
  12178. @param[in] args arguments to forward to a constructor of @ref basic_json
  12179. @tparam Args compatible types to create a @ref basic_json object
  12180. @return a pair consisting of an iterator to the inserted element, or the
  12181. already-existing element if no insertion happened, and a bool
  12182. denoting whether the insertion took place.
  12183. @throw type_error.311 when called on a type other than JSON object or
  12184. null; example: `"cannot use emplace() with number"`
  12185. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  12186. @liveexample{The example shows how `emplace()` can be used to add elements
  12187. to a JSON object. Note how the `null` value was silently converted to a
  12188. JSON object. Further note how no value is added if there was already one
  12189. value stored with the same key.,emplace}
  12190. @since version 2.0.8
  12191. */
  12192. template<class... Args>
  12193. std::pair<iterator, bool> emplace(Args&& ... args)
  12194. {
  12195. // emplace only works for null objects or arrays
  12196. if (JSON_UNLIKELY(not(is_null() or is_object())))
  12197. {
  12198. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  12199. }
  12200. // transform null object into an object
  12201. if (is_null())
  12202. {
  12203. m_type = value_t::object;
  12204. m_value = value_t::object;
  12205. assert_invariant();
  12206. }
  12207. // add element to array (perfect forwarding)
  12208. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  12209. // create result iterator and set iterator to the result of emplace
  12210. auto it = begin();
  12211. it.m_it.object_iterator = res.first;
  12212. // return pair of iterator and boolean
  12213. return {it, res.second};
  12214. }
  12215. /*!
  12216. @brief inserts element
  12217. Inserts element @a val before iterator @a pos.
  12218. @param[in] pos iterator before which the content will be inserted; may be
  12219. the end() iterator
  12220. @param[in] val element to insert
  12221. @return iterator pointing to the inserted @a val.
  12222. @throw type_error.309 if called on JSON values other than arrays;
  12223. example: `"cannot use insert() with string"`
  12224. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  12225. example: `"iterator does not fit current value"`
  12226. @complexity Constant plus linear in the distance between @a pos and end of
  12227. the container.
  12228. @liveexample{The example shows how `insert()` is used.,insert}
  12229. @since version 1.0.0
  12230. */
  12231. iterator insert(const_iterator pos, const basic_json& val)
  12232. {
  12233. // insert only works for arrays
  12234. if (JSON_LIKELY(is_array()))
  12235. {
  12236. // check if iterator pos fits to this JSON value
  12237. if (JSON_UNLIKELY(pos.m_object != this))
  12238. {
  12239. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  12240. }
  12241. // insert to array and return iterator
  12242. iterator result(this);
  12243. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  12244. return result;
  12245. }
  12246. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  12247. }
  12248. /*!
  12249. @brief inserts element
  12250. @copydoc insert(const_iterator, const basic_json&)
  12251. */
  12252. iterator insert(const_iterator pos, basic_json&& val)
  12253. {
  12254. return insert(pos, val);
  12255. }
  12256. /*!
  12257. @brief inserts elements
  12258. Inserts @a cnt copies of @a val before iterator @a pos.
  12259. @param[in] pos iterator before which the content will be inserted; may be
  12260. the end() iterator
  12261. @param[in] cnt number of copies of @a val to insert
  12262. @param[in] val element to insert
  12263. @return iterator pointing to the first element inserted, or @a pos if
  12264. `cnt==0`
  12265. @throw type_error.309 if called on JSON values other than arrays; example:
  12266. `"cannot use insert() with string"`
  12267. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  12268. example: `"iterator does not fit current value"`
  12269. @complexity Linear in @a cnt plus linear in the distance between @a pos
  12270. and end of the container.
  12271. @liveexample{The example shows how `insert()` is used.,insert__count}
  12272. @since version 1.0.0
  12273. */
  12274. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  12275. {
  12276. // insert only works for arrays
  12277. if (JSON_LIKELY(is_array()))
  12278. {
  12279. // check if iterator pos fits to this JSON value
  12280. if (JSON_UNLIKELY(pos.m_object != this))
  12281. {
  12282. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  12283. }
  12284. // insert to array and return iterator
  12285. iterator result(this);
  12286. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  12287. return result;
  12288. }
  12289. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  12290. }
  12291. /*!
  12292. @brief inserts elements
  12293. Inserts elements from range `[first, last)` before iterator @a pos.
  12294. @param[in] pos iterator before which the content will be inserted; may be
  12295. the end() iterator
  12296. @param[in] first begin of the range of elements to insert
  12297. @param[in] last end of the range of elements to insert
  12298. @throw type_error.309 if called on JSON values other than arrays; example:
  12299. `"cannot use insert() with string"`
  12300. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  12301. example: `"iterator does not fit current value"`
  12302. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  12303. same JSON value; example: `"iterators do not fit"`
  12304. @throw invalid_iterator.211 if @a first or @a last are iterators into
  12305. container for which insert is called; example: `"passed iterators may not
  12306. belong to container"`
  12307. @return iterator pointing to the first element inserted, or @a pos if
  12308. `first==last`
  12309. @complexity Linear in `std::distance(first, last)` plus linear in the
  12310. distance between @a pos and end of the container.
  12311. @liveexample{The example shows how `insert()` is used.,insert__range}
  12312. @since version 1.0.0
  12313. */
  12314. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  12315. {
  12316. // insert only works for arrays
  12317. if (JSON_UNLIKELY(not is_array()))
  12318. {
  12319. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  12320. }
  12321. // check if iterator pos fits to this JSON value
  12322. if (JSON_UNLIKELY(pos.m_object != this))
  12323. {
  12324. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  12325. }
  12326. // check if range iterators belong to the same JSON object
  12327. if (JSON_UNLIKELY(first.m_object != last.m_object))
  12328. {
  12329. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  12330. }
  12331. if (JSON_UNLIKELY(first.m_object == this))
  12332. {
  12333. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  12334. }
  12335. // insert to array and return iterator
  12336. iterator result(this);
  12337. result.m_it.array_iterator = m_value.array->insert(
  12338. pos.m_it.array_iterator,
  12339. first.m_it.array_iterator,
  12340. last.m_it.array_iterator);
  12341. return result;
  12342. }
  12343. /*!
  12344. @brief inserts elements
  12345. Inserts elements from initializer list @a ilist before iterator @a pos.
  12346. @param[in] pos iterator before which the content will be inserted; may be
  12347. the end() iterator
  12348. @param[in] ilist initializer list to insert the values from
  12349. @throw type_error.309 if called on JSON values other than arrays; example:
  12350. `"cannot use insert() with string"`
  12351. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  12352. example: `"iterator does not fit current value"`
  12353. @return iterator pointing to the first element inserted, or @a pos if
  12354. `ilist` is empty
  12355. @complexity Linear in `ilist.size()` plus linear in the distance between
  12356. @a pos and end of the container.
  12357. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  12358. @since version 1.0.0
  12359. */
  12360. iterator insert(const_iterator pos, initializer_list_t ilist)
  12361. {
  12362. // insert only works for arrays
  12363. if (JSON_UNLIKELY(not is_array()))
  12364. {
  12365. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  12366. }
  12367. // check if iterator pos fits to this JSON value
  12368. if (JSON_UNLIKELY(pos.m_object != this))
  12369. {
  12370. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  12371. }
  12372. // insert to array and return iterator
  12373. iterator result(this);
  12374. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
  12375. return result;
  12376. }
  12377. /*!
  12378. @brief inserts elements
  12379. Inserts elements from range `[first, last)`.
  12380. @param[in] first begin of the range of elements to insert
  12381. @param[in] last end of the range of elements to insert
  12382. @throw type_error.309 if called on JSON values other than objects; example:
  12383. `"cannot use insert() with string"`
  12384. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  12385. point to an object; example: `"iterators first and last must point to
  12386. objects"`
  12387. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  12388. same JSON value; example: `"iterators do not fit"`
  12389. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  12390. of elements to insert.
  12391. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  12392. @since version 3.0.0
  12393. */
  12394. void insert(const_iterator first, const_iterator last)
  12395. {
  12396. // insert only works for objects
  12397. if (JSON_UNLIKELY(not is_object()))
  12398. {
  12399. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  12400. }
  12401. // check if range iterators belong to the same JSON object
  12402. if (JSON_UNLIKELY(first.m_object != last.m_object))
  12403. {
  12404. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  12405. }
  12406. // passed iterators must belong to objects
  12407. if (JSON_UNLIKELY(not first.m_object->is_object()))
  12408. {
  12409. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  12410. }
  12411. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  12412. }
  12413. /*!
  12414. @brief updates a JSON object from another object, overwriting existing keys
  12415. Inserts all values from JSON object @a j and overwrites existing keys.
  12416. @param[in] j JSON object to read values from
  12417. @throw type_error.312 if called on JSON values other than objects; example:
  12418. `"cannot use update() with string"`
  12419. @complexity O(N*log(size() + N)), where N is the number of elements to
  12420. insert.
  12421. @liveexample{The example shows how `update()` is used.,update}
  12422. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  12423. @since version 3.0.0
  12424. */
  12425. void update(const_reference j)
  12426. {
  12427. // implicitly convert null value to an empty object
  12428. if (is_null())
  12429. {
  12430. m_type = value_t::object;
  12431. m_value.object = create<object_t>();
  12432. assert_invariant();
  12433. }
  12434. if (JSON_UNLIKELY(not is_object()))
  12435. {
  12436. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  12437. }
  12438. if (JSON_UNLIKELY(not j.is_object()))
  12439. {
  12440. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  12441. }
  12442. for (auto it = j.cbegin(); it != j.cend(); ++it)
  12443. {
  12444. m_value.object->operator[](it.key()) = it.value();
  12445. }
  12446. }
  12447. /*!
  12448. @brief updates a JSON object from another object, overwriting existing keys
  12449. Inserts all values from from range `[first, last)` and overwrites existing
  12450. keys.
  12451. @param[in] first begin of the range of elements to insert
  12452. @param[in] last end of the range of elements to insert
  12453. @throw type_error.312 if called on JSON values other than objects; example:
  12454. `"cannot use update() with string"`
  12455. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  12456. point to an object; example: `"iterators first and last must point to
  12457. objects"`
  12458. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  12459. same JSON value; example: `"iterators do not fit"`
  12460. @complexity O(N*log(size() + N)), where N is the number of elements to
  12461. insert.
  12462. @liveexample{The example shows how `update()` is used__range.,update}
  12463. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  12464. @since version 3.0.0
  12465. */
  12466. void update(const_iterator first, const_iterator last)
  12467. {
  12468. // implicitly convert null value to an empty object
  12469. if (is_null())
  12470. {
  12471. m_type = value_t::object;
  12472. m_value.object = create<object_t>();
  12473. assert_invariant();
  12474. }
  12475. if (JSON_UNLIKELY(not is_object()))
  12476. {
  12477. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  12478. }
  12479. // check if range iterators belong to the same JSON object
  12480. if (JSON_UNLIKELY(first.m_object != last.m_object))
  12481. {
  12482. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  12483. }
  12484. // passed iterators must belong to objects
  12485. if (JSON_UNLIKELY(not first.m_object->is_object()
  12486. or not last.m_object->is_object()))
  12487. {
  12488. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  12489. }
  12490. for (auto it = first; it != last; ++it)
  12491. {
  12492. m_value.object->operator[](it.key()) = it.value();
  12493. }
  12494. }
  12495. /*!
  12496. @brief exchanges the values
  12497. Exchanges the contents of the JSON value with those of @a other. Does not
  12498. invoke any move, copy, or swap operations on individual elements. All
  12499. iterators and references remain valid. The past-the-end iterator is
  12500. invalidated.
  12501. @param[in,out] other JSON value to exchange the contents with
  12502. @complexity Constant.
  12503. @liveexample{The example below shows how JSON values can be swapped with
  12504. `swap()`.,swap__reference}
  12505. @since version 1.0.0
  12506. */
  12507. void swap(reference other) noexcept (
  12508. std::is_nothrow_move_constructible<value_t>::value and
  12509. std::is_nothrow_move_assignable<value_t>::value and
  12510. std::is_nothrow_move_constructible<json_value>::value and
  12511. std::is_nothrow_move_assignable<json_value>::value
  12512. )
  12513. {
  12514. std::swap(m_type, other.m_type);
  12515. std::swap(m_value, other.m_value);
  12516. assert_invariant();
  12517. }
  12518. /*!
  12519. @brief exchanges the values
  12520. Exchanges the contents of a JSON array with those of @a other. Does not
  12521. invoke any move, copy, or swap operations on individual elements. All
  12522. iterators and references remain valid. The past-the-end iterator is
  12523. invalidated.
  12524. @param[in,out] other array to exchange the contents with
  12525. @throw type_error.310 when JSON value is not an array; example: `"cannot
  12526. use swap() with string"`
  12527. @complexity Constant.
  12528. @liveexample{The example below shows how arrays can be swapped with
  12529. `swap()`.,swap__array_t}
  12530. @since version 1.0.0
  12531. */
  12532. void swap(array_t& other)
  12533. {
  12534. // swap only works for arrays
  12535. if (JSON_LIKELY(is_array()))
  12536. {
  12537. std::swap(*(m_value.array), other);
  12538. }
  12539. else
  12540. {
  12541. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  12542. }
  12543. }
  12544. /*!
  12545. @brief exchanges the values
  12546. Exchanges the contents of a JSON object with those of @a other. Does not
  12547. invoke any move, copy, or swap operations on individual elements. All
  12548. iterators and references remain valid. The past-the-end iterator is
  12549. invalidated.
  12550. @param[in,out] other object to exchange the contents with
  12551. @throw type_error.310 when JSON value is not an object; example:
  12552. `"cannot use swap() with string"`
  12553. @complexity Constant.
  12554. @liveexample{The example below shows how objects can be swapped with
  12555. `swap()`.,swap__object_t}
  12556. @since version 1.0.0
  12557. */
  12558. void swap(object_t& other)
  12559. {
  12560. // swap only works for objects
  12561. if (JSON_LIKELY(is_object()))
  12562. {
  12563. std::swap(*(m_value.object), other);
  12564. }
  12565. else
  12566. {
  12567. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  12568. }
  12569. }
  12570. /*!
  12571. @brief exchanges the values
  12572. Exchanges the contents of a JSON string with those of @a other. Does not
  12573. invoke any move, copy, or swap operations on individual elements. All
  12574. iterators and references remain valid. The past-the-end iterator is
  12575. invalidated.
  12576. @param[in,out] other string to exchange the contents with
  12577. @throw type_error.310 when JSON value is not a string; example: `"cannot
  12578. use swap() with boolean"`
  12579. @complexity Constant.
  12580. @liveexample{The example below shows how strings can be swapped with
  12581. `swap()`.,swap__string_t}
  12582. @since version 1.0.0
  12583. */
  12584. void swap(string_t& other)
  12585. {
  12586. // swap only works for strings
  12587. if (JSON_LIKELY(is_string()))
  12588. {
  12589. std::swap(*(m_value.string), other);
  12590. }
  12591. else
  12592. {
  12593. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  12594. }
  12595. }
  12596. /// @}
  12597. public:
  12598. //////////////////////////////////////////
  12599. // lexicographical comparison operators //
  12600. //////////////////////////////////////////
  12601. /// @name lexicographical comparison operators
  12602. /// @{
  12603. /*!
  12604. @brief comparison: equal
  12605. Compares two JSON values for equality according to the following rules:
  12606. - Two JSON values are equal if (1) they are from the same type and (2)
  12607. their stored values are the same according to their respective
  12608. `operator==`.
  12609. - Integer and floating-point numbers are automatically converted before
  12610. comparison. Note than two NaN values are always treated as unequal.
  12611. - Two JSON null values are equal.
  12612. @note Floating-point inside JSON values numbers are compared with
  12613. `json::number_float_t::operator==` which is `double::operator==` by
  12614. default. To compare floating-point while respecting an epsilon, an alternative
  12615. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  12616. could be used, for instance
  12617. @code {.cpp}
  12618. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  12619. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  12620. {
  12621. return std::abs(a - b) <= epsilon;
  12622. }
  12623. @endcode
  12624. @note NaN values never compare equal to themselves or to other NaN values.
  12625. @param[in] lhs first JSON value to consider
  12626. @param[in] rhs second JSON value to consider
  12627. @return whether the values @a lhs and @a rhs are equal
  12628. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  12629. @complexity Linear.
  12630. @liveexample{The example demonstrates comparing several JSON
  12631. types.,operator__equal}
  12632. @since version 1.0.0
  12633. */
  12634. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  12635. {
  12636. const auto lhs_type = lhs.type();
  12637. const auto rhs_type = rhs.type();
  12638. if (lhs_type == rhs_type)
  12639. {
  12640. switch (lhs_type)
  12641. {
  12642. case value_t::array:
  12643. return (*lhs.m_value.array == *rhs.m_value.array);
  12644. case value_t::object:
  12645. return (*lhs.m_value.object == *rhs.m_value.object);
  12646. case value_t::null:
  12647. return true;
  12648. case value_t::string:
  12649. return (*lhs.m_value.string == *rhs.m_value.string);
  12650. case value_t::boolean:
  12651. return (lhs.m_value.boolean == rhs.m_value.boolean);
  12652. case value_t::number_integer:
  12653. return (lhs.m_value.number_integer == rhs.m_value.number_integer);
  12654. case value_t::number_unsigned:
  12655. return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
  12656. case value_t::number_float:
  12657. return (lhs.m_value.number_float == rhs.m_value.number_float);
  12658. default:
  12659. return false;
  12660. }
  12661. }
  12662. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  12663. {
  12664. return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
  12665. }
  12666. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  12667. {
  12668. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
  12669. }
  12670. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  12671. {
  12672. return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
  12673. }
  12674. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  12675. {
  12676. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
  12677. }
  12678. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  12679. {
  12680. return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
  12681. }
  12682. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  12683. {
  12684. return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
  12685. }
  12686. return false;
  12687. }
  12688. /*!
  12689. @brief comparison: equal
  12690. @copydoc operator==(const_reference, const_reference)
  12691. */
  12692. template<typename ScalarType, typename std::enable_if<
  12693. std::is_scalar<ScalarType>::value, int>::type = 0>
  12694. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  12695. {
  12696. return (lhs == basic_json(rhs));
  12697. }
  12698. /*!
  12699. @brief comparison: equal
  12700. @copydoc operator==(const_reference, const_reference)
  12701. */
  12702. template<typename ScalarType, typename std::enable_if<
  12703. std::is_scalar<ScalarType>::value, int>::type = 0>
  12704. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  12705. {
  12706. return (basic_json(lhs) == rhs);
  12707. }
  12708. /*!
  12709. @brief comparison: not equal
  12710. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  12711. @param[in] lhs first JSON value to consider
  12712. @param[in] rhs second JSON value to consider
  12713. @return whether the values @a lhs and @a rhs are not equal
  12714. @complexity Linear.
  12715. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  12716. @liveexample{The example demonstrates comparing several JSON
  12717. types.,operator__notequal}
  12718. @since version 1.0.0
  12719. */
  12720. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  12721. {
  12722. return not (lhs == rhs);
  12723. }
  12724. /*!
  12725. @brief comparison: not equal
  12726. @copydoc operator!=(const_reference, const_reference)
  12727. */
  12728. template<typename ScalarType, typename std::enable_if<
  12729. std::is_scalar<ScalarType>::value, int>::type = 0>
  12730. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  12731. {
  12732. return (lhs != basic_json(rhs));
  12733. }
  12734. /*!
  12735. @brief comparison: not equal
  12736. @copydoc operator!=(const_reference, const_reference)
  12737. */
  12738. template<typename ScalarType, typename std::enable_if<
  12739. std::is_scalar<ScalarType>::value, int>::type = 0>
  12740. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  12741. {
  12742. return (basic_json(lhs) != rhs);
  12743. }
  12744. /*!
  12745. @brief comparison: less than
  12746. Compares whether one JSON value @a lhs is less than another JSON value @a
  12747. rhs according to the following rules:
  12748. - If @a lhs and @a rhs have the same type, the values are compared using
  12749. the default `<` operator.
  12750. - Integer and floating-point numbers are automatically converted before
  12751. comparison
  12752. - In case @a lhs and @a rhs have different types, the values are ignored
  12753. and the order of the types is considered, see
  12754. @ref operator<(const value_t, const value_t).
  12755. @param[in] lhs first JSON value to consider
  12756. @param[in] rhs second JSON value to consider
  12757. @return whether @a lhs is less than @a rhs
  12758. @complexity Linear.
  12759. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  12760. @liveexample{The example demonstrates comparing several JSON
  12761. types.,operator__less}
  12762. @since version 1.0.0
  12763. */
  12764. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  12765. {
  12766. const auto lhs_type = lhs.type();
  12767. const auto rhs_type = rhs.type();
  12768. if (lhs_type == rhs_type)
  12769. {
  12770. switch (lhs_type)
  12771. {
  12772. case value_t::array:
  12773. return (*lhs.m_value.array) < (*rhs.m_value.array);
  12774. case value_t::object:
  12775. return *lhs.m_value.object < *rhs.m_value.object;
  12776. case value_t::null:
  12777. return false;
  12778. case value_t::string:
  12779. return *lhs.m_value.string < *rhs.m_value.string;
  12780. case value_t::boolean:
  12781. return lhs.m_value.boolean < rhs.m_value.boolean;
  12782. case value_t::number_integer:
  12783. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  12784. case value_t::number_unsigned:
  12785. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  12786. case value_t::number_float:
  12787. return lhs.m_value.number_float < rhs.m_value.number_float;
  12788. default:
  12789. return false;
  12790. }
  12791. }
  12792. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  12793. {
  12794. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  12795. }
  12796. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  12797. {
  12798. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  12799. }
  12800. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  12801. {
  12802. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  12803. }
  12804. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  12805. {
  12806. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  12807. }
  12808. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  12809. {
  12810. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  12811. }
  12812. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  12813. {
  12814. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  12815. }
  12816. // We only reach this line if we cannot compare values. In that case,
  12817. // we compare types. Note we have to call the operator explicitly,
  12818. // because MSVC has problems otherwise.
  12819. return operator<(lhs_type, rhs_type);
  12820. }
  12821. /*!
  12822. @brief comparison: less than
  12823. @copydoc operator<(const_reference, const_reference)
  12824. */
  12825. template<typename ScalarType, typename std::enable_if<
  12826. std::is_scalar<ScalarType>::value, int>::type = 0>
  12827. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  12828. {
  12829. return (lhs < basic_json(rhs));
  12830. }
  12831. /*!
  12832. @brief comparison: less than
  12833. @copydoc operator<(const_reference, const_reference)
  12834. */
  12835. template<typename ScalarType, typename std::enable_if<
  12836. std::is_scalar<ScalarType>::value, int>::type = 0>
  12837. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  12838. {
  12839. return (basic_json(lhs) < rhs);
  12840. }
  12841. /*!
  12842. @brief comparison: less than or equal
  12843. Compares whether one JSON value @a lhs is less than or equal to another
  12844. JSON value by calculating `not (rhs < lhs)`.
  12845. @param[in] lhs first JSON value to consider
  12846. @param[in] rhs second JSON value to consider
  12847. @return whether @a lhs is less than or equal to @a rhs
  12848. @complexity Linear.
  12849. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  12850. @liveexample{The example demonstrates comparing several JSON
  12851. types.,operator__greater}
  12852. @since version 1.0.0
  12853. */
  12854. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  12855. {
  12856. return not (rhs < lhs);
  12857. }
  12858. /*!
  12859. @brief comparison: less than or equal
  12860. @copydoc operator<=(const_reference, const_reference)
  12861. */
  12862. template<typename ScalarType, typename std::enable_if<
  12863. std::is_scalar<ScalarType>::value, int>::type = 0>
  12864. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  12865. {
  12866. return (lhs <= basic_json(rhs));
  12867. }
  12868. /*!
  12869. @brief comparison: less than or equal
  12870. @copydoc operator<=(const_reference, const_reference)
  12871. */
  12872. template<typename ScalarType, typename std::enable_if<
  12873. std::is_scalar<ScalarType>::value, int>::type = 0>
  12874. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  12875. {
  12876. return (basic_json(lhs) <= rhs);
  12877. }
  12878. /*!
  12879. @brief comparison: greater than
  12880. Compares whether one JSON value @a lhs is greater than another
  12881. JSON value by calculating `not (lhs <= rhs)`.
  12882. @param[in] lhs first JSON value to consider
  12883. @param[in] rhs second JSON value to consider
  12884. @return whether @a lhs is greater than to @a rhs
  12885. @complexity Linear.
  12886. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  12887. @liveexample{The example demonstrates comparing several JSON
  12888. types.,operator__lessequal}
  12889. @since version 1.0.0
  12890. */
  12891. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  12892. {
  12893. return not (lhs <= rhs);
  12894. }
  12895. /*!
  12896. @brief comparison: greater than
  12897. @copydoc operator>(const_reference, const_reference)
  12898. */
  12899. template<typename ScalarType, typename std::enable_if<
  12900. std::is_scalar<ScalarType>::value, int>::type = 0>
  12901. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  12902. {
  12903. return (lhs > basic_json(rhs));
  12904. }
  12905. /*!
  12906. @brief comparison: greater than
  12907. @copydoc operator>(const_reference, const_reference)
  12908. */
  12909. template<typename ScalarType, typename std::enable_if<
  12910. std::is_scalar<ScalarType>::value, int>::type = 0>
  12911. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  12912. {
  12913. return (basic_json(lhs) > rhs);
  12914. }
  12915. /*!
  12916. @brief comparison: greater than or equal
  12917. Compares whether one JSON value @a lhs is greater than or equal to another
  12918. JSON value by calculating `not (lhs < rhs)`.
  12919. @param[in] lhs first JSON value to consider
  12920. @param[in] rhs second JSON value to consider
  12921. @return whether @a lhs is greater than or equal to @a rhs
  12922. @complexity Linear.
  12923. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  12924. @liveexample{The example demonstrates comparing several JSON
  12925. types.,operator__greaterequal}
  12926. @since version 1.0.0
  12927. */
  12928. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  12929. {
  12930. return not (lhs < rhs);
  12931. }
  12932. /*!
  12933. @brief comparison: greater than or equal
  12934. @copydoc operator>=(const_reference, const_reference)
  12935. */
  12936. template<typename ScalarType, typename std::enable_if<
  12937. std::is_scalar<ScalarType>::value, int>::type = 0>
  12938. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  12939. {
  12940. return (lhs >= basic_json(rhs));
  12941. }
  12942. /*!
  12943. @brief comparison: greater than or equal
  12944. @copydoc operator>=(const_reference, const_reference)
  12945. */
  12946. template<typename ScalarType, typename std::enable_if<
  12947. std::is_scalar<ScalarType>::value, int>::type = 0>
  12948. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  12949. {
  12950. return (basic_json(lhs) >= rhs);
  12951. }
  12952. /// @}
  12953. ///////////////////
  12954. // serialization //
  12955. ///////////////////
  12956. /// @name serialization
  12957. /// @{
  12958. /*!
  12959. @brief serialize to stream
  12960. Serialize the given JSON value @a j to the output stream @a o. The JSON
  12961. value will be serialized using the @ref dump member function.
  12962. - The indentation of the output can be controlled with the member variable
  12963. `width` of the output stream @a o. For instance, using the manipulator
  12964. `std::setw(4)` on @a o sets the indentation level to `4` and the
  12965. serialization result is the same as calling `dump(4)`.
  12966. - The indentation character can be controlled with the member variable
  12967. `fill` of the output stream @a o. For instance, the manipulator
  12968. `std::setfill('\\t')` sets indentation to use a tab character rather than
  12969. the default space character.
  12970. @param[in,out] o stream to serialize to
  12971. @param[in] j JSON value to serialize
  12972. @return the stream @a o
  12973. @throw type_error.316 if a string stored inside the JSON value is not
  12974. UTF-8 encoded
  12975. @complexity Linear.
  12976. @liveexample{The example below shows the serialization with different
  12977. parameters to `width` to adjust the indentation level.,operator_serialize}
  12978. @since version 1.0.0; indentation character added in version 3.0.0
  12979. */
  12980. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  12981. {
  12982. // read width member and use it as indentation parameter if nonzero
  12983. const bool pretty_print = (o.width() > 0);
  12984. const auto indentation = (pretty_print ? o.width() : 0);
  12985. // reset width to 0 for subsequent calls to this stream
  12986. o.width(0);
  12987. // do the actual serialization
  12988. serializer s(detail::output_adapter<char>(o), o.fill());
  12989. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  12990. return o;
  12991. }
  12992. /*!
  12993. @brief serialize to stream
  12994. @deprecated This stream operator is deprecated and will be removed in
  12995. future 4.0.0 of the library. Please use
  12996. @ref operator<<(std::ostream&, const basic_json&)
  12997. instead; that is, replace calls like `j >> o;` with `o << j;`.
  12998. @since version 1.0.0; deprecated since version 3.0.0
  12999. */
  13000. JSON_DEPRECATED
  13001. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  13002. {
  13003. return o << j;
  13004. }
  13005. /// @}
  13006. /////////////////////
  13007. // deserialization //
  13008. /////////////////////
  13009. /// @name deserialization
  13010. /// @{
  13011. /*!
  13012. @brief deserialize from a compatible input
  13013. This function reads from a compatible input. Examples are:
  13014. - an array of 1-byte values
  13015. - strings with character/literal type with size of 1 byte
  13016. - input streams
  13017. - container with contiguous storage of 1-byte values. Compatible container
  13018. types include `std::vector`, `std::string`, `std::array`,
  13019. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  13020. arrays can be used with `std::begin()`/`std::end()`. User-defined
  13021. containers can be used as long as they implement random-access iterators
  13022. and a contiguous storage.
  13023. @pre Each element of the container has a size of 1 byte. Violating this
  13024. precondition yields undefined behavior. **This precondition is enforced
  13025. with a static assertion.**
  13026. @pre The container storage is contiguous. Violating this precondition
  13027. yields undefined behavior. **This precondition is enforced with an
  13028. assertion.**
  13029. @pre Each element of the container has a size of 1 byte. Violating this
  13030. precondition yields undefined behavior. **This precondition is enforced
  13031. with a static assertion.**
  13032. @warning There is no way to enforce all preconditions at compile-time. If
  13033. the function is called with a noncompliant container and with
  13034. assertions switched off, the behavior is undefined and will most
  13035. likely yield segmentation violation.
  13036. @param[in] i input to read from
  13037. @param[in] cb a parser callback function of type @ref parser_callback_t
  13038. which is used to control the deserialization by filtering unwanted values
  13039. (optional)
  13040. @return result of the deserialization
  13041. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  13042. of input; expected string literal""`
  13043. @throw parse_error.102 if to_unicode fails or surrogate error
  13044. @throw parse_error.103 if to_unicode fails
  13045. @complexity Linear in the length of the input. The parser is a predictive
  13046. LL(1) parser. The complexity can be higher if the parser callback function
  13047. @a cb has a super-linear complexity.
  13048. @note A UTF-8 byte order mark is silently ignored.
  13049. @liveexample{The example below demonstrates the `parse()` function reading
  13050. from an array.,parse__array__parser_callback_t}
  13051. @liveexample{The example below demonstrates the `parse()` function with
  13052. and without callback function.,parse__string__parser_callback_t}
  13053. @liveexample{The example below demonstrates the `parse()` function with
  13054. and without callback function.,parse__istream__parser_callback_t}
  13055. @liveexample{The example below demonstrates the `parse()` function reading
  13056. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  13057. @since version 2.0.3 (contiguous containers)
  13058. */
  13059. static basic_json parse(detail::input_adapter i,
  13060. const parser_callback_t cb = nullptr,
  13061. const bool allow_exceptions = true)
  13062. {
  13063. basic_json result;
  13064. parser(i, cb, allow_exceptions).parse(true, result);
  13065. return result;
  13066. }
  13067. /*!
  13068. @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
  13069. */
  13070. static basic_json parse(detail::input_adapter& i,
  13071. const parser_callback_t cb = nullptr,
  13072. const bool allow_exceptions = true)
  13073. {
  13074. basic_json result;
  13075. parser(i, cb, allow_exceptions).parse(true, result);
  13076. return result;
  13077. }
  13078. static bool accept(detail::input_adapter i)
  13079. {
  13080. return parser(i).accept(true);
  13081. }
  13082. static bool accept(detail::input_adapter& i)
  13083. {
  13084. return parser(i).accept(true);
  13085. }
  13086. /*!
  13087. @brief deserialize from an iterator range with contiguous storage
  13088. This function reads from an iterator range of a container with contiguous
  13089. storage of 1-byte values. Compatible container types include
  13090. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  13091. `std::initializer_list`. Furthermore, C-style arrays can be used with
  13092. `std::begin()`/`std::end()`. User-defined containers can be used as long
  13093. as they implement random-access iterators and a contiguous storage.
  13094. @pre The iterator range is contiguous. Violating this precondition yields
  13095. undefined behavior. **This precondition is enforced with an assertion.**
  13096. @pre Each element in the range has a size of 1 byte. Violating this
  13097. precondition yields undefined behavior. **This precondition is enforced
  13098. with a static assertion.**
  13099. @warning There is no way to enforce all preconditions at compile-time. If
  13100. the function is called with noncompliant iterators and with
  13101. assertions switched off, the behavior is undefined and will most
  13102. likely yield segmentation violation.
  13103. @tparam IteratorType iterator of container with contiguous storage
  13104. @param[in] first begin of the range to parse (included)
  13105. @param[in] last end of the range to parse (excluded)
  13106. @param[in] cb a parser callback function of type @ref parser_callback_t
  13107. which is used to control the deserialization by filtering unwanted values
  13108. (optional)
  13109. @param[in] allow_exceptions whether to throw exceptions in case of a
  13110. parse error (optional, true by default)
  13111. @return result of the deserialization
  13112. @throw parse_error.101 in case of an unexpected token
  13113. @throw parse_error.102 if to_unicode fails or surrogate error
  13114. @throw parse_error.103 if to_unicode fails
  13115. @complexity Linear in the length of the input. The parser is a predictive
  13116. LL(1) parser. The complexity can be higher if the parser callback function
  13117. @a cb has a super-linear complexity.
  13118. @note A UTF-8 byte order mark is silently ignored.
  13119. @liveexample{The example below demonstrates the `parse()` function reading
  13120. from an iterator range.,parse__iteratortype__parser_callback_t}
  13121. @since version 2.0.3
  13122. */
  13123. template<class IteratorType, typename std::enable_if<
  13124. std::is_base_of<
  13125. std::random_access_iterator_tag,
  13126. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  13127. static basic_json parse(IteratorType first, IteratorType last,
  13128. const parser_callback_t cb = nullptr,
  13129. const bool allow_exceptions = true)
  13130. {
  13131. basic_json result;
  13132. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  13133. return result;
  13134. }
  13135. template<class IteratorType, typename std::enable_if<
  13136. std::is_base_of<
  13137. std::random_access_iterator_tag,
  13138. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  13139. static bool accept(IteratorType first, IteratorType last)
  13140. {
  13141. return parser(detail::input_adapter(first, last)).accept(true);
  13142. }
  13143. /*!
  13144. @brief deserialize from stream
  13145. @deprecated This stream operator is deprecated and will be removed in
  13146. version 4.0.0 of the library. Please use
  13147. @ref operator>>(std::istream&, basic_json&)
  13148. instead; that is, replace calls like `j << i;` with `i >> j;`.
  13149. @since version 1.0.0; deprecated since version 3.0.0
  13150. */
  13151. JSON_DEPRECATED
  13152. friend std::istream& operator<<(basic_json& j, std::istream& i)
  13153. {
  13154. return operator>>(i, j);
  13155. }
  13156. /*!
  13157. @brief deserialize from stream
  13158. Deserializes an input stream to a JSON value.
  13159. @param[in,out] i input stream to read a serialized JSON value from
  13160. @param[in,out] j JSON value to write the deserialized input to
  13161. @throw parse_error.101 in case of an unexpected token
  13162. @throw parse_error.102 if to_unicode fails or surrogate error
  13163. @throw parse_error.103 if to_unicode fails
  13164. @complexity Linear in the length of the input. The parser is a predictive
  13165. LL(1) parser.
  13166. @note A UTF-8 byte order mark is silently ignored.
  13167. @liveexample{The example below shows how a JSON value is constructed by
  13168. reading a serialization from a stream.,operator_deserialize}
  13169. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  13170. parser callback function to filter values while parsing
  13171. @since version 1.0.0
  13172. */
  13173. friend std::istream& operator>>(std::istream& i, basic_json& j)
  13174. {
  13175. parser(detail::input_adapter(i)).parse(false, j);
  13176. return i;
  13177. }
  13178. /// @}
  13179. ///////////////////////////
  13180. // convenience functions //
  13181. ///////////////////////////
  13182. /*!
  13183. @brief return the type as string
  13184. Returns the type name as string to be used in error messages - usually to
  13185. indicate that a function was called on a wrong JSON type.
  13186. @return a string representation of a the @a m_type member:
  13187. Value type | return value
  13188. ----------- | -------------
  13189. null | `"null"`
  13190. boolean | `"boolean"`
  13191. string | `"string"`
  13192. number | `"number"` (for all number types)
  13193. object | `"object"`
  13194. array | `"array"`
  13195. discarded | `"discarded"`
  13196. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  13197. @complexity Constant.
  13198. @liveexample{The following code exemplifies `type_name()` for all JSON
  13199. types.,type_name}
  13200. @sa @ref type() -- return the type of the JSON value
  13201. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  13202. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  13203. since 3.0.0
  13204. */
  13205. const char* type_name() const noexcept
  13206. {
  13207. {
  13208. switch (m_type)
  13209. {
  13210. case value_t::null:
  13211. return "null";
  13212. case value_t::object:
  13213. return "object";
  13214. case value_t::array:
  13215. return "array";
  13216. case value_t::string:
  13217. return "string";
  13218. case value_t::boolean:
  13219. return "boolean";
  13220. case value_t::discarded:
  13221. return "discarded";
  13222. default:
  13223. return "number";
  13224. }
  13225. }
  13226. }
  13227. private:
  13228. //////////////////////
  13229. // member variables //
  13230. //////////////////////
  13231. /// the type of the current element
  13232. value_t m_type = value_t::null;
  13233. /// the value of the current element
  13234. json_value m_value = {};
  13235. //////////////////////////////////////////
  13236. // binary serialization/deserialization //
  13237. //////////////////////////////////////////
  13238. /// @name binary serialization/deserialization support
  13239. /// @{
  13240. public:
  13241. /*!
  13242. @brief create a CBOR serialization of a given JSON value
  13243. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  13244. Binary Object Representation) serialization format. CBOR is a binary
  13245. serialization format which aims to be more compact than JSON itself, yet
  13246. more efficient to parse.
  13247. The library uses the following mapping from JSON values types to
  13248. CBOR types according to the CBOR specification (RFC 7049):
  13249. JSON value type | value/range | CBOR type | first byte
  13250. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  13251. null | `null` | Null | 0xF6
  13252. boolean | `true` | True | 0xF5
  13253. boolean | `false` | False | 0xF4
  13254. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  13255. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  13256. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  13257. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  13258. number_integer | -24..-1 | Negative integer | 0x20..0x37
  13259. number_integer | 0..23 | Integer | 0x00..0x17
  13260. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  13261. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  13262. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  13263. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  13264. number_unsigned | 0..23 | Integer | 0x00..0x17
  13265. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  13266. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  13267. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  13268. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  13269. number_float | *any value* | Double-Precision Float | 0xFB
  13270. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  13271. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  13272. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  13273. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  13274. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  13275. array | *size*: 0..23 | array | 0x80..0x97
  13276. array | *size*: 23..255 | array (1 byte follow) | 0x98
  13277. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  13278. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  13279. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  13280. object | *size*: 0..23 | map | 0xA0..0xB7
  13281. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  13282. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  13283. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  13284. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  13285. @note The mapping is **complete** in the sense that any JSON value type
  13286. can be converted to a CBOR value.
  13287. @note If NaN or Infinity are stored inside a JSON number, they are
  13288. serialized properly. This behavior differs from the @ref dump()
  13289. function which serializes NaN or Infinity to `null`.
  13290. @note The following CBOR types are not used in the conversion:
  13291. - byte strings (0x40..0x5F)
  13292. - UTF-8 strings terminated by "break" (0x7F)
  13293. - arrays terminated by "break" (0x9F)
  13294. - maps terminated by "break" (0xBF)
  13295. - date/time (0xC0..0xC1)
  13296. - bignum (0xC2..0xC3)
  13297. - decimal fraction (0xC4)
  13298. - bigfloat (0xC5)
  13299. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  13300. - expected conversions (0xD5..0xD7)
  13301. - simple values (0xE0..0xF3, 0xF8)
  13302. - undefined (0xF7)
  13303. - half and single-precision floats (0xF9-0xFA)
  13304. - break (0xFF)
  13305. @param[in] j JSON value to serialize
  13306. @return MessagePack serialization as byte vector
  13307. @complexity Linear in the size of the JSON value @a j.
  13308. @liveexample{The example shows the serialization of a JSON value to a byte
  13309. vector in CBOR format.,to_cbor}
  13310. @sa http://cbor.io
  13311. @sa @ref from_cbor(detail::input_adapter, const bool strict) for the
  13312. analogous deserialization
  13313. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  13314. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  13315. related UBJSON format
  13316. @since version 2.0.9
  13317. */
  13318. static std::vector<uint8_t> to_cbor(const basic_json& j)
  13319. {
  13320. std::vector<uint8_t> result;
  13321. to_cbor(j, result);
  13322. return result;
  13323. }
  13324. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  13325. {
  13326. binary_writer<uint8_t>(o).write_cbor(j);
  13327. }
  13328. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  13329. {
  13330. binary_writer<char>(o).write_cbor(j);
  13331. }
  13332. /*!
  13333. @brief create a MessagePack serialization of a given JSON value
  13334. Serializes a given JSON value @a j to a byte vector using the MessagePack
  13335. serialization format. MessagePack is a binary serialization format which
  13336. aims to be more compact than JSON itself, yet more efficient to parse.
  13337. The library uses the following mapping from JSON values types to
  13338. MessagePack types according to the MessagePack specification:
  13339. JSON value type | value/range | MessagePack type | first byte
  13340. --------------- | --------------------------------- | ---------------- | ----------
  13341. null | `null` | nil | 0xC0
  13342. boolean | `true` | true | 0xC3
  13343. boolean | `false` | false | 0xC2
  13344. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  13345. number_integer | -2147483648..-32769 | int32 | 0xD2
  13346. number_integer | -32768..-129 | int16 | 0xD1
  13347. number_integer | -128..-33 | int8 | 0xD0
  13348. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  13349. number_integer | 0..127 | positive fixint | 0x00..0x7F
  13350. number_integer | 128..255 | uint 8 | 0xCC
  13351. number_integer | 256..65535 | uint 16 | 0xCD
  13352. number_integer | 65536..4294967295 | uint 32 | 0xCE
  13353. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  13354. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  13355. number_unsigned | 128..255 | uint 8 | 0xCC
  13356. number_unsigned | 256..65535 | uint 16 | 0xCD
  13357. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  13358. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  13359. number_float | *any value* | float 64 | 0xCB
  13360. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  13361. string | *length*: 32..255 | str 8 | 0xD9
  13362. string | *length*: 256..65535 | str 16 | 0xDA
  13363. string | *length*: 65536..4294967295 | str 32 | 0xDB
  13364. array | *size*: 0..15 | fixarray | 0x90..0x9F
  13365. array | *size*: 16..65535 | array 16 | 0xDC
  13366. array | *size*: 65536..4294967295 | array 32 | 0xDD
  13367. object | *size*: 0..15 | fix map | 0x80..0x8F
  13368. object | *size*: 16..65535 | map 16 | 0xDE
  13369. object | *size*: 65536..4294967295 | map 32 | 0xDF
  13370. @note The mapping is **complete** in the sense that any JSON value type
  13371. can be converted to a MessagePack value.
  13372. @note The following values can **not** be converted to a MessagePack value:
  13373. - strings with more than 4294967295 bytes
  13374. - arrays with more than 4294967295 elements
  13375. - objects with more than 4294967295 elements
  13376. @note The following MessagePack types are not used in the conversion:
  13377. - bin 8 - bin 32 (0xC4..0xC6)
  13378. - ext 8 - ext 32 (0xC7..0xC9)
  13379. - float 32 (0xCA)
  13380. - fixext 1 - fixext 16 (0xD4..0xD8)
  13381. @note Any MessagePack output created @ref to_msgpack can be successfully
  13382. parsed by @ref from_msgpack.
  13383. @note If NaN or Infinity are stored inside a JSON number, they are
  13384. serialized properly. This behavior differs from the @ref dump()
  13385. function which serializes NaN or Infinity to `null`.
  13386. @param[in] j JSON value to serialize
  13387. @return MessagePack serialization as byte vector
  13388. @complexity Linear in the size of the JSON value @a j.
  13389. @liveexample{The example shows the serialization of a JSON value to a byte
  13390. vector in MessagePack format.,to_msgpack}
  13391. @sa http://msgpack.org
  13392. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  13393. analogous deserialization
  13394. @sa @ref to_cbor(const basic_json& for the related CBOR format
  13395. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  13396. related UBJSON format
  13397. @since version 2.0.9
  13398. */
  13399. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  13400. {
  13401. std::vector<uint8_t> result;
  13402. to_msgpack(j, result);
  13403. return result;
  13404. }
  13405. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  13406. {
  13407. binary_writer<uint8_t>(o).write_msgpack(j);
  13408. }
  13409. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  13410. {
  13411. binary_writer<char>(o).write_msgpack(j);
  13412. }
  13413. /*!
  13414. @brief create a UBJSON serialization of a given JSON value
  13415. Serializes a given JSON value @a j to a byte vector using the UBJSON
  13416. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  13417. than JSON itself, yet more efficient to parse.
  13418. The library uses the following mapping from JSON values types to
  13419. UBJSON types according to the UBJSON specification:
  13420. JSON value type | value/range | UBJSON type | marker
  13421. --------------- | --------------------------------- | ----------- | ------
  13422. null | `null` | null | `Z`
  13423. boolean | `true` | true | `T`
  13424. boolean | `false` | false | `F`
  13425. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  13426. number_integer | -2147483648..-32769 | int32 | `l`
  13427. number_integer | -32768..-129 | int16 | `I`
  13428. number_integer | -128..127 | int8 | `i`
  13429. number_integer | 128..255 | uint8 | `U`
  13430. number_integer | 256..32767 | int16 | `I`
  13431. number_integer | 32768..2147483647 | int32 | `l`
  13432. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  13433. number_unsigned | 0..127 | int8 | `i`
  13434. number_unsigned | 128..255 | uint8 | `U`
  13435. number_unsigned | 256..32767 | int16 | `I`
  13436. number_unsigned | 32768..2147483647 | int32 | `l`
  13437. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  13438. number_float | *any value* | float64 | `D`
  13439. string | *with shortest length indicator* | string | `S`
  13440. array | *see notes on optimized format* | array | `[`
  13441. object | *see notes on optimized format* | map | `{`
  13442. @note The mapping is **complete** in the sense that any JSON value type
  13443. can be converted to a UBJSON value.
  13444. @note The following values can **not** be converted to a UBJSON value:
  13445. - strings with more than 9223372036854775807 bytes (theoretical)
  13446. - unsigned integer numbers above 9223372036854775807
  13447. @note The following markers are not used in the conversion:
  13448. - `Z`: no-op values are not created.
  13449. - `C`: single-byte strings are serialized with `S` markers.
  13450. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  13451. by @ref from_ubjson.
  13452. @note If NaN or Infinity are stored inside a JSON number, they are
  13453. serialized properly. This behavior differs from the @ref dump()
  13454. function which serializes NaN or Infinity to `null`.
  13455. @note The optimized formats for containers are supported: Parameter
  13456. @a use_size adds size information to the beginning of a container and
  13457. removes the closing marker. Parameter @a use_type further checks
  13458. whether all elements of a container have the same type and adds the
  13459. type marker to the beginning of the container. The @a use_type
  13460. parameter must only be used together with @a use_size = true. Note
  13461. that @a use_size = true alone may result in larger representations -
  13462. the benefit of this parameter is that the receiving side is
  13463. immediately informed on the number of elements of the container.
  13464. @param[in] j JSON value to serialize
  13465. @param[in] use_size whether to add size annotations to container types
  13466. @param[in] use_type whether to add type annotations to container types
  13467. (must be combined with @a use_size = true)
  13468. @return UBJSON serialization as byte vector
  13469. @complexity Linear in the size of the JSON value @a j.
  13470. @liveexample{The example shows the serialization of a JSON value to a byte
  13471. vector in UBJSON format.,to_ubjson}
  13472. @sa http://ubjson.org
  13473. @sa @ref from_ubjson(detail::input_adapter, const bool strict) for the
  13474. analogous deserialization
  13475. @sa @ref to_cbor(const basic_json& for the related CBOR format
  13476. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  13477. @since version 3.1.0
  13478. */
  13479. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  13480. const bool use_size = false,
  13481. const bool use_type = false)
  13482. {
  13483. std::vector<uint8_t> result;
  13484. to_ubjson(j, result, use_size, use_type);
  13485. return result;
  13486. }
  13487. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  13488. const bool use_size = false, const bool use_type = false)
  13489. {
  13490. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  13491. }
  13492. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  13493. const bool use_size = false, const bool use_type = false)
  13494. {
  13495. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  13496. }
  13497. /*!
  13498. @brief create a JSON value from an input in CBOR format
  13499. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  13500. Binary Object Representation) serialization format.
  13501. The library maps CBOR types to JSON value types as follows:
  13502. CBOR type | JSON value type | first byte
  13503. ---------------------- | --------------- | ----------
  13504. Integer | number_unsigned | 0x00..0x17
  13505. Unsigned integer | number_unsigned | 0x18
  13506. Unsigned integer | number_unsigned | 0x19
  13507. Unsigned integer | number_unsigned | 0x1A
  13508. Unsigned integer | number_unsigned | 0x1B
  13509. Negative integer | number_integer | 0x20..0x37
  13510. Negative integer | number_integer | 0x38
  13511. Negative integer | number_integer | 0x39
  13512. Negative integer | number_integer | 0x3A
  13513. Negative integer | number_integer | 0x3B
  13514. Negative integer | number_integer | 0x40..0x57
  13515. UTF-8 string | string | 0x60..0x77
  13516. UTF-8 string | string | 0x78
  13517. UTF-8 string | string | 0x79
  13518. UTF-8 string | string | 0x7A
  13519. UTF-8 string | string | 0x7B
  13520. UTF-8 string | string | 0x7F
  13521. array | array | 0x80..0x97
  13522. array | array | 0x98
  13523. array | array | 0x99
  13524. array | array | 0x9A
  13525. array | array | 0x9B
  13526. array | array | 0x9F
  13527. map | object | 0xA0..0xB7
  13528. map | object | 0xB8
  13529. map | object | 0xB9
  13530. map | object | 0xBA
  13531. map | object | 0xBB
  13532. map | object | 0xBF
  13533. False | `false` | 0xF4
  13534. True | `true` | 0xF5
  13535. Nill | `null` | 0xF6
  13536. Half-Precision Float | number_float | 0xF9
  13537. Single-Precision Float | number_float | 0xFA
  13538. Double-Precision Float | number_float | 0xFB
  13539. @warning The mapping is **incomplete** in the sense that not all CBOR
  13540. types can be converted to a JSON value. The following CBOR types
  13541. are not supported and will yield parse errors (parse_error.112):
  13542. - byte strings (0x40..0x5F)
  13543. - date/time (0xC0..0xC1)
  13544. - bignum (0xC2..0xC3)
  13545. - decimal fraction (0xC4)
  13546. - bigfloat (0xC5)
  13547. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  13548. - expected conversions (0xD5..0xD7)
  13549. - simple values (0xE0..0xF3, 0xF8)
  13550. - undefined (0xF7)
  13551. @warning CBOR allows map keys of any type, whereas JSON only allows
  13552. strings as keys in object values. Therefore, CBOR maps with keys
  13553. other than UTF-8 strings are rejected (parse_error.113).
  13554. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  13555. @ref from_cbor.
  13556. @param[in] i an input in CBOR format convertible to an input adapter
  13557. @param[in] strict whether to expect the input to be consumed until EOF
  13558. (true by default)
  13559. @return deserialized JSON value
  13560. @throw parse_error.110 if the given input ends prematurely or the end of
  13561. file was not reached when @a strict was set to true
  13562. @throw parse_error.112 if unsupported features from CBOR were
  13563. used in the given input @a v or if the input is not valid CBOR
  13564. @throw parse_error.113 if a string was expected as map key, but not found
  13565. @complexity Linear in the size of the input @a i.
  13566. @liveexample{The example shows the deserialization of a byte vector in CBOR
  13567. format to a JSON value.,from_cbor}
  13568. @sa http://cbor.io
  13569. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  13570. @sa @ref from_msgpack(detail::input_adapter, const bool) for the
  13571. related MessagePack format
  13572. @sa @ref from_ubjson(detail::input_adapter, const bool) for the related
  13573. UBJSON format
  13574. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  13575. consume input adapters, removed start_index parameter, and added
  13576. @a strict parameter since 3.0.0
  13577. */
  13578. static basic_json from_cbor(detail::input_adapter i,
  13579. const bool strict = true)
  13580. {
  13581. return binary_reader(i).parse_cbor(strict);
  13582. }
  13583. /*!
  13584. @copydoc from_cbor(detail::input_adapter, const bool)
  13585. */
  13586. template<typename A1, typename A2,
  13587. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  13588. static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
  13589. {
  13590. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
  13591. }
  13592. /*!
  13593. @brief create a JSON value from an input in MessagePack format
  13594. Deserializes a given input @a i to a JSON value using the MessagePack
  13595. serialization format.
  13596. The library maps MessagePack types to JSON value types as follows:
  13597. MessagePack type | JSON value type | first byte
  13598. ---------------- | --------------- | ----------
  13599. positive fixint | number_unsigned | 0x00..0x7F
  13600. fixmap | object | 0x80..0x8F
  13601. fixarray | array | 0x90..0x9F
  13602. fixstr | string | 0xA0..0xBF
  13603. nil | `null` | 0xC0
  13604. false | `false` | 0xC2
  13605. true | `true` | 0xC3
  13606. float 32 | number_float | 0xCA
  13607. float 64 | number_float | 0xCB
  13608. uint 8 | number_unsigned | 0xCC
  13609. uint 16 | number_unsigned | 0xCD
  13610. uint 32 | number_unsigned | 0xCE
  13611. uint 64 | number_unsigned | 0xCF
  13612. int 8 | number_integer | 0xD0
  13613. int 16 | number_integer | 0xD1
  13614. int 32 | number_integer | 0xD2
  13615. int 64 | number_integer | 0xD3
  13616. str 8 | string | 0xD9
  13617. str 16 | string | 0xDA
  13618. str 32 | string | 0xDB
  13619. array 16 | array | 0xDC
  13620. array 32 | array | 0xDD
  13621. map 16 | object | 0xDE
  13622. map 32 | object | 0xDF
  13623. negative fixint | number_integer | 0xE0-0xFF
  13624. @warning The mapping is **incomplete** in the sense that not all
  13625. MessagePack types can be converted to a JSON value. The following
  13626. MessagePack types are not supported and will yield parse errors:
  13627. - bin 8 - bin 32 (0xC4..0xC6)
  13628. - ext 8 - ext 32 (0xC7..0xC9)
  13629. - fixext 1 - fixext 16 (0xD4..0xD8)
  13630. @note Any MessagePack output created @ref to_msgpack can be successfully
  13631. parsed by @ref from_msgpack.
  13632. @param[in] i an input in MessagePack format convertible to an input
  13633. adapter
  13634. @param[in] strict whether to expect the input to be consumed until EOF
  13635. (true by default)
  13636. @throw parse_error.110 if the given input ends prematurely or the end of
  13637. file was not reached when @a strict was set to true
  13638. @throw parse_error.112 if unsupported features from MessagePack were
  13639. used in the given input @a i or if the input is not valid MessagePack
  13640. @throw parse_error.113 if a string was expected as map key, but not found
  13641. @complexity Linear in the size of the input @a i.
  13642. @liveexample{The example shows the deserialization of a byte vector in
  13643. MessagePack format to a JSON value.,from_msgpack}
  13644. @sa http://msgpack.org
  13645. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  13646. @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
  13647. format
  13648. @sa @ref from_ubjson(detail::input_adapter, const bool) for the related
  13649. UBJSON format
  13650. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  13651. consume input adapters, removed start_index parameter, and added
  13652. @a strict parameter since 3.0.0
  13653. */
  13654. static basic_json from_msgpack(detail::input_adapter i,
  13655. const bool strict = true)
  13656. {
  13657. return binary_reader(i).parse_msgpack(strict);
  13658. }
  13659. /*!
  13660. @copydoc from_msgpack(detail::input_adapter, const bool)
  13661. */
  13662. template<typename A1, typename A2,
  13663. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  13664. static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
  13665. {
  13666. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
  13667. }
  13668. /*!
  13669. @brief create a JSON value from an input in UBJSON format
  13670. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  13671. Binary JSON) serialization format.
  13672. The library maps UBJSON types to JSON value types as follows:
  13673. UBJSON type | JSON value type | marker
  13674. ----------- | --------------------------------------- | ------
  13675. no-op | *no value, next value is read* | `N`
  13676. null | `null` | `Z`
  13677. false | `false` | `F`
  13678. true | `true` | `T`
  13679. float32 | number_float | `d`
  13680. float64 | number_float | `D`
  13681. uint8 | number_unsigned | `U`
  13682. int8 | number_integer | `i`
  13683. int16 | number_integer | `I`
  13684. int32 | number_integer | `l`
  13685. int64 | number_integer | `L`
  13686. string | string | `S`
  13687. char | string | `C`
  13688. array | array (optimized values are supported) | `[`
  13689. object | object (optimized values are supported) | `{`
  13690. @note The mapping is **complete** in the sense that any UBJSON value can
  13691. be converted to a JSON value.
  13692. @param[in] i an input in UBJSON format convertible to an input adapter
  13693. @param[in] strict whether to expect the input to be consumed until EOF
  13694. (true by default)
  13695. @throw parse_error.110 if the given input ends prematurely or the end of
  13696. file was not reached when @a strict was set to true
  13697. @throw parse_error.112 if a parse error occurs
  13698. @throw parse_error.113 if a string could not be parsed successfully
  13699. @complexity Linear in the size of the input @a i.
  13700. @liveexample{The example shows the deserialization of a byte vector in
  13701. UBJSON format to a JSON value.,from_ubjson}
  13702. @sa http://ubjson.org
  13703. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  13704. analogous serialization
  13705. @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
  13706. format
  13707. @sa @ref from_msgpack(detail::input_adapter, const bool) for the related
  13708. MessagePack format
  13709. @since version 3.1.0
  13710. */
  13711. static basic_json from_ubjson(detail::input_adapter i,
  13712. const bool strict = true)
  13713. {
  13714. return binary_reader(i).parse_ubjson(strict);
  13715. }
  13716. template<typename A1, typename A2,
  13717. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  13718. static basic_json from_ubjson(A1 && a1, A2 && a2, const bool strict = true)
  13719. {
  13720. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_ubjson(strict);
  13721. }
  13722. /// @}
  13723. //////////////////////////
  13724. // JSON Pointer support //
  13725. //////////////////////////
  13726. /// @name JSON Pointer functions
  13727. /// @{
  13728. /*!
  13729. @brief access specified element via JSON Pointer
  13730. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  13731. No bound checking is performed. Similar to @ref operator[](const typename
  13732. object_t::key_type&), `null` values are created in arrays and objects if
  13733. necessary.
  13734. In particular:
  13735. - If the JSON pointer points to an object key that does not exist, it
  13736. is created an filled with a `null` value before a reference to it
  13737. is returned.
  13738. - If the JSON pointer points to an array index that does not exist, it
  13739. is created an filled with a `null` value before a reference to it
  13740. is returned. All indices between the current maximum and the given
  13741. index are also filled with `null`.
  13742. - The special value `-` is treated as a synonym for the index past the
  13743. end.
  13744. @param[in] ptr a JSON pointer
  13745. @return reference to the element pointed to by @a ptr
  13746. @complexity Constant.
  13747. @throw parse_error.106 if an array index begins with '0'
  13748. @throw parse_error.109 if an array index was not a number
  13749. @throw out_of_range.404 if the JSON pointer can not be resolved
  13750. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  13751. @since version 2.0.0
  13752. */
  13753. reference operator[](const json_pointer& ptr)
  13754. {
  13755. return ptr.get_unchecked(this);
  13756. }
  13757. /*!
  13758. @brief access specified element via JSON Pointer
  13759. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  13760. No bound checking is performed. The function does not change the JSON
  13761. value; no `null` values are created. In particular, the the special value
  13762. `-` yields an exception.
  13763. @param[in] ptr JSON pointer to the desired element
  13764. @return const reference to the element pointed to by @a ptr
  13765. @complexity Constant.
  13766. @throw parse_error.106 if an array index begins with '0'
  13767. @throw parse_error.109 if an array index was not a number
  13768. @throw out_of_range.402 if the array index '-' is used
  13769. @throw out_of_range.404 if the JSON pointer can not be resolved
  13770. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  13771. @since version 2.0.0
  13772. */
  13773. const_reference operator[](const json_pointer& ptr) const
  13774. {
  13775. return ptr.get_unchecked(this);
  13776. }
  13777. /*!
  13778. @brief access specified element via JSON Pointer
  13779. Returns a reference to the element at with specified JSON pointer @a ptr,
  13780. with bounds checking.
  13781. @param[in] ptr JSON pointer to the desired element
  13782. @return reference to the element pointed to by @a ptr
  13783. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  13784. begins with '0'. See example below.
  13785. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  13786. is not a number. See example below.
  13787. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  13788. is out of range. See example below.
  13789. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  13790. pointer @a ptr. As `at` provides checked access (and no elements are
  13791. implicitly inserted), the index '-' is always invalid. See example below.
  13792. @throw out_of_range.403 if the JSON pointer describes a key of an object
  13793. which cannot be found. See example below.
  13794. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  13795. See example below.
  13796. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13797. changes in the JSON value.
  13798. @complexity Constant.
  13799. @since version 2.0.0
  13800. @liveexample{The behavior is shown in the example.,at_json_pointer}
  13801. */
  13802. reference at(const json_pointer& ptr)
  13803. {
  13804. return ptr.get_checked(this);
  13805. }
  13806. /*!
  13807. @brief access specified element via JSON Pointer
  13808. Returns a const reference to the element at with specified JSON pointer @a
  13809. ptr, with bounds checking.
  13810. @param[in] ptr JSON pointer to the desired element
  13811. @return reference to the element pointed to by @a ptr
  13812. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  13813. begins with '0'. See example below.
  13814. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  13815. is not a number. See example below.
  13816. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  13817. is out of range. See example below.
  13818. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  13819. pointer @a ptr. As `at` provides checked access (and no elements are
  13820. implicitly inserted), the index '-' is always invalid. See example below.
  13821. @throw out_of_range.403 if the JSON pointer describes a key of an object
  13822. which cannot be found. See example below.
  13823. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  13824. See example below.
  13825. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13826. changes in the JSON value.
  13827. @complexity Constant.
  13828. @since version 2.0.0
  13829. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  13830. */
  13831. const_reference at(const json_pointer& ptr) const
  13832. {
  13833. return ptr.get_checked(this);
  13834. }
  13835. /*!
  13836. @brief return flattened JSON value
  13837. The function creates a JSON object whose keys are JSON pointers (see [RFC
  13838. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  13839. primitive. The original JSON value can be restored using the @ref
  13840. unflatten() function.
  13841. @return an object that maps JSON pointers to primitive values
  13842. @note Empty objects and arrays are flattened to `null` and will not be
  13843. reconstructed correctly by the @ref unflatten() function.
  13844. @complexity Linear in the size the JSON value.
  13845. @liveexample{The following code shows how a JSON object is flattened to an
  13846. object whose keys consist of JSON pointers.,flatten}
  13847. @sa @ref unflatten() for the reverse function
  13848. @since version 2.0.0
  13849. */
  13850. basic_json flatten() const
  13851. {
  13852. basic_json result(value_t::object);
  13853. json_pointer::flatten("", *this, result);
  13854. return result;
  13855. }
  13856. /*!
  13857. @brief unflatten a previously flattened JSON value
  13858. The function restores the arbitrary nesting of a JSON value that has been
  13859. flattened before using the @ref flatten() function. The JSON value must
  13860. meet certain constraints:
  13861. 1. The value must be an object.
  13862. 2. The keys must be JSON pointers (see
  13863. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  13864. 3. The mapped values must be primitive JSON types.
  13865. @return the original JSON from a flattened version
  13866. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  13867. values and can not unflattened to their original type. Apart from
  13868. this example, for a JSON value `j`, the following is always true:
  13869. `j == j.flatten().unflatten()`.
  13870. @complexity Linear in the size the JSON value.
  13871. @throw type_error.314 if value is not an object
  13872. @throw type_error.315 if object values are not primitive
  13873. @liveexample{The following code shows how a flattened JSON object is
  13874. unflattened into the original nested JSON object.,unflatten}
  13875. @sa @ref flatten() for the reverse function
  13876. @since version 2.0.0
  13877. */
  13878. basic_json unflatten() const
  13879. {
  13880. return json_pointer::unflatten(*this);
  13881. }
  13882. /// @}
  13883. //////////////////////////
  13884. // JSON Patch functions //
  13885. //////////////////////////
  13886. /// @name JSON Patch functions
  13887. /// @{
  13888. /*!
  13889. @brief applies a JSON patch
  13890. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  13891. expressing a sequence of operations to apply to a JSON) document. With
  13892. this function, a JSON Patch is applied to the current JSON value by
  13893. executing all operations from the patch.
  13894. @param[in] json_patch JSON patch document
  13895. @return patched document
  13896. @note The application of a patch is atomic: Either all operations succeed
  13897. and the patched document is returned or an exception is thrown. In
  13898. any case, the original value is not changed: the patch is applied
  13899. to a copy of the value.
  13900. @throw parse_error.104 if the JSON patch does not consist of an array of
  13901. objects
  13902. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  13903. attributes are missing); example: `"operation add must have member path"`
  13904. @throw out_of_range.401 if an array index is out of range.
  13905. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  13906. resolved successfully in the current JSON value; example: `"key baz not
  13907. found"`
  13908. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  13909. "move")
  13910. @throw other_error.501 if "test" operation was unsuccessful
  13911. @complexity Linear in the size of the JSON value and the length of the
  13912. JSON patch. As usually only a fraction of the JSON value is affected by
  13913. the patch, the complexity can usually be neglected.
  13914. @liveexample{The following code shows how a JSON patch is applied to a
  13915. value.,patch}
  13916. @sa @ref diff -- create a JSON patch by comparing two JSON values
  13917. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  13918. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  13919. @since version 2.0.0
  13920. */
  13921. basic_json patch(const basic_json& json_patch) const
  13922. {
  13923. // make a working copy to apply the patch to
  13924. basic_json result = *this;
  13925. // the valid JSON Patch operations
  13926. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  13927. const auto get_op = [](const std::string & op)
  13928. {
  13929. if (op == "add")
  13930. {
  13931. return patch_operations::add;
  13932. }
  13933. if (op == "remove")
  13934. {
  13935. return patch_operations::remove;
  13936. }
  13937. if (op == "replace")
  13938. {
  13939. return patch_operations::replace;
  13940. }
  13941. if (op == "move")
  13942. {
  13943. return patch_operations::move;
  13944. }
  13945. if (op == "copy")
  13946. {
  13947. return patch_operations::copy;
  13948. }
  13949. if (op == "test")
  13950. {
  13951. return patch_operations::test;
  13952. }
  13953. return patch_operations::invalid;
  13954. };
  13955. // wrapper for "add" operation; add value at ptr
  13956. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  13957. {
  13958. // adding to the root of the target document means replacing it
  13959. if (ptr.is_root())
  13960. {
  13961. result = val;
  13962. }
  13963. else
  13964. {
  13965. // make sure the top element of the pointer exists
  13966. json_pointer top_pointer = ptr.top();
  13967. if (top_pointer != ptr)
  13968. {
  13969. result.at(top_pointer);
  13970. }
  13971. // get reference to parent of JSON pointer ptr
  13972. const auto last_path = ptr.pop_back();
  13973. basic_json& parent = result[ptr];
  13974. switch (parent.m_type)
  13975. {
  13976. case value_t::null:
  13977. case value_t::object:
  13978. {
  13979. // use operator[] to add value
  13980. parent[last_path] = val;
  13981. break;
  13982. }
  13983. case value_t::array:
  13984. {
  13985. if (last_path == "-")
  13986. {
  13987. // special case: append to back
  13988. parent.push_back(val);
  13989. }
  13990. else
  13991. {
  13992. const auto idx = json_pointer::array_index(last_path);
  13993. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  13994. {
  13995. // avoid undefined behavior
  13996. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13997. }
  13998. else
  13999. {
  14000. // default case: insert add offset
  14001. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  14002. }
  14003. }
  14004. break;
  14005. }
  14006. default:
  14007. {
  14008. // if there exists a parent it cannot be primitive
  14009. assert(false); // LCOV_EXCL_LINE
  14010. }
  14011. }
  14012. }
  14013. };
  14014. // wrapper for "remove" operation; remove value at ptr
  14015. const auto operation_remove = [&result](json_pointer & ptr)
  14016. {
  14017. // get reference to parent of JSON pointer ptr
  14018. const auto last_path = ptr.pop_back();
  14019. basic_json& parent = result.at(ptr);
  14020. // remove child
  14021. if (parent.is_object())
  14022. {
  14023. // perform range check
  14024. auto it = parent.find(last_path);
  14025. if (JSON_LIKELY(it != parent.end()))
  14026. {
  14027. parent.erase(it);
  14028. }
  14029. else
  14030. {
  14031. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  14032. }
  14033. }
  14034. else if (parent.is_array())
  14035. {
  14036. // note erase performs range check
  14037. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  14038. }
  14039. };
  14040. // type check: top level value must be an array
  14041. if (JSON_UNLIKELY(not json_patch.is_array()))
  14042. {
  14043. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  14044. }
  14045. // iterate and apply the operations
  14046. for (const auto& val : json_patch)
  14047. {
  14048. // wrapper to get a value for an operation
  14049. const auto get_value = [&val](const std::string & op,
  14050. const std::string & member,
  14051. bool string_type) -> basic_json &
  14052. {
  14053. // find value
  14054. auto it = val.m_value.object->find(member);
  14055. // context-sensitive error message
  14056. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  14057. // check if desired value is present
  14058. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  14059. {
  14060. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  14061. }
  14062. // check if result is of type string
  14063. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  14064. {
  14065. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  14066. }
  14067. // no error: return value
  14068. return it->second;
  14069. };
  14070. // type check: every element of the array must be an object
  14071. if (JSON_UNLIKELY(not val.is_object()))
  14072. {
  14073. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  14074. }
  14075. // collect mandatory members
  14076. const std::string op = get_value("op", "op", true);
  14077. const std::string path = get_value(op, "path", true);
  14078. json_pointer ptr(path);
  14079. switch (get_op(op))
  14080. {
  14081. case patch_operations::add:
  14082. {
  14083. operation_add(ptr, get_value("add", "value", false));
  14084. break;
  14085. }
  14086. case patch_operations::remove:
  14087. {
  14088. operation_remove(ptr);
  14089. break;
  14090. }
  14091. case patch_operations::replace:
  14092. {
  14093. // the "path" location must exist - use at()
  14094. result.at(ptr) = get_value("replace", "value", false);
  14095. break;
  14096. }
  14097. case patch_operations::move:
  14098. {
  14099. const std::string from_path = get_value("move", "from", true);
  14100. json_pointer from_ptr(from_path);
  14101. // the "from" location must exist - use at()
  14102. basic_json v = result.at(from_ptr);
  14103. // The move operation is functionally identical to a
  14104. // "remove" operation on the "from" location, followed
  14105. // immediately by an "add" operation at the target
  14106. // location with the value that was just removed.
  14107. operation_remove(from_ptr);
  14108. operation_add(ptr, v);
  14109. break;
  14110. }
  14111. case patch_operations::copy:
  14112. {
  14113. const std::string from_path = get_value("copy", "from", true);
  14114. const json_pointer from_ptr(from_path);
  14115. // the "from" location must exist - use at()
  14116. basic_json v = result.at(from_ptr);
  14117. // The copy is functionally identical to an "add"
  14118. // operation at the target location using the value
  14119. // specified in the "from" member.
  14120. operation_add(ptr, v);
  14121. break;
  14122. }
  14123. case patch_operations::test:
  14124. {
  14125. bool success = false;
  14126. JSON_TRY
  14127. {
  14128. // check if "value" matches the one at "path"
  14129. // the "path" location must exist - use at()
  14130. success = (result.at(ptr) == get_value("test", "value", false));
  14131. }
  14132. JSON_CATCH (out_of_range&)
  14133. {
  14134. // ignore out of range errors: success remains false
  14135. }
  14136. // throw an exception if test fails
  14137. if (JSON_UNLIKELY(not success))
  14138. {
  14139. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  14140. }
  14141. break;
  14142. }
  14143. case patch_operations::invalid:
  14144. {
  14145. // op must be "add", "remove", "replace", "move", "copy", or
  14146. // "test"
  14147. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  14148. }
  14149. }
  14150. }
  14151. return result;
  14152. }
  14153. /*!
  14154. @brief creates a diff as a JSON patch
  14155. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  14156. be changed into the value @a target by calling @ref patch function.
  14157. @invariant For two JSON values @a source and @a target, the following code
  14158. yields always `true`:
  14159. @code {.cpp}
  14160. source.patch(diff(source, target)) == target;
  14161. @endcode
  14162. @note Currently, only `remove`, `add`, and `replace` operations are
  14163. generated.
  14164. @param[in] source JSON value to compare from
  14165. @param[in] target JSON value to compare against
  14166. @param[in] path helper value to create JSON pointers
  14167. @return a JSON patch to convert the @a source to @a target
  14168. @complexity Linear in the lengths of @a source and @a target.
  14169. @liveexample{The following code shows how a JSON patch is created as a
  14170. diff for two JSON values.,diff}
  14171. @sa @ref patch -- apply a JSON patch
  14172. @sa @ref merge_patch -- apply a JSON Merge Patch
  14173. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  14174. @since version 2.0.0
  14175. */
  14176. static basic_json diff(const basic_json& source, const basic_json& target,
  14177. const std::string& path = "")
  14178. {
  14179. // the patch
  14180. basic_json result(value_t::array);
  14181. // if the values are the same, return empty patch
  14182. if (source == target)
  14183. {
  14184. return result;
  14185. }
  14186. if (source.type() != target.type())
  14187. {
  14188. // different types: replace value
  14189. result.push_back(
  14190. {
  14191. {"op", "replace"}, {"path", path}, {"value", target}
  14192. });
  14193. }
  14194. else
  14195. {
  14196. switch (source.type())
  14197. {
  14198. case value_t::array:
  14199. {
  14200. // first pass: traverse common elements
  14201. std::size_t i = 0;
  14202. while (i < source.size() and i < target.size())
  14203. {
  14204. // recursive call to compare array values at index i
  14205. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  14206. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  14207. ++i;
  14208. }
  14209. // i now reached the end of at least one array
  14210. // in a second pass, traverse the remaining elements
  14211. // remove my remaining elements
  14212. const auto end_index = static_cast<difference_type>(result.size());
  14213. while (i < source.size())
  14214. {
  14215. // add operations in reverse order to avoid invalid
  14216. // indices
  14217. result.insert(result.begin() + end_index, object(
  14218. {
  14219. {"op", "remove"},
  14220. {"path", path + "/" + std::to_string(i)}
  14221. }));
  14222. ++i;
  14223. }
  14224. // add other remaining elements
  14225. while (i < target.size())
  14226. {
  14227. result.push_back(
  14228. {
  14229. {"op", "add"},
  14230. {"path", path + "/" + std::to_string(i)},
  14231. {"value", target[i]}
  14232. });
  14233. ++i;
  14234. }
  14235. break;
  14236. }
  14237. case value_t::object:
  14238. {
  14239. // first pass: traverse this object's elements
  14240. for (auto it = source.cbegin(); it != source.cend(); ++it)
  14241. {
  14242. // escape the key name to be used in a JSON patch
  14243. const auto key = json_pointer::escape(it.key());
  14244. if (target.find(it.key()) != target.end())
  14245. {
  14246. // recursive call to compare object values at key it
  14247. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  14248. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  14249. }
  14250. else
  14251. {
  14252. // found a key that is not in o -> remove it
  14253. result.push_back(object(
  14254. {
  14255. {"op", "remove"}, {"path", path + "/" + key}
  14256. }));
  14257. }
  14258. }
  14259. // second pass: traverse other object's elements
  14260. for (auto it = target.cbegin(); it != target.cend(); ++it)
  14261. {
  14262. if (source.find(it.key()) == source.end())
  14263. {
  14264. // found a key that is not in this -> add it
  14265. const auto key = json_pointer::escape(it.key());
  14266. result.push_back(
  14267. {
  14268. {"op", "add"}, {"path", path + "/" + key},
  14269. {"value", it.value()}
  14270. });
  14271. }
  14272. }
  14273. break;
  14274. }
  14275. default:
  14276. {
  14277. // both primitive type: replace value
  14278. result.push_back(
  14279. {
  14280. {"op", "replace"}, {"path", path}, {"value", target}
  14281. });
  14282. break;
  14283. }
  14284. }
  14285. }
  14286. return result;
  14287. }
  14288. /// @}
  14289. ////////////////////////////////
  14290. // JSON Merge Patch functions //
  14291. ////////////////////////////////
  14292. /// @name JSON Merge Patch functions
  14293. /// @{
  14294. /*!
  14295. @brief applies a JSON Merge Patch
  14296. The merge patch format is primarily intended for use with the HTTP PATCH
  14297. method as a means of describing a set of modifications to a target
  14298. resource's content. This function applies a merge patch to the current
  14299. JSON value.
  14300. The function implements the following algorithm from Section 2 of
  14301. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  14302. ```
  14303. define MergePatch(Target, Patch):
  14304. if Patch is an Object:
  14305. if Target is not an Object:
  14306. Target = {} // Ignore the contents and set it to an empty Object
  14307. for each Name/Value pair in Patch:
  14308. if Value is null:
  14309. if Name exists in Target:
  14310. remove the Name/Value pair from Target
  14311. else:
  14312. Target[Name] = MergePatch(Target[Name], Value)
  14313. return Target
  14314. else:
  14315. return Patch
  14316. ```
  14317. Thereby, `Target` is the current object; that is, the patch is applied to
  14318. the current value.
  14319. @param[in] patch the patch to apply
  14320. @complexity Linear in the lengths of @a patch.
  14321. @liveexample{The following code shows how a JSON Merge Patch is applied to
  14322. a JSON document.,merge_patch}
  14323. @sa @ref patch -- apply a JSON patch
  14324. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  14325. @since version 3.0.0
  14326. */
  14327. void merge_patch(const basic_json& patch)
  14328. {
  14329. if (patch.is_object())
  14330. {
  14331. if (not is_object())
  14332. {
  14333. *this = object();
  14334. }
  14335. for (auto it = patch.begin(); it != patch.end(); ++it)
  14336. {
  14337. if (it.value().is_null())
  14338. {
  14339. erase(it.key());
  14340. }
  14341. else
  14342. {
  14343. operator[](it.key()).merge_patch(it.value());
  14344. }
  14345. }
  14346. }
  14347. else
  14348. {
  14349. *this = patch;
  14350. }
  14351. }
  14352. /// @}
  14353. };
  14354. } // namespace nlohmann
  14355. ///////////////////////
  14356. // nonmember support //
  14357. ///////////////////////
  14358. // specialization of std::swap, and std::hash
  14359. namespace std
  14360. {
  14361. /*!
  14362. @brief exchanges the values of two JSON objects
  14363. @since version 1.0.0
  14364. */
  14365. template<>
  14366. inline void swap(nlohmann::json& j1,
  14367. nlohmann::json& j2) noexcept(
  14368. is_nothrow_move_constructible<nlohmann::json>::value and
  14369. is_nothrow_move_assignable<nlohmann::json>::value
  14370. )
  14371. {
  14372. j1.swap(j2);
  14373. }
  14374. /// hash value for JSON objects
  14375. template<>
  14376. struct hash<nlohmann::json>
  14377. {
  14378. /*!
  14379. @brief return a hash value for a JSON object
  14380. @since version 1.0.0
  14381. */
  14382. std::size_t operator()(const nlohmann::json& j) const
  14383. {
  14384. // a naive hashing via the string representation
  14385. const auto& h = hash<nlohmann::json::string_t>();
  14386. return h(j.dump());
  14387. }
  14388. };
  14389. /// specialization for std::less<value_t>
  14390. /// @note: do not remove the space after '<',
  14391. /// see https://github.com/nlohmann/json/pull/679
  14392. template<>
  14393. struct less< ::nlohmann::detail::value_t>
  14394. {
  14395. /*!
  14396. @brief compare two value_t enum values
  14397. @since version 3.0.0
  14398. */
  14399. bool operator()(nlohmann::detail::value_t lhs,
  14400. nlohmann::detail::value_t rhs) const noexcept
  14401. {
  14402. return nlohmann::detail::operator<(lhs, rhs);
  14403. }
  14404. };
  14405. } // namespace std
  14406. /*!
  14407. @brief user-defined string literal for JSON values
  14408. This operator implements a user-defined string literal for JSON objects. It
  14409. can be used by adding `"_json"` to a string literal and returns a JSON object
  14410. if no parse error occurred.
  14411. @param[in] s a string representation of a JSON object
  14412. @param[in] n the length of string @a s
  14413. @return a JSON object
  14414. @since version 1.0.0
  14415. */
  14416. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  14417. {
  14418. return nlohmann::json::parse(s, s + n);
  14419. }
  14420. /*!
  14421. @brief user-defined string literal for JSON pointer
  14422. This operator implements a user-defined string literal for JSON Pointers. It
  14423. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  14424. object if no parse error occurred.
  14425. @param[in] s a string representation of a JSON Pointer
  14426. @param[in] n the length of string @a s
  14427. @return a JSON pointer object
  14428. @since version 2.0.0
  14429. */
  14430. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  14431. {
  14432. return nlohmann::json::json_pointer(std::string(s, n));
  14433. }
  14434. // #include <nlohmann/detail/macro_unscope.hpp>
  14435. // restore GCC/clang diagnostic settings
  14436. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  14437. #pragma GCC diagnostic pop
  14438. #endif
  14439. #if defined(__clang__)
  14440. #pragma GCC diagnostic pop
  14441. #endif
  14442. // clean up
  14443. #undef JSON_CATCH
  14444. #undef JSON_THROW
  14445. #undef JSON_TRY
  14446. #undef JSON_LIKELY
  14447. #undef JSON_UNLIKELY
  14448. #undef JSON_DEPRECATED
  14449. #undef JSON_HAS_CPP_14
  14450. #undef JSON_HAS_CPP_17
  14451. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  14452. #undef NLOHMANN_BASIC_JSON_TPL
  14453. #undef NLOHMANN_JSON_HAS_HELPER
  14454. #endif