json.hpp 496 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 2.1.1
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. Copyright (c) 2013-2017 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. #include <algorithm> // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform
  27. #include <array> // array
  28. #include <cassert> // assert
  29. #include <ciso646> // and, not, or
  30. #include <clocale> // lconv, localeconv
  31. #include <cmath> // isfinite, labs, ldexp, signbit
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <cstdint> // int64_t, uint64_t
  34. #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
  35. #include <cstring> // memcpy, strlen
  36. #include <forward_list> // forward_list
  37. #include <functional> // function, hash, less
  38. #include <initializer_list> // initializer_list
  39. #include <iomanip> // hex
  40. #include <iosfwd> // istream, ostream
  41. #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
  42. #include <limits> // numeric_limits
  43. #include <locale> // locale
  44. #include <map> // map
  45. #include <memory> // addressof, allocator, allocator_traits, unique_ptr
  46. #include <numeric> // accumulate
  47. #include <sstream> // stringstream
  48. #include <string> // getline, stoi, string, to_string
  49. #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
  50. #include <utility> // declval, forward, make_pair, move, pair, swap
  51. #include <vector> // vector
  52. // exclude unsupported compilers
  53. #if defined(__clang__)
  54. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  55. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  56. #endif
  57. #elif defined(__GNUC__)
  58. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
  59. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  60. #endif
  61. #endif
  62. // disable float-equal warnings on GCC/clang
  63. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  64. #pragma GCC diagnostic push
  65. #pragma GCC diagnostic ignored "-Wfloat-equal"
  66. #endif
  67. // disable documentation warnings on clang
  68. #if defined(__clang__)
  69. #pragma GCC diagnostic push
  70. #pragma GCC diagnostic ignored "-Wdocumentation"
  71. #endif
  72. // allow for portable deprecation warnings
  73. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  74. #define JSON_DEPRECATED __attribute__((deprecated))
  75. #elif defined(_MSC_VER)
  76. #define JSON_DEPRECATED __declspec(deprecated)
  77. #else
  78. #define JSON_DEPRECATED
  79. #endif
  80. // allow to disable exceptions
  81. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)
  82. #define JSON_THROW(exception) throw exception
  83. #define JSON_TRY try
  84. #define JSON_CATCH(exception) catch(exception)
  85. #else
  86. #define JSON_THROW(exception) std::abort()
  87. #define JSON_TRY if(true)
  88. #define JSON_CATCH(exception) if(false)
  89. #endif
  90. // manual branch prediction
  91. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  92. #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
  93. #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
  94. #else
  95. #define JSON_LIKELY(x) x
  96. #define JSON_UNLIKELY(x) x
  97. #endif
  98. /*!
  99. @brief namespace for Niels Lohmann
  100. @see https://github.com/nlohmann
  101. @since version 1.0.0
  102. */
  103. namespace nlohmann
  104. {
  105. /*!
  106. @brief unnamed namespace with internal helper functions
  107. This namespace collects some functions that could not be defined inside the
  108. @ref basic_json class.
  109. @since version 2.1.0
  110. */
  111. namespace detail
  112. {
  113. ////////////////
  114. // exceptions //
  115. ////////////////
  116. /*!
  117. @brief general exception of the @ref basic_json class
  118. Extension of std::exception objects with a member @a id for exception ids.
  119. @note To have nothrow-copy-constructible exceptions, we internally use
  120. std::runtime_error which can cope with arbitrary-length error messages.
  121. Intermediate strings are built with static functions and then passed to
  122. the actual constructor.
  123. @since version 3.0.0
  124. */
  125. class exception : public std::exception
  126. {
  127. public:
  128. /// returns the explanatory string
  129. virtual const char* what() const noexcept override
  130. {
  131. return m.what();
  132. }
  133. /// the id of the exception
  134. const int id;
  135. protected:
  136. exception(int id_, const char* what_arg)
  137. : id(id_), m(what_arg)
  138. {}
  139. static std::string name(const std::string& ename, int id)
  140. {
  141. return "[json.exception." + ename + "." + std::to_string(id) + "] ";
  142. }
  143. private:
  144. /// an exception object as storage for error messages
  145. std::runtime_error m;
  146. };
  147. /*!
  148. @brief exception indicating a parse error
  149. This excpetion is thrown by the library when a parse error occurs. Parse
  150. errors can occur during the deserialization of JSON text as well as when
  151. using JSON Patch.
  152. Member @a byte holds the byte index of the last read character in the input
  153. file.
  154. @note For an input with n bytes, 1 is the index of the first character
  155. and n+1 is the index of the terminating null byte or the end of
  156. file. This also holds true when reading a byte vector (CBOR or
  157. MessagePack).
  158. Exceptions have ids 1xx.
  159. name / id | example massage | description
  160. ------------------------------ | --------------- | -------------------------
  161. 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.
  162. 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.
  163. 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.
  164. 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.
  165. 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.
  166. 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 wihtout a leading `0`.
  167. 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.
  168. 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.
  169. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  170. 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.
  171. 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.
  172. 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.
  173. @since version 3.0.0
  174. */
  175. class parse_error : public exception
  176. {
  177. public:
  178. /*!
  179. @brief create a parse error exception
  180. @param[in] id the id of the exception
  181. @param[in] byte_ the byte index where the error occurred (or 0 if
  182. the position cannot be determined)
  183. @param[in] what_arg the explanatory string
  184. @return parse_error object
  185. */
  186. static parse_error create(int id, size_t byte_, const std::string& what_arg)
  187. {
  188. std::string w = exception::name("parse_error", id) + "parse error" +
  189. (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
  190. ": " + what_arg;
  191. return parse_error(id, byte_, w.c_str());
  192. }
  193. /*!
  194. @brief byte index of the parse error
  195. The byte index of the last read character in the input file.
  196. @note For an input with n bytes, 1 is the index of the first character
  197. and n+1 is the index of the terminating null byte or the end of
  198. file. This also holds true when reading a byte vector (CBOR or
  199. MessagePack).
  200. */
  201. const size_t byte;
  202. private:
  203. parse_error(int id_, size_t byte_, const char* what_arg)
  204. : exception(id_, what_arg), byte(byte_)
  205. {}
  206. };
  207. /*!
  208. @brief exception indicating errors with iterators
  209. Exceptions have ids 2xx.
  210. name / id | example massage | description
  211. ----------------------------------- | --------------- | -------------------------
  212. 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.
  213. 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.
  214. 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.
  215. 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.
  216. 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.
  217. 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.
  218. 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.
  219. 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.
  220. 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.
  221. 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.
  222. 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.
  223. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  224. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  225. 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().
  226. @since version 3.0.0
  227. */
  228. class invalid_iterator : public exception
  229. {
  230. public:
  231. static invalid_iterator create(int id, const std::string& what_arg)
  232. {
  233. std::string w = exception::name("invalid_iterator", id) + what_arg;
  234. return invalid_iterator(id, w.c_str());
  235. }
  236. private:
  237. invalid_iterator(int id_, const char* what_arg)
  238. : exception(id_, what_arg)
  239. {}
  240. };
  241. /*!
  242. @brief exception indicating executing a member function with a wrong type
  243. Exceptions have ids 3xx.
  244. name / id | example message | description
  245. ----------------------------- | --------------- | -------------------------
  246. 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.
  247. 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.
  248. 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&.
  249. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  250. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  251. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  252. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  253. 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.
  254. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  255. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  256. 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.
  257. 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.
  258. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  259. 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.
  260. @since version 3.0.0
  261. */
  262. class type_error : public exception
  263. {
  264. public:
  265. static type_error create(int id, const std::string& what_arg)
  266. {
  267. std::string w = exception::name("type_error", id) + what_arg;
  268. return type_error(id, w.c_str());
  269. }
  270. private:
  271. type_error(int id_, const char* what_arg)
  272. : exception(id_, what_arg)
  273. {}
  274. };
  275. /*!
  276. @brief exception indicating access out of the defined range
  277. Exceptions have ids 4xx.
  278. name / id | example message | description
  279. ------------------------------- | --------------- | -------------------------
  280. 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.
  281. 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.
  282. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  283. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  284. 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.
  285. 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.
  286. @since version 3.0.0
  287. */
  288. class out_of_range : public exception
  289. {
  290. public:
  291. static out_of_range create(int id, const std::string& what_arg)
  292. {
  293. std::string w = exception::name("out_of_range", id) + what_arg;
  294. return out_of_range(id, w.c_str());
  295. }
  296. private:
  297. out_of_range(int id_, const char* what_arg)
  298. : exception(id_, what_arg)
  299. {}
  300. };
  301. /*!
  302. @brief exception indicating other errors
  303. Exceptions have ids 5xx.
  304. name / id | example message | description
  305. ------------------------------ | --------------- | -------------------------
  306. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  307. json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair)
  308. @since version 3.0.0
  309. */
  310. class other_error : public exception
  311. {
  312. public:
  313. static other_error create(int id, const std::string& what_arg)
  314. {
  315. std::string w = exception::name("other_error", id) + what_arg;
  316. return other_error(id, w.c_str());
  317. }
  318. private:
  319. other_error(int id_, const char* what_arg)
  320. : exception(id_, what_arg)
  321. {}
  322. };
  323. ///////////////////////////
  324. // JSON type enumeration //
  325. ///////////////////////////
  326. /*!
  327. @brief the JSON type enumeration
  328. This enumeration collects the different JSON types. It is internally used to
  329. distinguish the stored values, and the functions @ref basic_json::is_null(),
  330. @ref basic_json::is_object(), @ref basic_json::is_array(),
  331. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  332. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  333. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  334. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  335. @ref basic_json::is_structured() rely on it.
  336. @note There are three enumeration entries (number_integer, number_unsigned, and
  337. number_float), because the library distinguishes these three types for numbers:
  338. @ref basic_json::number_unsigned_t is used for unsigned integers,
  339. @ref basic_json::number_integer_t is used for signed integers, and
  340. @ref basic_json::number_float_t is used for floating-point numbers or to
  341. approximate integers which do not fit in the limits of their respective type.
  342. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  343. value with the default value for a given type
  344. @since version 1.0.0
  345. */
  346. enum class value_t : uint8_t
  347. {
  348. null, ///< null value
  349. object, ///< object (unordered set of name/value pairs)
  350. array, ///< array (ordered collection of values)
  351. string, ///< string value
  352. boolean, ///< boolean value
  353. number_integer, ///< number value (signed integer)
  354. number_unsigned, ///< number value (unsigned integer)
  355. number_float, ///< number value (floating-point)
  356. discarded ///< discarded by the the parser callback function
  357. };
  358. /*!
  359. @brief comparison operator for JSON types
  360. Returns an ordering that is similar to Python:
  361. - order: null < boolean < number < object < array < string
  362. - furthermore, each type is not smaller than itself
  363. @since version 1.0.0
  364. */
  365. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  366. {
  367. static constexpr std::array<uint8_t, 8> order = {{
  368. 0, // null
  369. 3, // object
  370. 4, // array
  371. 5, // string
  372. 1, // boolean
  373. 2, // integer
  374. 2, // unsigned
  375. 2, // float
  376. }
  377. };
  378. // discarded values are not comparable
  379. if (lhs == value_t::discarded or rhs == value_t::discarded)
  380. {
  381. return false;
  382. }
  383. return order[static_cast<std::size_t>(lhs)] <
  384. order[static_cast<std::size_t>(rhs)];
  385. }
  386. /////////////
  387. // helpers //
  388. /////////////
  389. // alias templates to reduce boilerplate
  390. template<bool B, typename T = void>
  391. using enable_if_t = typename std::enable_if<B, T>::type;
  392. template<typename T>
  393. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  394. // implementation of C++14 index_sequence and affiliates
  395. // source: https://stackoverflow.com/a/32223343
  396. template <std::size_t... Ints>
  397. struct index_sequence
  398. {
  399. using type = index_sequence;
  400. using value_type = std::size_t;
  401. static constexpr std::size_t size() noexcept
  402. {
  403. return sizeof...(Ints);
  404. }
  405. };
  406. template <class Sequence1, class Sequence2>
  407. struct merge_and_renumber;
  408. template <std::size_t... I1, std::size_t... I2>
  409. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  410. : index_sequence < I1..., (sizeof...(I1) + I2)... >
  411. { };
  412. template <std::size_t N>
  413. struct make_index_sequence
  414. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  415. typename make_index_sequence < N - N / 2 >::type >
  416. { };
  417. template<> struct make_index_sequence<0> : index_sequence<> { };
  418. template<> struct make_index_sequence<1> : index_sequence<0> { };
  419. template<typename... Ts>
  420. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  421. /*
  422. Implementation of two C++17 constructs: conjunction, negation. This is needed
  423. to avoid evaluating all the traits in a condition
  424. For example: not std::is_same<void, T>::value and has_value_type<T>::value
  425. will not compile when T = void (on MSVC at least). Whereas
  426. conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
  427. stop evaluating if negation<...>::value == false
  428. Please note that those constructs must be used with caution, since symbols can
  429. become very long quickly (which can slow down compilation and cause MSVC
  430. internal compiler errors). Only use it when you have to (see example ahead).
  431. */
  432. template<class...> struct conjunction : std::true_type {};
  433. template<class B1> struct conjunction<B1> : B1 {};
  434. template<class B1, class... Bn>
  435. struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  436. template<class B> struct negation : std::integral_constant < bool, !B::value > {};
  437. // dispatch utility (taken from ranges-v3)
  438. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  439. template<> struct priority_tag<0> {};
  440. //////////////////
  441. // constructors //
  442. //////////////////
  443. template<value_t> struct external_constructor;
  444. template<>
  445. struct external_constructor<value_t::boolean>
  446. {
  447. template<typename BasicJsonType>
  448. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  449. {
  450. j.m_type = value_t::boolean;
  451. j.m_value = b;
  452. j.assert_invariant();
  453. }
  454. };
  455. template<>
  456. struct external_constructor<value_t::string>
  457. {
  458. template<typename BasicJsonType>
  459. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  460. {
  461. j.m_type = value_t::string;
  462. j.m_value = s;
  463. j.assert_invariant();
  464. }
  465. };
  466. template<>
  467. struct external_constructor<value_t::number_float>
  468. {
  469. template<typename BasicJsonType>
  470. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  471. {
  472. j.m_type = value_t::number_float;
  473. j.m_value = val;
  474. j.assert_invariant();
  475. }
  476. };
  477. template<>
  478. struct external_constructor<value_t::number_unsigned>
  479. {
  480. template<typename BasicJsonType>
  481. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  482. {
  483. j.m_type = value_t::number_unsigned;
  484. j.m_value = val;
  485. j.assert_invariant();
  486. }
  487. };
  488. template<>
  489. struct external_constructor<value_t::number_integer>
  490. {
  491. template<typename BasicJsonType>
  492. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  493. {
  494. j.m_type = value_t::number_integer;
  495. j.m_value = val;
  496. j.assert_invariant();
  497. }
  498. };
  499. template<>
  500. struct external_constructor<value_t::array>
  501. {
  502. template<typename BasicJsonType>
  503. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  504. {
  505. j.m_type = value_t::array;
  506. j.m_value = arr;
  507. j.assert_invariant();
  508. }
  509. template<typename BasicJsonType, typename CompatibleArrayType,
  510. enable_if_t<not std::is_same<CompatibleArrayType,
  511. typename BasicJsonType::array_t>::value,
  512. int> = 0>
  513. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  514. {
  515. using std::begin;
  516. using std::end;
  517. j.m_type = value_t::array;
  518. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  519. j.assert_invariant();
  520. }
  521. template<typename BasicJsonType>
  522. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  523. {
  524. j.m_type = value_t::array;
  525. j.m_value = value_t::array;
  526. j.m_value.array->reserve(arr.size());
  527. for (bool x : arr)
  528. {
  529. j.m_value.array->push_back(x);
  530. }
  531. j.assert_invariant();
  532. }
  533. };
  534. template<>
  535. struct external_constructor<value_t::object>
  536. {
  537. template<typename BasicJsonType>
  538. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  539. {
  540. j.m_type = value_t::object;
  541. j.m_value = obj;
  542. j.assert_invariant();
  543. }
  544. template<typename BasicJsonType, typename CompatibleObjectType,
  545. enable_if_t<not std::is_same<CompatibleObjectType,
  546. typename BasicJsonType::object_t>::value,
  547. int> = 0>
  548. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  549. {
  550. using std::begin;
  551. using std::end;
  552. j.m_type = value_t::object;
  553. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  554. j.assert_invariant();
  555. }
  556. };
  557. ////////////////////////
  558. // has_/is_ functions //
  559. ////////////////////////
  560. /*!
  561. @brief Helper to determine whether there's a key_type for T.
  562. This helper is used to tell associative containers apart from other containers
  563. such as sequence containers. For instance, `std::map` passes the test as it
  564. contains a `mapped_type`, whereas `std::vector` fails the test.
  565. @sa http://stackoverflow.com/a/7728728/266378
  566. @since version 1.0.0, overworked in version 2.0.6
  567. */
  568. #define NLOHMANN_JSON_HAS_HELPER(type) \
  569. template<typename T> struct has_##type { \
  570. private: \
  571. template<typename U, typename = typename U::type> \
  572. static int detect(U &&); \
  573. static void detect(...); \
  574. public: \
  575. static constexpr bool value = \
  576. std::is_integral<decltype(detect(std::declval<T>()))>::value; \
  577. }
  578. NLOHMANN_JSON_HAS_HELPER(mapped_type);
  579. NLOHMANN_JSON_HAS_HELPER(key_type);
  580. NLOHMANN_JSON_HAS_HELPER(value_type);
  581. NLOHMANN_JSON_HAS_HELPER(iterator);
  582. #undef NLOHMANN_JSON_HAS_HELPER
  583. template<bool B, class RealType, class CompatibleObjectType>
  584. struct is_compatible_object_type_impl : std::false_type {};
  585. template<class RealType, class CompatibleObjectType>
  586. struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
  587. {
  588. static constexpr auto value =
  589. std::is_constructible<typename RealType::key_type,
  590. typename CompatibleObjectType::key_type>::value and
  591. std::is_constructible<typename RealType::mapped_type,
  592. typename CompatibleObjectType::mapped_type>::value;
  593. };
  594. template<class BasicJsonType, class CompatibleObjectType>
  595. struct is_compatible_object_type
  596. {
  597. static auto constexpr value = is_compatible_object_type_impl <
  598. conjunction<negation<std::is_same<void, CompatibleObjectType>>,
  599. has_mapped_type<CompatibleObjectType>,
  600. has_key_type<CompatibleObjectType>>::value,
  601. typename BasicJsonType::object_t, CompatibleObjectType >::value;
  602. };
  603. template<typename BasicJsonType, typename T>
  604. struct is_basic_json_nested_type
  605. {
  606. static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
  607. std::is_same<T, typename BasicJsonType::const_iterator>::value or
  608. std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
  609. std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value or
  610. std::is_same<T, typename BasicJsonType::json_pointer>::value;
  611. };
  612. template<class BasicJsonType, class CompatibleArrayType>
  613. struct is_compatible_array_type
  614. {
  615. static auto constexpr value =
  616. conjunction<negation<std::is_same<void, CompatibleArrayType>>,
  617. negation<is_compatible_object_type<
  618. BasicJsonType, CompatibleArrayType>>,
  619. negation<std::is_constructible<typename BasicJsonType::string_t,
  620. CompatibleArrayType>>,
  621. negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
  622. has_value_type<CompatibleArrayType>,
  623. has_iterator<CompatibleArrayType>>::value;
  624. };
  625. template<bool, typename, typename>
  626. struct is_compatible_integer_type_impl : std::false_type {};
  627. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  628. struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
  629. {
  630. // is there an assert somewhere on overflows?
  631. using RealLimits = std::numeric_limits<RealIntegerType>;
  632. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  633. static constexpr auto value =
  634. std::is_constructible<RealIntegerType,
  635. CompatibleNumberIntegerType>::value and
  636. CompatibleLimits::is_integer and
  637. RealLimits::is_signed == CompatibleLimits::is_signed;
  638. };
  639. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  640. struct is_compatible_integer_type
  641. {
  642. static constexpr auto value =
  643. is_compatible_integer_type_impl <
  644. std::is_integral<CompatibleNumberIntegerType>::value and
  645. not std::is_same<bool, CompatibleNumberIntegerType>::value,
  646. RealIntegerType, CompatibleNumberIntegerType > ::value;
  647. };
  648. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  649. template<typename BasicJsonType, typename T>
  650. struct has_from_json
  651. {
  652. private:
  653. // also check the return type of from_json
  654. template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
  655. std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
  656. static int detect(U&&);
  657. static void detect(...);
  658. public:
  659. static constexpr bool value = std::is_integral<decltype(
  660. detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  661. };
  662. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  663. // this overload is used for non-default-constructible user-defined-types
  664. template<typename BasicJsonType, typename T>
  665. struct has_non_default_from_json
  666. {
  667. private:
  668. template <
  669. typename U,
  670. typename = enable_if_t<std::is_same<
  671. T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
  672. static int detect(U&&);
  673. static void detect(...);
  674. public:
  675. static constexpr bool value = std::is_integral<decltype(detect(
  676. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  677. };
  678. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  679. template<typename BasicJsonType, typename T>
  680. struct has_to_json
  681. {
  682. private:
  683. template<typename U, typename = decltype(uncvref_t<U>::to_json(
  684. std::declval<BasicJsonType&>(), std::declval<T>()))>
  685. static int detect(U&&);
  686. static void detect(...);
  687. public:
  688. static constexpr bool value = std::is_integral<decltype(detect(
  689. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  690. };
  691. /////////////
  692. // to_json //
  693. /////////////
  694. template<typename BasicJsonType, typename T, enable_if_t<
  695. std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  696. void to_json(BasicJsonType& j, T b) noexcept
  697. {
  698. external_constructor<value_t::boolean>::construct(j, b);
  699. }
  700. template<typename BasicJsonType, typename CompatibleString,
  701. enable_if_t<std::is_constructible<typename BasicJsonType::string_t,
  702. CompatibleString>::value, int> = 0>
  703. void to_json(BasicJsonType& j, const CompatibleString& s)
  704. {
  705. external_constructor<value_t::string>::construct(j, s);
  706. }
  707. template<typename BasicJsonType, typename FloatType,
  708. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  709. void to_json(BasicJsonType& j, FloatType val) noexcept
  710. {
  711. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  712. }
  713. template <
  714. typename BasicJsonType, typename CompatibleNumberUnsignedType,
  715. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t,
  716. CompatibleNumberUnsignedType>::value, int> = 0 >
  717. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  718. {
  719. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  720. }
  721. template <
  722. typename BasicJsonType, typename CompatibleNumberIntegerType,
  723. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t,
  724. CompatibleNumberIntegerType>::value, int> = 0 >
  725. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  726. {
  727. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  728. }
  729. template<typename BasicJsonType, typename EnumType,
  730. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  731. void to_json(BasicJsonType& j, EnumType e) noexcept
  732. {
  733. using underlying_type = typename std::underlying_type<EnumType>::type;
  734. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  735. }
  736. template<typename BasicJsonType>
  737. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  738. {
  739. external_constructor<value_t::array>::construct(j, e);
  740. }
  741. template <
  742. typename BasicJsonType, typename CompatibleArrayType,
  743. enable_if_t <
  744. is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
  745. std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
  746. int > = 0 >
  747. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  748. {
  749. external_constructor<value_t::array>::construct(j, arr);
  750. }
  751. template <
  752. typename BasicJsonType, typename CompatibleObjectType,
  753. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value,
  754. int> = 0 >
  755. void to_json(BasicJsonType& j, const CompatibleObjectType& arr)
  756. {
  757. external_constructor<value_t::object>::construct(j, arr);
  758. }
  759. template <typename BasicJsonType, typename T, std::size_t N,
  760. enable_if_t<not std::is_constructible<
  761. typename BasicJsonType::string_t, T (&)[N]>::value,
  762. int> = 0>
  763. void to_json(BasicJsonType& j, T (&arr)[N])
  764. {
  765. external_constructor<value_t::array>::construct(j, arr);
  766. }
  767. template <typename BasicJsonType, typename... Args>
  768. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  769. {
  770. j = {p.first, p.second};
  771. }
  772. template <typename BasicJsonType, typename Tuple, std::size_t... Idx>
  773. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
  774. {
  775. j = {std::get<Idx>(t)...};
  776. }
  777. template <typename BasicJsonType, typename... Args>
  778. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  779. {
  780. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  781. }
  782. ///////////////
  783. // from_json //
  784. ///////////////
  785. // overloads for basic_json template parameters
  786. template<typename BasicJsonType, typename ArithmeticType,
  787. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  788. not std::is_same<ArithmeticType,
  789. typename BasicJsonType::boolean_t>::value,
  790. int> = 0>
  791. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  792. {
  793. switch (static_cast<value_t>(j))
  794. {
  795. case value_t::number_unsigned:
  796. {
  797. val = static_cast<ArithmeticType>(
  798. *j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  799. break;
  800. }
  801. case value_t::number_integer:
  802. {
  803. val = static_cast<ArithmeticType>(
  804. *j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  805. break;
  806. }
  807. case value_t::number_float:
  808. {
  809. val = static_cast<ArithmeticType>(
  810. *j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  811. break;
  812. }
  813. default:
  814. {
  815. JSON_THROW(type_error::create(302, "type must be number, but is " + j.type_name()));
  816. }
  817. }
  818. }
  819. template<typename BasicJsonType>
  820. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  821. {
  822. if (not j.is_boolean())
  823. {
  824. JSON_THROW(type_error::create(302, "type must be boolean, but is " + j.type_name()));
  825. }
  826. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  827. }
  828. template<typename BasicJsonType>
  829. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  830. {
  831. if (not j.is_string())
  832. {
  833. JSON_THROW(type_error::create(302, "type must be string, but is " + j.type_name()));
  834. }
  835. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  836. }
  837. template<typename BasicJsonType>
  838. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  839. {
  840. get_arithmetic_value(j, val);
  841. }
  842. template<typename BasicJsonType>
  843. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  844. {
  845. get_arithmetic_value(j, val);
  846. }
  847. template<typename BasicJsonType>
  848. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  849. {
  850. get_arithmetic_value(j, val);
  851. }
  852. template<typename BasicJsonType, typename EnumType,
  853. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  854. void from_json(const BasicJsonType& j, EnumType& e)
  855. {
  856. typename std::underlying_type<EnumType>::type val;
  857. get_arithmetic_value(j, val);
  858. e = static_cast<EnumType>(val);
  859. }
  860. template<typename BasicJsonType>
  861. void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
  862. {
  863. if (not j.is_array())
  864. {
  865. JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name()));
  866. }
  867. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  868. }
  869. // forward_list doesn't have an insert method
  870. template<typename BasicJsonType, typename T, typename Allocator,
  871. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  872. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  873. {
  874. if (not j.is_array())
  875. {
  876. JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name()));
  877. }
  878. for (auto it = j.rbegin(), end = j.rend(); it != end; ++it)
  879. {
  880. l.push_front(it->template get<T>());
  881. }
  882. }
  883. template<typename BasicJsonType, typename CompatibleArrayType>
  884. void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0>)
  885. {
  886. using std::begin;
  887. using std::end;
  888. std::transform(j.begin(), j.end(),
  889. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  890. {
  891. // get<BasicJsonType>() returns *this, this won't call a from_json
  892. // method when value_type is BasicJsonType
  893. return i.template get<typename CompatibleArrayType::value_type>();
  894. });
  895. }
  896. template<typename BasicJsonType, typename CompatibleArrayType>
  897. auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1>)
  898. -> decltype(
  899. arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
  900. void())
  901. {
  902. using std::begin;
  903. using std::end;
  904. arr.reserve(j.size());
  905. std::transform(j.begin(), j.end(),
  906. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  907. {
  908. // get<BasicJsonType>() returns *this, this won't call a from_json
  909. // method when value_type is BasicJsonType
  910. return i.template get<typename CompatibleArrayType::value_type>();
  911. });
  912. }
  913. template <typename BasicJsonType, typename T, std::size_t N>
  914. void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2>)
  915. {
  916. for (std::size_t i = 0; i < N; ++i)
  917. {
  918. arr[i] = j.at(i).template get<T>();
  919. }
  920. }
  921. template<typename BasicJsonType, typename CompatibleArrayType,
  922. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
  923. std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
  924. not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
  925. void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
  926. {
  927. if (not j.is_array())
  928. {
  929. JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name()));
  930. }
  931. from_json_array_impl(j, arr, priority_tag<2> {});
  932. }
  933. template<typename BasicJsonType, typename CompatibleObjectType,
  934. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  935. void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
  936. {
  937. if (not j.is_object())
  938. {
  939. JSON_THROW(type_error::create(302, "type must be object, but is " + j.type_name()));
  940. }
  941. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  942. using std::begin;
  943. using std::end;
  944. using value_type = typename CompatibleObjectType::value_type;
  945. std::transform(
  946. inner_object->begin(), inner_object->end(),
  947. std::inserter(obj, obj.begin()),
  948. [](typename BasicJsonType::object_t::value_type const & p)
  949. {
  950. return value_type(
  951. p.first,
  952. p.second
  953. .template get<typename CompatibleObjectType::mapped_type>());
  954. });
  955. }
  956. // overload for arithmetic types, not chosen for basic_json template arguments
  957. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  958. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  959. // an arithmetic type?
  960. template<typename BasicJsonType, typename ArithmeticType,
  961. enable_if_t <
  962. std::is_arithmetic<ArithmeticType>::value and
  963. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  964. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  965. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  966. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  967. int> = 0>
  968. void from_json(const BasicJsonType& j, ArithmeticType& val)
  969. {
  970. switch (static_cast<value_t>(j))
  971. {
  972. case value_t::number_unsigned:
  973. {
  974. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  975. break;
  976. }
  977. case value_t::number_integer:
  978. {
  979. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  980. break;
  981. }
  982. case value_t::number_float:
  983. {
  984. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  985. break;
  986. }
  987. case value_t::boolean:
  988. {
  989. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  990. break;
  991. }
  992. default:
  993. {
  994. JSON_THROW(type_error::create(302, "type must be number, but is " + j.type_name()));
  995. }
  996. }
  997. }
  998. template <typename BasicJsonType, typename... Args>
  999. void from_json(const BasicJsonType& j, std::pair<Args...>& p)
  1000. {
  1001. p = {j.at(0), j.at(1)};
  1002. }
  1003. template <typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1004. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
  1005. {
  1006. t = std::make_tuple(j.at(Idx)...);
  1007. }
  1008. template <typename BasicJsonType, typename... Args>
  1009. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1010. {
  1011. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1012. }
  1013. struct to_json_fn
  1014. {
  1015. private:
  1016. template<typename BasicJsonType, typename T>
  1017. auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1018. -> decltype(to_json(j, std::forward<T>(val)), void())
  1019. {
  1020. return to_json(j, std::forward<T>(val));
  1021. }
  1022. template<typename BasicJsonType, typename T>
  1023. void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept
  1024. {
  1025. static_assert(sizeof(BasicJsonType) == 0,
  1026. "could not find to_json() method in T's namespace");
  1027. }
  1028. public:
  1029. template<typename BasicJsonType, typename T>
  1030. void operator()(BasicJsonType& j, T&& val) const
  1031. noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
  1032. {
  1033. return call(j, std::forward<T>(val), priority_tag<1> {});
  1034. }
  1035. };
  1036. struct from_json_fn
  1037. {
  1038. private:
  1039. template<typename BasicJsonType, typename T>
  1040. auto call(const BasicJsonType& j, T& val, priority_tag<1>) const
  1041. noexcept(noexcept(from_json(j, val)))
  1042. -> decltype(from_json(j, val), void())
  1043. {
  1044. return from_json(j, val);
  1045. }
  1046. template<typename BasicJsonType, typename T>
  1047. void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept
  1048. {
  1049. static_assert(sizeof(BasicJsonType) == 0,
  1050. "could not find from_json() method in T's namespace");
  1051. }
  1052. public:
  1053. template<typename BasicJsonType, typename T>
  1054. void operator()(const BasicJsonType& j, T& val) const
  1055. noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
  1056. {
  1057. return call(j, val, priority_tag<1> {});
  1058. }
  1059. };
  1060. // taken from ranges-v3
  1061. template<typename T>
  1062. struct static_const
  1063. {
  1064. static constexpr T value{};
  1065. };
  1066. template<typename T>
  1067. constexpr T static_const<T>::value;
  1068. } // namespace detail
  1069. /// namespace to hold default `to_json` / `from_json` functions
  1070. namespace
  1071. {
  1072. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  1073. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  1074. }
  1075. /*!
  1076. @brief default JSONSerializer template argument
  1077. This serializer ignores the template arguments and uses ADL
  1078. ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
  1079. for serialization.
  1080. */
  1081. template<typename = void, typename = void>
  1082. struct adl_serializer
  1083. {
  1084. /*!
  1085. @brief convert a JSON value to any value type
  1086. This function is usually called by the `get()` function of the
  1087. @ref basic_json class (either explicit or via conversion operators).
  1088. @param[in] j JSON value to read from
  1089. @param[in,out] val value to write to
  1090. */
  1091. template<typename BasicJsonType, typename ValueType>
  1092. static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
  1093. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  1094. {
  1095. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  1096. }
  1097. /*!
  1098. @brief convert any value type to a JSON value
  1099. This function is usually called by the constructors of the @ref basic_json
  1100. class.
  1101. @param[in,out] j JSON value to write to
  1102. @param[in] val value to read from
  1103. */
  1104. template<typename BasicJsonType, typename ValueType>
  1105. static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
  1106. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  1107. {
  1108. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  1109. }
  1110. };
  1111. /*!
  1112. @brief a class to store JSON values
  1113. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  1114. in @ref object_t)
  1115. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  1116. in @ref array_t)
  1117. @tparam StringType type for JSON strings and object keys (`std::string` by
  1118. default; will be used in @ref string_t)
  1119. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  1120. in @ref boolean_t)
  1121. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  1122. default; will be used in @ref number_integer_t)
  1123. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  1124. `uint64_t` by default; will be used in @ref number_unsigned_t)
  1125. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  1126. default; will be used in @ref number_float_t)
  1127. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  1128. default)
  1129. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  1130. and `from_json()` (@ref adl_serializer by default)
  1131. @requirement The class satisfies the following concept requirements:
  1132. - Basic
  1133. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  1134. JSON values can be default constructed. The result will be a JSON null
  1135. value.
  1136. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  1137. A JSON value can be constructed from an rvalue argument.
  1138. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  1139. A JSON value can be copy-constructed from an lvalue expression.
  1140. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  1141. A JSON value van be assigned from an rvalue argument.
  1142. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  1143. A JSON value can be copy-assigned from an lvalue expression.
  1144. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  1145. JSON values can be destructed.
  1146. - Layout
  1147. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  1148. JSON values have
  1149. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  1150. All non-static data members are private and standard layout types, the
  1151. class has no virtual functions or (virtual) base classes.
  1152. - Library-wide
  1153. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  1154. JSON values can be compared with `==`, see @ref
  1155. operator==(const_reference,const_reference).
  1156. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  1157. JSON values can be compared with `<`, see @ref
  1158. operator<(const_reference,const_reference).
  1159. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  1160. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  1161. other compatible types, using unqualified function call @ref swap().
  1162. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  1163. JSON values can be compared against `std::nullptr_t` objects which are used
  1164. to model the `null` value.
  1165. - Container
  1166. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  1167. JSON values can be used like STL containers and provide iterator access.
  1168. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  1169. JSON values can be used like STL containers and provide reverse iterator
  1170. access.
  1171. @invariant The member variables @a m_value and @a m_type have the following
  1172. relationship:
  1173. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  1174. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  1175. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  1176. The invariants are checked by member function assert_invariant().
  1177. @internal
  1178. @note ObjectType trick from http://stackoverflow.com/a/9860911
  1179. @endinternal
  1180. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  1181. Format](http://rfc7159.net/rfc7159)
  1182. @since version 1.0.0
  1183. @nosubgrouping
  1184. */
  1185. template <
  1186. template<typename U, typename V, typename... Args> class ObjectType = std::map,
  1187. template<typename U, typename... Args> class ArrayType = std::vector,
  1188. class StringType = std::string,
  1189. class BooleanType = bool,
  1190. class NumberIntegerType = std::int64_t,
  1191. class NumberUnsignedType = std::uint64_t,
  1192. class NumberFloatType = double,
  1193. template<typename U> class AllocatorType = std::allocator,
  1194. template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer
  1195. >
  1196. class basic_json
  1197. {
  1198. private:
  1199. template<detail::value_t> friend struct detail::external_constructor;
  1200. /// workaround type for MSVC
  1201. using basic_json_t = basic_json<ObjectType, ArrayType, StringType,
  1202. BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType,
  1203. AllocatorType, JSONSerializer>;
  1204. public:
  1205. using value_t = detail::value_t;
  1206. // forward declarations
  1207. template<typename U> class iter_impl;
  1208. template<typename Base> class json_reverse_iterator;
  1209. class json_pointer;
  1210. template<typename T, typename SFINAE>
  1211. using json_serializer = JSONSerializer<T, SFINAE>;
  1212. ////////////////
  1213. // exceptions //
  1214. ////////////////
  1215. /// @name exceptions
  1216. /// Classes to implement user-defined exceptions.
  1217. /// @{
  1218. /// @copydoc detail::exception
  1219. using exception = detail::exception;
  1220. /// @copydoc detail::parse_error
  1221. using parse_error = detail::parse_error;
  1222. /// @copydoc detail::invalid_iterator
  1223. using invalid_iterator = detail::invalid_iterator;
  1224. /// @copydoc detail::type_error
  1225. using type_error = detail::type_error;
  1226. /// @copydoc detail::out_of_range
  1227. using out_of_range = detail::out_of_range;
  1228. /// @copydoc detail::other_error
  1229. using other_error = detail::other_error;
  1230. /// @}
  1231. /////////////////////
  1232. // container types //
  1233. /////////////////////
  1234. /// @name container types
  1235. /// The canonic container types to use @ref basic_json like any other STL
  1236. /// container.
  1237. /// @{
  1238. /// the type of elements in a basic_json container
  1239. using value_type = basic_json;
  1240. /// the type of an element reference
  1241. using reference = value_type&;
  1242. /// the type of an element const reference
  1243. using const_reference = const value_type&;
  1244. /// a type to represent differences between iterators
  1245. using difference_type = std::ptrdiff_t;
  1246. /// a type to represent container sizes
  1247. using size_type = std::size_t;
  1248. /// the allocator type
  1249. using allocator_type = AllocatorType<basic_json>;
  1250. /// the type of an element pointer
  1251. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  1252. /// the type of an element const pointer
  1253. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  1254. /// an iterator for a basic_json container
  1255. using iterator = iter_impl<basic_json>;
  1256. /// a const iterator for a basic_json container
  1257. using const_iterator = iter_impl<const basic_json>;
  1258. /// a reverse iterator for a basic_json container
  1259. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  1260. /// a const reverse iterator for a basic_json container
  1261. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  1262. /// @}
  1263. /*!
  1264. @brief returns the allocator associated with the container
  1265. */
  1266. static allocator_type get_allocator()
  1267. {
  1268. return allocator_type();
  1269. }
  1270. /*!
  1271. @brief returns version information on the library
  1272. This function returns a JSON object with information about the library,
  1273. including the version number and information on the platform and compiler.
  1274. @return JSON object holding version information
  1275. key | description
  1276. ----------- | ---------------
  1277. `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).
  1278. `copyright` | The copyright line for the library as string.
  1279. `name` | The name of the library as string.
  1280. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  1281. `url` | The URL of the project as string.
  1282. `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).
  1283. @liveexample{The following code shows an example output of the `meta()`
  1284. function.,meta}
  1285. @complexity Constant.
  1286. @since 2.1.0
  1287. */
  1288. static basic_json meta()
  1289. {
  1290. basic_json result;
  1291. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  1292. result["name"] = "JSON for Modern C++";
  1293. result["url"] = "https://github.com/nlohmann/json";
  1294. result["version"] =
  1295. {
  1296. {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1}
  1297. };
  1298. #ifdef _WIN32
  1299. result["platform"] = "win32";
  1300. #elif defined __linux__
  1301. result["platform"] = "linux";
  1302. #elif defined __APPLE__
  1303. result["platform"] = "apple";
  1304. #elif defined __unix__
  1305. result["platform"] = "unix";
  1306. #else
  1307. result["platform"] = "unknown";
  1308. #endif
  1309. #if defined(__clang__)
  1310. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  1311. #elif defined(__ICC) || defined(__INTEL_COMPILER)
  1312. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  1313. #elif defined(__GNUC__) || defined(__GNUG__)
  1314. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  1315. #elif defined(__HP_cc) || defined(__HP_aCC)
  1316. result["compiler"] = "hp"
  1317. #elif defined(__IBMCPP__)
  1318. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  1319. #elif defined(_MSC_VER)
  1320. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  1321. #elif defined(__PGI)
  1322. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  1323. #elif defined(__SUNPRO_CC)
  1324. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  1325. #else
  1326. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  1327. #endif
  1328. #ifdef __cplusplus
  1329. result["compiler"]["c++"] = std::to_string(__cplusplus);
  1330. #else
  1331. result["compiler"]["c++"] = "unknown";
  1332. #endif
  1333. return result;
  1334. }
  1335. ///////////////////////////
  1336. // JSON value data types //
  1337. ///////////////////////////
  1338. /// @name JSON value data types
  1339. /// The data types to store a JSON value. These types are derived from
  1340. /// the template arguments passed to class @ref basic_json.
  1341. /// @{
  1342. /*!
  1343. @brief a type for an object
  1344. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  1345. > An object is an unordered collection of zero or more name/value pairs,
  1346. > where a name is a string and a value is a string, number, boolean, null,
  1347. > object, or array.
  1348. To store objects in C++, a type is defined by the template parameters
  1349. described below.
  1350. @tparam ObjectType the container to store objects (e.g., `std::map` or
  1351. `std::unordered_map`)
  1352. @tparam StringType the type of the keys or names (e.g., `std::string`).
  1353. The comparison function `std::less<StringType>` is used to order elements
  1354. inside the container.
  1355. @tparam AllocatorType the allocator to use for objects (e.g.,
  1356. `std::allocator`)
  1357. #### Default type
  1358. With the default values for @a ObjectType (`std::map`), @a StringType
  1359. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  1360. value for @a object_t is:
  1361. @code {.cpp}
  1362. std::map<
  1363. std::string, // key_type
  1364. basic_json, // value_type
  1365. std::less<std::string>, // key_compare
  1366. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  1367. >
  1368. @endcode
  1369. #### Behavior
  1370. The choice of @a object_t influences the behavior of the JSON class. With
  1371. the default type, objects have the following behavior:
  1372. - When all names are unique, objects will be interoperable in the sense
  1373. that all software implementations receiving that object will agree on
  1374. the name-value mappings.
  1375. - When the names within an object are not unique, later stored name/value
  1376. pairs overwrite previously stored name/value pairs, leaving the used
  1377. names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
  1378. be treated as equal and both stored as `{"key": 1}`.
  1379. - Internally, name/value pairs are stored in lexicographical order of the
  1380. names. Objects will also be serialized (see @ref dump) in this order.
  1381. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  1382. and serialized as `{"a": 2, "b": 1}`.
  1383. - When comparing objects, the order of the name/value pairs is irrelevant.
  1384. This makes objects interoperable in the sense that they will not be
  1385. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  1386. `{"a": 2, "b": 1}` will be treated as equal.
  1387. #### Limits
  1388. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1389. > An implementation may set limits on the maximum depth of nesting.
  1390. In this class, the object's limit of nesting is not constraint explicitly.
  1391. However, a maximum depth of nesting may be introduced by the compiler or
  1392. runtime environment. A theoretical limit can be queried by calling the
  1393. @ref max_size function of a JSON object.
  1394. #### Storage
  1395. Objects are stored as pointers in a @ref basic_json type. That is, for any
  1396. access to object values, a pointer of type `object_t*` must be
  1397. dereferenced.
  1398. @sa @ref array_t -- type for an array value
  1399. @since version 1.0.0
  1400. @note The order name/value pairs are added to the object is *not*
  1401. preserved by the library. Therefore, iterating an object may return
  1402. name/value pairs in a different order than they were originally stored. In
  1403. fact, keys will be traversed in alphabetical order as `std::map` with
  1404. `std::less` is used by default. Please note this behavior conforms to [RFC
  1405. 7159](http://rfc7159.net/rfc7159), because any order implements the
  1406. specified "unordered" nature of JSON objects.
  1407. */
  1408. using object_t = ObjectType<StringType,
  1409. basic_json,
  1410. std::less<StringType>,
  1411. AllocatorType<std::pair<const StringType,
  1412. basic_json>>>;
  1413. /*!
  1414. @brief a type for an array
  1415. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  1416. > An array is an ordered sequence of zero or more values.
  1417. To store objects in C++, a type is defined by the template parameters
  1418. explained below.
  1419. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  1420. `std::list`)
  1421. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  1422. #### Default type
  1423. With the default values for @a ArrayType (`std::vector`) and @a
  1424. AllocatorType (`std::allocator`), the default value for @a array_t is:
  1425. @code {.cpp}
  1426. std::vector<
  1427. basic_json, // value_type
  1428. std::allocator<basic_json> // allocator_type
  1429. >
  1430. @endcode
  1431. #### Limits
  1432. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1433. > An implementation may set limits on the maximum depth of nesting.
  1434. In this class, the array's limit of nesting is not constraint explicitly.
  1435. However, a maximum depth of nesting may be introduced by the compiler or
  1436. runtime environment. A theoretical limit can be queried by calling the
  1437. @ref max_size function of a JSON array.
  1438. #### Storage
  1439. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  1440. access to array values, a pointer of type `array_t*` must be dereferenced.
  1441. @sa @ref object_t -- type for an object value
  1442. @since version 1.0.0
  1443. */
  1444. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  1445. /*!
  1446. @brief a type for a string
  1447. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  1448. > A string is a sequence of zero or more Unicode characters.
  1449. To store objects in C++, a type is defined by the template parameter
  1450. described below. Unicode values are split by the JSON class into
  1451. byte-sized characters during deserialization.
  1452. @tparam StringType the container to store strings (e.g., `std::string`).
  1453. Note this container is used for keys/names in objects, see @ref object_t.
  1454. #### Default type
  1455. With the default values for @a StringType (`std::string`), the default
  1456. value for @a string_t is:
  1457. @code {.cpp}
  1458. std::string
  1459. @endcode
  1460. #### Encoding
  1461. Strings are stored in UTF-8 encoding. Therefore, functions like
  1462. `std::string::size()` or `std::string::length()` return the number of
  1463. bytes in the string rather than the number of characters or glyphs.
  1464. #### String comparison
  1465. [RFC 7159](http://rfc7159.net/rfc7159) states:
  1466. > Software implementations are typically required to test names of object
  1467. > members for equality. Implementations that transform the textual
  1468. > representation into sequences of Unicode code units and then perform the
  1469. > comparison numerically, code unit by code unit, are interoperable in the
  1470. > sense that implementations will agree in all cases on equality or
  1471. > inequality of two strings. For example, implementations that compare
  1472. > strings with escaped characters unconverted may incorrectly find that
  1473. > `"a\\b"` and `"a\u005Cb"` are not equal.
  1474. This implementation is interoperable as it does compare strings code unit
  1475. by code unit.
  1476. #### Storage
  1477. String values are stored as pointers in a @ref basic_json type. That is,
  1478. for any access to string values, a pointer of type `string_t*` must be
  1479. dereferenced.
  1480. @since version 1.0.0
  1481. */
  1482. using string_t = StringType;
  1483. /*!
  1484. @brief a type for a boolean
  1485. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  1486. type which differentiates the two literals `true` and `false`.
  1487. To store objects in C++, a type is defined by the template parameter @a
  1488. BooleanType which chooses the type to use.
  1489. #### Default type
  1490. With the default values for @a BooleanType (`bool`), the default value for
  1491. @a boolean_t is:
  1492. @code {.cpp}
  1493. bool
  1494. @endcode
  1495. #### Storage
  1496. Boolean values are stored directly inside a @ref basic_json type.
  1497. @since version 1.0.0
  1498. */
  1499. using boolean_t = BooleanType;
  1500. /*!
  1501. @brief a type for a number (integer)
  1502. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  1503. > The representation of numbers is similar to that used in most
  1504. > programming languages. A number is represented in base 10 using decimal
  1505. > digits. It contains an integer component that may be prefixed with an
  1506. > optional minus sign, which may be followed by a fraction part and/or an
  1507. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  1508. > cannot be represented in the grammar below (such as Infinity and NaN)
  1509. > are not permitted.
  1510. This description includes both integer and floating-point numbers.
  1511. However, C++ allows more precise storage if it is known whether the number
  1512. is a signed integer, an unsigned integer or a floating-point number.
  1513. Therefore, three different types, @ref number_integer_t, @ref
  1514. number_unsigned_t and @ref number_float_t are used.
  1515. To store integer numbers in C++, a type is defined by the template
  1516. parameter @a NumberIntegerType which chooses the type to use.
  1517. #### Default type
  1518. With the default values for @a NumberIntegerType (`int64_t`), the default
  1519. value for @a number_integer_t is:
  1520. @code {.cpp}
  1521. int64_t
  1522. @endcode
  1523. #### Default behavior
  1524. - The restrictions about leading zeros is not enforced in C++. Instead,
  1525. leading zeros in integer literals lead to an interpretation as octal
  1526. number. Internally, the value will be stored as decimal number. For
  1527. instance, the C++ integer literal `010` will be serialized to `8`.
  1528. During deserialization, leading zeros yield an error.
  1529. - Not-a-number (NaN) values will be serialized to `null`.
  1530. #### Limits
  1531. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1532. > An implementation may set limits on the range and precision of numbers.
  1533. When the default type is used, the maximal integer number that can be
  1534. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  1535. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  1536. that are out of range will yield over/underflow when used in a
  1537. constructor. During deserialization, too large or small integer numbers
  1538. will be automatically be stored as @ref number_unsigned_t or @ref
  1539. number_float_t.
  1540. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  1541. > Note that when such software is used, numbers that are integers and are
  1542. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  1543. > that implementations will agree exactly on their numeric values.
  1544. As this range is a subrange of the exactly supported range [INT64_MIN,
  1545. INT64_MAX], this class's integer type is interoperable.
  1546. #### Storage
  1547. Integer number values are stored directly inside a @ref basic_json type.
  1548. @sa @ref number_float_t -- type for number values (floating-point)
  1549. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  1550. @since version 1.0.0
  1551. */
  1552. using number_integer_t = NumberIntegerType;
  1553. /*!
  1554. @brief a type for a number (unsigned)
  1555. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  1556. > The representation of numbers is similar to that used in most
  1557. > programming languages. A number is represented in base 10 using decimal
  1558. > digits. It contains an integer component that may be prefixed with an
  1559. > optional minus sign, which may be followed by a fraction part and/or an
  1560. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  1561. > cannot be represented in the grammar below (such as Infinity and NaN)
  1562. > are not permitted.
  1563. This description includes both integer and floating-point numbers.
  1564. However, C++ allows more precise storage if it is known whether the number
  1565. is a signed integer, an unsigned integer or a floating-point number.
  1566. Therefore, three different types, @ref number_integer_t, @ref
  1567. number_unsigned_t and @ref number_float_t are used.
  1568. To store unsigned integer numbers in C++, a type is defined by the
  1569. template parameter @a NumberUnsignedType which chooses the type to use.
  1570. #### Default type
  1571. With the default values for @a NumberUnsignedType (`uint64_t`), the
  1572. default value for @a number_unsigned_t is:
  1573. @code {.cpp}
  1574. uint64_t
  1575. @endcode
  1576. #### Default behavior
  1577. - The restrictions about leading zeros is not enforced in C++. Instead,
  1578. leading zeros in integer literals lead to an interpretation as octal
  1579. number. Internally, the value will be stored as decimal number. For
  1580. instance, the C++ integer literal `010` will be serialized to `8`.
  1581. During deserialization, leading zeros yield an error.
  1582. - Not-a-number (NaN) values will be serialized to `null`.
  1583. #### Limits
  1584. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1585. > An implementation may set limits on the range and precision of numbers.
  1586. When the default type is used, the maximal integer number that can be
  1587. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  1588. number that can be stored is `0`. Integer numbers that are out of range
  1589. will yield over/underflow when used in a constructor. During
  1590. deserialization, too large or small integer numbers will be automatically
  1591. be stored as @ref number_integer_t or @ref number_float_t.
  1592. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  1593. > Note that when such software is used, numbers that are integers and are
  1594. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  1595. > that implementations will agree exactly on their numeric values.
  1596. As this range is a subrange (when considered in conjunction with the
  1597. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  1598. this class's integer type is interoperable.
  1599. #### Storage
  1600. Integer number values are stored directly inside a @ref basic_json type.
  1601. @sa @ref number_float_t -- type for number values (floating-point)
  1602. @sa @ref number_integer_t -- type for number values (integer)
  1603. @since version 2.0.0
  1604. */
  1605. using number_unsigned_t = NumberUnsignedType;
  1606. /*!
  1607. @brief a type for a number (floating-point)
  1608. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  1609. > The representation of numbers is similar to that used in most
  1610. > programming languages. A number is represented in base 10 using decimal
  1611. > digits. It contains an integer component that may be prefixed with an
  1612. > optional minus sign, which may be followed by a fraction part and/or an
  1613. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  1614. > cannot be represented in the grammar below (such as Infinity and NaN)
  1615. > are not permitted.
  1616. This description includes both integer and floating-point numbers.
  1617. However, C++ allows more precise storage if it is known whether the number
  1618. is a signed integer, an unsigned integer or a floating-point number.
  1619. Therefore, three different types, @ref number_integer_t, @ref
  1620. number_unsigned_t and @ref number_float_t are used.
  1621. To store floating-point numbers in C++, a type is defined by the template
  1622. parameter @a NumberFloatType which chooses the type to use.
  1623. #### Default type
  1624. With the default values for @a NumberFloatType (`double`), the default
  1625. value for @a number_float_t is:
  1626. @code {.cpp}
  1627. double
  1628. @endcode
  1629. #### Default behavior
  1630. - The restrictions about leading zeros is not enforced in C++. Instead,
  1631. leading zeros in floating-point literals will be ignored. Internally,
  1632. the value will be stored as decimal number. For instance, the C++
  1633. floating-point literal `01.2` will be serialized to `1.2`. During
  1634. deserialization, leading zeros yield an error.
  1635. - Not-a-number (NaN) values will be serialized to `null`.
  1636. #### Limits
  1637. [RFC 7159](http://rfc7159.net/rfc7159) states:
  1638. > This specification allows implementations to set limits on the range and
  1639. > precision of numbers accepted. Since software that implements IEEE
  1640. > 754-2008 binary64 (double precision) numbers is generally available and
  1641. > widely used, good interoperability can be achieved by implementations
  1642. > that expect no more precision or range than these provide, in the sense
  1643. > that implementations will approximate JSON numbers within the expected
  1644. > precision.
  1645. This implementation does exactly follow this approach, as it uses double
  1646. precision floating-point numbers. Note values smaller than
  1647. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  1648. will be stored as NaN internally and be serialized to `null`.
  1649. #### Storage
  1650. Floating-point number values are stored directly inside a @ref basic_json
  1651. type.
  1652. @sa @ref number_integer_t -- type for number values (integer)
  1653. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  1654. @since version 1.0.0
  1655. */
  1656. using number_float_t = NumberFloatType;
  1657. /// @}
  1658. private:
  1659. /// helper for exception-safe object creation
  1660. template<typename T, typename... Args>
  1661. static T* create(Args&& ... args)
  1662. {
  1663. AllocatorType<T> alloc;
  1664. auto deleter = [&](T * object)
  1665. {
  1666. alloc.deallocate(object, 1);
  1667. };
  1668. std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
  1669. alloc.construct(object.get(), std::forward<Args>(args)...);
  1670. assert(object != nullptr);
  1671. return object.release();
  1672. }
  1673. ////////////////////////
  1674. // JSON value storage //
  1675. ////////////////////////
  1676. /*!
  1677. @brief a JSON value
  1678. The actual storage for a JSON value of the @ref basic_json class. This
  1679. union combines the different storage types for the JSON value types
  1680. defined in @ref value_t.
  1681. JSON type | value_t type | used type
  1682. --------- | --------------- | ------------------------
  1683. object | object | pointer to @ref object_t
  1684. array | array | pointer to @ref array_t
  1685. string | string | pointer to @ref string_t
  1686. boolean | boolean | @ref boolean_t
  1687. number | number_integer | @ref number_integer_t
  1688. number | number_unsigned | @ref number_unsigned_t
  1689. number | number_float | @ref number_float_t
  1690. null | null | *no value is stored*
  1691. @note Variable-length types (objects, arrays, and strings) are stored as
  1692. pointers. The size of the union should not exceed 64 bits if the default
  1693. value types are used.
  1694. @since version 1.0.0
  1695. */
  1696. union json_value
  1697. {
  1698. /// object (stored with pointer to save storage)
  1699. object_t* object;
  1700. /// array (stored with pointer to save storage)
  1701. array_t* array;
  1702. /// string (stored with pointer to save storage)
  1703. string_t* string;
  1704. /// boolean
  1705. boolean_t boolean;
  1706. /// number (integer)
  1707. number_integer_t number_integer;
  1708. /// number (unsigned integer)
  1709. number_unsigned_t number_unsigned;
  1710. /// number (floating-point)
  1711. number_float_t number_float;
  1712. /// default constructor (for null values)
  1713. json_value() = default;
  1714. /// constructor for booleans
  1715. json_value(boolean_t v) noexcept : boolean(v) {}
  1716. /// constructor for numbers (integer)
  1717. json_value(number_integer_t v) noexcept : number_integer(v) {}
  1718. /// constructor for numbers (unsigned)
  1719. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  1720. /// constructor for numbers (floating-point)
  1721. json_value(number_float_t v) noexcept : number_float(v) {}
  1722. /// constructor for empty values of a given type
  1723. json_value(value_t t)
  1724. {
  1725. switch (t)
  1726. {
  1727. case value_t::object:
  1728. {
  1729. object = create<object_t>();
  1730. break;
  1731. }
  1732. case value_t::array:
  1733. {
  1734. array = create<array_t>();
  1735. break;
  1736. }
  1737. case value_t::string:
  1738. {
  1739. string = create<string_t>("");
  1740. break;
  1741. }
  1742. case value_t::boolean:
  1743. {
  1744. boolean = boolean_t(false);
  1745. break;
  1746. }
  1747. case value_t::number_integer:
  1748. {
  1749. number_integer = number_integer_t(0);
  1750. break;
  1751. }
  1752. case value_t::number_unsigned:
  1753. {
  1754. number_unsigned = number_unsigned_t(0);
  1755. break;
  1756. }
  1757. case value_t::number_float:
  1758. {
  1759. number_float = number_float_t(0.0);
  1760. break;
  1761. }
  1762. case value_t::null:
  1763. {
  1764. break;
  1765. }
  1766. default:
  1767. {
  1768. if (JSON_UNLIKELY(t == value_t::null))
  1769. {
  1770. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE
  1771. }
  1772. break;
  1773. }
  1774. }
  1775. }
  1776. /// constructor for strings
  1777. json_value(const string_t& value)
  1778. {
  1779. string = create<string_t>(value);
  1780. }
  1781. /// constructor for objects
  1782. json_value(const object_t& value)
  1783. {
  1784. object = create<object_t>(value);
  1785. }
  1786. /// constructor for arrays
  1787. json_value(const array_t& value)
  1788. {
  1789. array = create<array_t>(value);
  1790. }
  1791. };
  1792. /*!
  1793. @brief checks the class invariants
  1794. This function asserts the class invariants. It needs to be called at the
  1795. end of every constructor to make sure that created objects respect the
  1796. invariant. Furthermore, it has to be called each time the type of a JSON
  1797. value is changed, because the invariant expresses a relationship between
  1798. @a m_type and @a m_value.
  1799. */
  1800. void assert_invariant() const
  1801. {
  1802. assert(m_type != value_t::object or m_value.object != nullptr);
  1803. assert(m_type != value_t::array or m_value.array != nullptr);
  1804. assert(m_type != value_t::string or m_value.string != nullptr);
  1805. }
  1806. public:
  1807. //////////////////////////
  1808. // JSON parser callback //
  1809. //////////////////////////
  1810. /*!
  1811. @brief JSON callback events
  1812. This enumeration lists the parser events that can trigger calling a
  1813. callback function of type @ref parser_callback_t during parsing.
  1814. @image html callback_events.png "Example when certain parse events are triggered"
  1815. @since version 1.0.0
  1816. */
  1817. enum class parse_event_t : uint8_t
  1818. {
  1819. /// the parser read `{` and started to process a JSON object
  1820. object_start,
  1821. /// the parser read `}` and finished processing a JSON object
  1822. object_end,
  1823. /// the parser read `[` and started to process a JSON array
  1824. array_start,
  1825. /// the parser read `]` and finished processing a JSON array
  1826. array_end,
  1827. /// the parser read a key of a value in an object
  1828. key,
  1829. /// the parser finished reading a JSON value
  1830. value
  1831. };
  1832. /*!
  1833. @brief per-element parser callback type
  1834. With a parser callback function, the result of parsing a JSON text can be
  1835. influenced. When passed to @ref parse(std::istream&, const
  1836. parser_callback_t) or @ref parse(const CharT, const parser_callback_t),
  1837. it is called on certain events (passed as @ref parse_event_t via parameter
  1838. @a event) with a set recursion depth @a depth and context JSON value
  1839. @a parsed. The return value of the callback function is a boolean
  1840. indicating whether the element that emitted the callback shall be kept or
  1841. not.
  1842. We distinguish six scenarios (determined by the event type) in which the
  1843. callback function can be called. The following table describes the values
  1844. of the parameters @a depth, @a event, and @a parsed.
  1845. parameter @a event | description | parameter @a depth | parameter @a parsed
  1846. ------------------ | ----------- | ------------------ | -------------------
  1847. 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
  1848. 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
  1849. 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
  1850. 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
  1851. 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
  1852. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  1853. @image html callback_events.png "Example when certain parse events are triggered"
  1854. Discarding a value (i.e., returning `false`) has different effects
  1855. depending on the context in which function was called:
  1856. - Discarded values in structured types are skipped. That is, the parser
  1857. will behave as if the discarded value was never read.
  1858. - In case a value outside a structured type is skipped, it is replaced
  1859. with `null`. This case happens if the top-level element is skipped.
  1860. @param[in] depth the depth of the recursion during parsing
  1861. @param[in] event an event of type parse_event_t indicating the context in
  1862. the callback function has been called
  1863. @param[in,out] parsed the current intermediate parse result; note that
  1864. writing to this value has no effect for parse_event_t::key events
  1865. @return Whether the JSON value which called the function during parsing
  1866. should be kept (`true`) or not (`false`). In the latter case, it is either
  1867. skipped completely or replaced by an empty discarded object.
  1868. @sa @ref parse(std::istream&, parser_callback_t) or
  1869. @ref parse(const CharT, const parser_callback_t) for examples
  1870. @since version 1.0.0
  1871. */
  1872. using parser_callback_t = std::function<bool(int depth,
  1873. parse_event_t event,
  1874. basic_json& parsed)>;
  1875. //////////////////
  1876. // constructors //
  1877. //////////////////
  1878. /// @name constructors and destructors
  1879. /// Constructors of class @ref basic_json, copy/move constructor, copy
  1880. /// assignment, static functions creating objects, and the destructor.
  1881. /// @{
  1882. /*!
  1883. @brief create an empty value with a given type
  1884. Create an empty JSON value with a given type. The value will be default
  1885. initialized with an empty value which depends on the type:
  1886. Value type | initial value
  1887. ----------- | -------------
  1888. null | `null`
  1889. boolean | `false`
  1890. string | `""`
  1891. number | `0`
  1892. object | `{}`
  1893. array | `[]`
  1894. @param[in] v the type of the value to create
  1895. @complexity Constant.
  1896. @liveexample{The following code shows the constructor for different @ref
  1897. value_t values,basic_json__value_t}
  1898. @since version 1.0.0
  1899. */
  1900. basic_json(const value_t v)
  1901. : m_type(v), m_value(v)
  1902. {
  1903. assert_invariant();
  1904. }
  1905. /*!
  1906. @brief create a null object
  1907. Create a `null` JSON value. It either takes a null pointer as parameter
  1908. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  1909. The passed null pointer itself is not read -- it is only used to choose
  1910. the right constructor.
  1911. @complexity Constant.
  1912. @exceptionsafety No-throw guarantee: this constructor never throws
  1913. exceptions.
  1914. @liveexample{The following code shows the constructor with and without a
  1915. null pointer parameter.,basic_json__nullptr_t}
  1916. @since version 1.0.0
  1917. */
  1918. basic_json(std::nullptr_t = nullptr) noexcept
  1919. : basic_json(value_t::null)
  1920. {
  1921. assert_invariant();
  1922. }
  1923. /*!
  1924. @brief create a JSON value
  1925. This is a "catch all" constructor for all compatible JSON types; that is,
  1926. types for which a `to_json()` method exsits. The constructor forwards the
  1927. parameter @a val to that method (to `json_serializer<U>::to_json` method
  1928. with `U = uncvref_t<CompatibleType>`, to be exact).
  1929. Template type @a CompatibleType includes, but is not limited to, the
  1930. following types:
  1931. - **arrays**: @ref array_t and all kinds of compatible containers such as
  1932. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  1933. `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and
  1934. `unordered_multiset` with a `value_type` from which a @ref basic_json
  1935. value can be constructed.
  1936. - **objects**: @ref object_t and all kinds of compatible associative
  1937. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  1938. and `std::unordered_multimap` with a `key_type` compatible to
  1939. @ref string_t and a `value_type` from which a @ref basic_json value can
  1940. be constructed.
  1941. - **strings**: @ref string_t, string literals, and all compatible string
  1942. containers can be used.
  1943. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  1944. @ref number_float_t, and all convertible number types such as `int`,
  1945. `size_t`, `int64_t`, `float` or `double` can be used.
  1946. - **boolean**: @ref boolean_t / `bool` can be used.
  1947. See the examples below.
  1948. @tparam CompatibleType a type such that:
  1949. - @a CompatibleType is not derived from `std::istream`,
  1950. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  1951. constructors),
  1952. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  1953. @ref json_pointer, @ref iterator, etc ...)
  1954. - @ref @ref json_serializer<U> has a
  1955. `to_json(basic_json_t&, CompatibleType&&)` method
  1956. @tparam U = `uncvref_t<CompatibleType>`
  1957. @param[in] val the value to be forwarded
  1958. @complexity Usually linear in the size of the passed @a val, also
  1959. depending on the implementation of the called `to_json()`
  1960. method.
  1961. @throw what `json_serializer<U>::to_json()` throws
  1962. @liveexample{The following code shows the constructor with several
  1963. compatible types.,basic_json__CompatibleType}
  1964. @since version 2.1.0
  1965. */
  1966. template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
  1967. detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
  1968. not std::is_same<U, basic_json_t>::value and
  1969. not detail::is_basic_json_nested_type<
  1970. basic_json_t, U>::value and
  1971. detail::has_to_json<basic_json, U>::value,
  1972. int> = 0>
  1973. basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
  1974. std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
  1975. {
  1976. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  1977. assert_invariant();
  1978. }
  1979. /*!
  1980. @brief create a container (array or object) from an initializer list
  1981. Creates a JSON value of type array or object from the passed initializer
  1982. list @a init. In case @a type_deduction is `true` (default), the type of
  1983. the JSON value to be created is deducted from the initializer list @a init
  1984. according to the following rules:
  1985. 1. If the list is empty, an empty JSON object value `{}` is created.
  1986. 2. If the list consists of pairs whose first element is a string, a JSON
  1987. object value is created where the first elements of the pairs are
  1988. treated as keys and the second elements are as values.
  1989. 3. In all other cases, an array is created.
  1990. The rules aim to create the best fit between a C++ initializer list and
  1991. JSON values. The rationale is as follows:
  1992. 1. The empty initializer list is written as `{}` which is exactly an empty
  1993. JSON object.
  1994. 2. C++ has now way of describing mapped types other than to list a list of
  1995. pairs. As JSON requires that keys must be of type string, rule 2 is the
  1996. weakest constraint one can pose on initializer lists to interpret them
  1997. as an object.
  1998. 3. In all other cases, the initializer list could not be interpreted as
  1999. JSON object type, so interpreting it as JSON array type is safe.
  2000. With the rules described above, the following JSON values cannot be
  2001. expressed by an initializer list:
  2002. - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
  2003. with an empty initializer list in this case
  2004. - arrays whose elements satisfy rule 2: use @ref
  2005. array(std::initializer_list<basic_json>) with the same initializer list
  2006. in this case
  2007. @note When used without parentheses around an empty initializer list, @ref
  2008. basic_json() is called instead of this function, yielding the JSON null
  2009. value.
  2010. @param[in] init initializer list with JSON values
  2011. @param[in] type_deduction internal parameter; when set to `true`, the type
  2012. of the JSON value is deducted from the initializer list @a init; when set
  2013. to `false`, the type provided via @a manual_type is forced. This mode is
  2014. used by the functions @ref array(std::initializer_list<basic_json>) and
  2015. @ref object(std::initializer_list<basic_json>).
  2016. @param[in] manual_type internal parameter; when @a type_deduction is set
  2017. to `false`, the created JSON value will use the provided type (only @ref
  2018. value_t::array and @ref value_t::object are valid); when @a type_deduction
  2019. is set to `true`, this parameter has no effect
  2020. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  2021. `value_t::object`, but @a init contains an element which is not a pair
  2022. whose first element is a string. In this case, the constructor could not
  2023. create an object. If @a type_deduction would have be `true`, an array
  2024. would have been created. See @ref object(std::initializer_list<basic_json>)
  2025. for an example.
  2026. @complexity Linear in the size of the initializer list @a init.
  2027. @liveexample{The example below shows how JSON values are created from
  2028. initializer lists.,basic_json__list_init_t}
  2029. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  2030. value from an initializer list
  2031. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  2032. value from an initializer list
  2033. @since version 1.0.0
  2034. */
  2035. basic_json(std::initializer_list<basic_json> init,
  2036. bool type_deduction = true,
  2037. value_t manual_type = value_t::array)
  2038. {
  2039. // check if each element is an array with two elements whose first
  2040. // element is a string
  2041. bool is_an_object = std::all_of(init.begin(), init.end(),
  2042. [](const basic_json & element)
  2043. {
  2044. return element.is_array() and element.size() == 2 and element[0].is_string();
  2045. });
  2046. // adjust type if type deduction is not wanted
  2047. if (not type_deduction)
  2048. {
  2049. // if array is wanted, do not create an object though possible
  2050. if (manual_type == value_t::array)
  2051. {
  2052. is_an_object = false;
  2053. }
  2054. // if object is wanted but impossible, throw an exception
  2055. if (manual_type == value_t::object and not is_an_object)
  2056. {
  2057. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  2058. }
  2059. }
  2060. if (is_an_object)
  2061. {
  2062. // the initializer list is a list of pairs -> create object
  2063. m_type = value_t::object;
  2064. m_value = value_t::object;
  2065. std::for_each(init.begin(), init.end(), [this](const basic_json & element)
  2066. {
  2067. m_value.object->emplace(*(element[0].m_value.string), element[1]);
  2068. });
  2069. }
  2070. else
  2071. {
  2072. // the initializer list describes an array -> create array
  2073. m_type = value_t::array;
  2074. m_value.array = create<array_t>(init);
  2075. }
  2076. assert_invariant();
  2077. }
  2078. /*!
  2079. @brief explicitly create an array from an initializer list
  2080. Creates a JSON array value from a given initializer list. That is, given a
  2081. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  2082. initializer list is empty, the empty array `[]` is created.
  2083. @note This function is only needed to express two edge cases that cannot
  2084. be realized with the initializer list constructor (@ref
  2085. basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
  2086. are:
  2087. 1. creating an array whose elements are all pairs whose first element is a
  2088. string -- in this case, the initializer list constructor would create an
  2089. object, taking the first elements as keys
  2090. 2. creating an empty array -- passing the empty initializer list to the
  2091. initializer list constructor yields an empty object
  2092. @param[in] init initializer list with JSON values to create an array from
  2093. (optional)
  2094. @return JSON array value
  2095. @complexity Linear in the size of @a init.
  2096. @liveexample{The following code shows an example for the `array`
  2097. function.,array}
  2098. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  2099. create a JSON value from an initializer list
  2100. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  2101. value from an initializer list
  2102. @since version 1.0.0
  2103. */
  2104. static basic_json array(std::initializer_list<basic_json> init =
  2105. std::initializer_list<basic_json>())
  2106. {
  2107. return basic_json(init, false, value_t::array);
  2108. }
  2109. /*!
  2110. @brief explicitly create an object from an initializer list
  2111. Creates a JSON object value from a given initializer list. The initializer
  2112. lists elements must be pairs, and their first elements must be strings. If
  2113. the initializer list is empty, the empty object `{}` is created.
  2114. @note This function is only added for symmetry reasons. In contrast to the
  2115. related function @ref array(std::initializer_list<basic_json>), there are
  2116. no cases which can only be expressed by this function. That is, any
  2117. initializer list @a init can also be passed to the initializer list
  2118. constructor @ref basic_json(std::initializer_list<basic_json>, bool, value_t).
  2119. @param[in] init initializer list to create an object from (optional)
  2120. @return JSON object value
  2121. @throw type_error.301 if @a init is not a list of pairs whose first
  2122. elements are strings. In this case, no object can be created. When such a
  2123. value is passed to @ref basic_json(std::initializer_list<basic_json>, bool, value_t),
  2124. an array would have been created from the passed initializer list @a init.
  2125. See example below.
  2126. @complexity Linear in the size of @a init.
  2127. @liveexample{The following code shows an example for the `object`
  2128. function.,object}
  2129. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  2130. create a JSON value from an initializer list
  2131. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  2132. value from an initializer list
  2133. @since version 1.0.0
  2134. */
  2135. static basic_json object(std::initializer_list<basic_json> init =
  2136. std::initializer_list<basic_json>())
  2137. {
  2138. return basic_json(init, false, value_t::object);
  2139. }
  2140. /*!
  2141. @brief construct an array with count copies of given value
  2142. Constructs a JSON array value by creating @a cnt copies of a passed value.
  2143. In case @a cnt is `0`, an empty array is created. As postcondition,
  2144. `std::distance(begin(),end()) == cnt` holds.
  2145. @param[in] cnt the number of JSON copies of @a val to create
  2146. @param[in] val the JSON value to copy
  2147. @complexity Linear in @a cnt.
  2148. @liveexample{The following code shows examples for the @ref
  2149. basic_json(size_type\, const basic_json&)
  2150. constructor.,basic_json__size_type_basic_json}
  2151. @since version 1.0.0
  2152. */
  2153. basic_json(size_type cnt, const basic_json& val)
  2154. : m_type(value_t::array)
  2155. {
  2156. m_value.array = create<array_t>(cnt, val);
  2157. assert_invariant();
  2158. }
  2159. /*!
  2160. @brief construct a JSON container given an iterator range
  2161. Constructs the JSON value with the contents of the range `[first, last)`.
  2162. The semantics depends on the different types a JSON value can have:
  2163. - In case of primitive types (number, boolean, or string), @a first must
  2164. be `begin()` and @a last must be `end()`. In this case, the value is
  2165. copied. Otherwise, invalid_iterator.204 is thrown.
  2166. - In case of structured types (array, object), the constructor behaves as
  2167. similar versions for `std::vector`.
  2168. - In case of a null type, invalid_iterator.206 is thrown.
  2169. @tparam InputIT an input iterator type (@ref iterator or @ref
  2170. const_iterator)
  2171. @param[in] first begin of the range to copy from (included)
  2172. @param[in] last end of the range to copy from (excluded)
  2173. @pre Iterators @a first and @a last must be initialized. **This
  2174. precondition is enforced with an assertion.**
  2175. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  2176. checked efficiently. Only certain edge cases are detected; see the
  2177. description of the exceptions below.
  2178. @throw invalid_iterator.201 if iterators @a first and @a last are not
  2179. compatible (i.e., do not belong to the same JSON value). In this case,
  2180. the range `[first, last)` is undefined.
  2181. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  2182. primitive type (number, boolean, or string), but @a first does not point
  2183. to the first element any more. In this case, the range `[first, last)` is
  2184. undefined. See example code below.
  2185. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  2186. null value. In this case, the range `[first, last)` is undefined.
  2187. @complexity Linear in distance between @a first and @a last.
  2188. @liveexample{The example below shows several ways to create JSON values by
  2189. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  2190. @since version 1.0.0
  2191. */
  2192. template<class InputIT, typename std::enable_if<
  2193. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  2194. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  2195. basic_json(InputIT first, InputIT last)
  2196. {
  2197. assert(first.m_object != nullptr);
  2198. assert(last.m_object != nullptr);
  2199. // make sure iterator fits the current value
  2200. if (first.m_object != last.m_object)
  2201. {
  2202. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  2203. }
  2204. // copy type from first iterator
  2205. m_type = first.m_object->m_type;
  2206. // check if iterator range is complete for primitive values
  2207. switch (m_type)
  2208. {
  2209. case value_t::boolean:
  2210. case value_t::number_float:
  2211. case value_t::number_integer:
  2212. case value_t::number_unsigned:
  2213. case value_t::string:
  2214. {
  2215. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  2216. {
  2217. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  2218. }
  2219. break;
  2220. }
  2221. default:
  2222. {
  2223. break;
  2224. }
  2225. }
  2226. switch (m_type)
  2227. {
  2228. case value_t::number_integer:
  2229. {
  2230. m_value.number_integer = first.m_object->m_value.number_integer;
  2231. break;
  2232. }
  2233. case value_t::number_unsigned:
  2234. {
  2235. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  2236. break;
  2237. }
  2238. case value_t::number_float:
  2239. {
  2240. m_value.number_float = first.m_object->m_value.number_float;
  2241. break;
  2242. }
  2243. case value_t::boolean:
  2244. {
  2245. m_value.boolean = first.m_object->m_value.boolean;
  2246. break;
  2247. }
  2248. case value_t::string:
  2249. {
  2250. m_value = *first.m_object->m_value.string;
  2251. break;
  2252. }
  2253. case value_t::object:
  2254. {
  2255. m_value.object = create<object_t>(first.m_it.object_iterator,
  2256. last.m_it.object_iterator);
  2257. break;
  2258. }
  2259. case value_t::array:
  2260. {
  2261. m_value.array = create<array_t>(first.m_it.array_iterator,
  2262. last.m_it.array_iterator);
  2263. break;
  2264. }
  2265. default:
  2266. {
  2267. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  2268. first.m_object->type_name()));
  2269. }
  2270. }
  2271. assert_invariant();
  2272. }
  2273. ///////////////////////////////////////
  2274. // other constructors and destructor //
  2275. ///////////////////////////////////////
  2276. /*!
  2277. @brief copy constructor
  2278. Creates a copy of a given JSON value.
  2279. @param[in] other the JSON value to copy
  2280. @complexity Linear in the size of @a other.
  2281. @requirement This function helps `basic_json` satisfying the
  2282. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  2283. requirements:
  2284. - The complexity is linear.
  2285. - As postcondition, it holds: `other == basic_json(other)`.
  2286. @liveexample{The following code shows an example for the copy
  2287. constructor.,basic_json__basic_json}
  2288. @since version 1.0.0
  2289. */
  2290. basic_json(const basic_json& other)
  2291. : m_type(other.m_type)
  2292. {
  2293. // check of passed value is valid
  2294. other.assert_invariant();
  2295. switch (m_type)
  2296. {
  2297. case value_t::object:
  2298. {
  2299. m_value = *other.m_value.object;
  2300. break;
  2301. }
  2302. case value_t::array:
  2303. {
  2304. m_value = *other.m_value.array;
  2305. break;
  2306. }
  2307. case value_t::string:
  2308. {
  2309. m_value = *other.m_value.string;
  2310. break;
  2311. }
  2312. case value_t::boolean:
  2313. {
  2314. m_value = other.m_value.boolean;
  2315. break;
  2316. }
  2317. case value_t::number_integer:
  2318. {
  2319. m_value = other.m_value.number_integer;
  2320. break;
  2321. }
  2322. case value_t::number_unsigned:
  2323. {
  2324. m_value = other.m_value.number_unsigned;
  2325. break;
  2326. }
  2327. case value_t::number_float:
  2328. {
  2329. m_value = other.m_value.number_float;
  2330. break;
  2331. }
  2332. default:
  2333. {
  2334. break;
  2335. }
  2336. }
  2337. assert_invariant();
  2338. }
  2339. /*!
  2340. @brief move constructor
  2341. Move constructor. Constructs a JSON value with the contents of the given
  2342. value @a other using move semantics. It "steals" the resources from @a
  2343. other and leaves it as JSON null value.
  2344. @param[in,out] other value to move to this object
  2345. @post @a other is a JSON null value
  2346. @complexity Constant.
  2347. @liveexample{The code below shows the move constructor explicitly called
  2348. via std::move.,basic_json__moveconstructor}
  2349. @since version 1.0.0
  2350. */
  2351. basic_json(basic_json&& other) noexcept
  2352. : m_type(std::move(other.m_type)),
  2353. m_value(std::move(other.m_value))
  2354. {
  2355. // check that passed value is valid
  2356. other.assert_invariant();
  2357. // invalidate payload
  2358. other.m_type = value_t::null;
  2359. other.m_value = {};
  2360. assert_invariant();
  2361. }
  2362. /*!
  2363. @brief copy assignment
  2364. Copy assignment operator. Copies a JSON value via the "copy and swap"
  2365. strategy: It is expressed in terms of the copy constructor, destructor,
  2366. and the swap() member function.
  2367. @param[in] other value to copy from
  2368. @complexity Linear.
  2369. @requirement This function helps `basic_json` satisfying the
  2370. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  2371. requirements:
  2372. - The complexity is linear.
  2373. @liveexample{The code below shows and example for the copy assignment. It
  2374. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  2375. copy of `a` (which is the null value after the swap) is
  2376. destroyed.,basic_json__copyassignment}
  2377. @since version 1.0.0
  2378. */
  2379. reference& operator=(basic_json other) noexcept (
  2380. std::is_nothrow_move_constructible<value_t>::value and
  2381. std::is_nothrow_move_assignable<value_t>::value and
  2382. std::is_nothrow_move_constructible<json_value>::value and
  2383. std::is_nothrow_move_assignable<json_value>::value
  2384. )
  2385. {
  2386. // check that passed value is valid
  2387. other.assert_invariant();
  2388. using std::swap;
  2389. swap(m_type, other.m_type);
  2390. swap(m_value, other.m_value);
  2391. assert_invariant();
  2392. return *this;
  2393. }
  2394. /*!
  2395. @brief destructor
  2396. Destroys the JSON value and frees all allocated memory.
  2397. @complexity Linear.
  2398. @requirement This function helps `basic_json` satisfying the
  2399. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  2400. requirements:
  2401. - The complexity is linear.
  2402. - All stored elements are destroyed and all memory is freed.
  2403. @since version 1.0.0
  2404. */
  2405. ~basic_json()
  2406. {
  2407. assert_invariant();
  2408. switch (m_type)
  2409. {
  2410. case value_t::object:
  2411. {
  2412. AllocatorType<object_t> alloc;
  2413. alloc.destroy(m_value.object);
  2414. alloc.deallocate(m_value.object, 1);
  2415. break;
  2416. }
  2417. case value_t::array:
  2418. {
  2419. AllocatorType<array_t> alloc;
  2420. alloc.destroy(m_value.array);
  2421. alloc.deallocate(m_value.array, 1);
  2422. break;
  2423. }
  2424. case value_t::string:
  2425. {
  2426. AllocatorType<string_t> alloc;
  2427. alloc.destroy(m_value.string);
  2428. alloc.deallocate(m_value.string, 1);
  2429. break;
  2430. }
  2431. default:
  2432. {
  2433. // all other types need no specific destructor
  2434. break;
  2435. }
  2436. }
  2437. }
  2438. /// @}
  2439. public:
  2440. ///////////////////////
  2441. // object inspection //
  2442. ///////////////////////
  2443. /// @name object inspection
  2444. /// Functions to inspect the type of a JSON value.
  2445. /// @{
  2446. /*!
  2447. @brief serialization
  2448. Serialization function for JSON values. The function tries to mimic
  2449. Python's `json.dumps()` function, and currently supports its @a indent
  2450. parameter.
  2451. @param[in] indent If indent is nonnegative, then array elements and object
  2452. members will be pretty-printed with that indent level. An indent level of
  2453. `0` will only insert newlines. `-1` (the default) selects the most compact
  2454. representation.
  2455. @param[in] indent_char The character to use for indentation if @a indent is
  2456. greater than `0`. The default is ` ` (space).
  2457. @return string containing the serialization of the JSON value
  2458. @complexity Linear.
  2459. @liveexample{The following example shows the effect of different @a indent
  2460. parameters to the result of the serialization.,dump}
  2461. @see https://docs.python.org/2/library/json.html#json.dump
  2462. @since version 1.0.0; indentation character added in version 3.0.0
  2463. */
  2464. string_t dump(const int indent = -1, const char indent_char = ' ') const
  2465. {
  2466. string_t result;
  2467. serializer s(output_adapter<char>::create(result), indent_char);
  2468. if (indent >= 0)
  2469. {
  2470. s.dump(*this, true, static_cast<unsigned int>(indent));
  2471. }
  2472. else
  2473. {
  2474. s.dump(*this, false, 0);
  2475. }
  2476. return result;
  2477. }
  2478. /*!
  2479. @brief return the type of the JSON value (explicit)
  2480. Return the type of the JSON value as a value from the @ref value_t
  2481. enumeration.
  2482. @return the type of the JSON value
  2483. @complexity Constant.
  2484. @exceptionsafety No-throw guarantee: this member function never throws
  2485. exceptions.
  2486. @liveexample{The following code exemplifies `type()` for all JSON
  2487. types.,type}
  2488. @since version 1.0.0
  2489. */
  2490. constexpr value_t type() const noexcept
  2491. {
  2492. return m_type;
  2493. }
  2494. /*!
  2495. @brief return whether type is primitive
  2496. This function returns true iff the JSON type is primitive (string, number,
  2497. boolean, or null).
  2498. @return `true` if type is primitive (string, number, boolean, or null),
  2499. `false` otherwise.
  2500. @complexity Constant.
  2501. @exceptionsafety No-throw guarantee: this member function never throws
  2502. exceptions.
  2503. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  2504. types.,is_primitive}
  2505. @sa @ref is_structured() -- returns whether JSON value is structured
  2506. @sa @ref is_null() -- returns whether JSON value is `null`
  2507. @sa @ref is_string() -- returns whether JSON value is a string
  2508. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  2509. @sa @ref is_number() -- returns whether JSON value is a number
  2510. @since version 1.0.0
  2511. */
  2512. constexpr bool is_primitive() const noexcept
  2513. {
  2514. return is_null() or is_string() or is_boolean() or is_number();
  2515. }
  2516. /*!
  2517. @brief return whether type is structured
  2518. This function returns true iff the JSON type is structured (array or
  2519. object).
  2520. @return `true` if type is structured (array or object), `false` otherwise.
  2521. @complexity Constant.
  2522. @exceptionsafety No-throw guarantee: this member function never throws
  2523. exceptions.
  2524. @liveexample{The following code exemplifies `is_structured()` for all JSON
  2525. types.,is_structured}
  2526. @sa @ref is_primitive() -- returns whether value is primitive
  2527. @sa @ref is_array() -- returns whether value is an array
  2528. @sa @ref is_object() -- returns whether value is an object
  2529. @since version 1.0.0
  2530. */
  2531. constexpr bool is_structured() const noexcept
  2532. {
  2533. return is_array() or is_object();
  2534. }
  2535. /*!
  2536. @brief return whether value is null
  2537. This function returns true iff the JSON value is null.
  2538. @return `true` if type is null, `false` otherwise.
  2539. @complexity Constant.
  2540. @exceptionsafety No-throw guarantee: this member function never throws
  2541. exceptions.
  2542. @liveexample{The following code exemplifies `is_null()` for all JSON
  2543. types.,is_null}
  2544. @since version 1.0.0
  2545. */
  2546. constexpr bool is_null() const noexcept
  2547. {
  2548. return m_type == value_t::null;
  2549. }
  2550. /*!
  2551. @brief return whether value is a boolean
  2552. This function returns true iff the JSON value is a boolean.
  2553. @return `true` if type is boolean, `false` otherwise.
  2554. @complexity Constant.
  2555. @exceptionsafety No-throw guarantee: this member function never throws
  2556. exceptions.
  2557. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  2558. types.,is_boolean}
  2559. @since version 1.0.0
  2560. */
  2561. constexpr bool is_boolean() const noexcept
  2562. {
  2563. return m_type == value_t::boolean;
  2564. }
  2565. /*!
  2566. @brief return whether value is a number
  2567. This function returns true iff the JSON value is a number. This includes
  2568. both integer and floating-point values.
  2569. @return `true` if type is number (regardless whether integer, unsigned
  2570. integer or floating-type), `false` otherwise.
  2571. @complexity Constant.
  2572. @exceptionsafety No-throw guarantee: this member function never throws
  2573. exceptions.
  2574. @liveexample{The following code exemplifies `is_number()` for all JSON
  2575. types.,is_number}
  2576. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  2577. integer number
  2578. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2579. number
  2580. @sa @ref is_number_float() -- check if value is a floating-point number
  2581. @since version 1.0.0
  2582. */
  2583. constexpr bool is_number() const noexcept
  2584. {
  2585. return is_number_integer() or is_number_float();
  2586. }
  2587. /*!
  2588. @brief return whether value is an integer number
  2589. This function returns true iff the JSON value is an integer or unsigned
  2590. integer number. This excludes floating-point values.
  2591. @return `true` if type is an integer or unsigned integer number, `false`
  2592. otherwise.
  2593. @complexity Constant.
  2594. @exceptionsafety No-throw guarantee: this member function never throws
  2595. exceptions.
  2596. @liveexample{The following code exemplifies `is_number_integer()` for all
  2597. JSON types.,is_number_integer}
  2598. @sa @ref is_number() -- check if value is a number
  2599. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2600. number
  2601. @sa @ref is_number_float() -- check if value is a floating-point number
  2602. @since version 1.0.0
  2603. */
  2604. constexpr bool is_number_integer() const noexcept
  2605. {
  2606. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  2607. }
  2608. /*!
  2609. @brief return whether value is an unsigned integer number
  2610. This function returns true iff the JSON value is an unsigned integer
  2611. number. This excludes floating-point and (signed) integer values.
  2612. @return `true` if type is an unsigned integer number, `false` otherwise.
  2613. @complexity Constant.
  2614. @exceptionsafety No-throw guarantee: this member function never throws
  2615. exceptions.
  2616. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  2617. JSON types.,is_number_unsigned}
  2618. @sa @ref is_number() -- check if value is a number
  2619. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  2620. integer number
  2621. @sa @ref is_number_float() -- check if value is a floating-point number
  2622. @since version 2.0.0
  2623. */
  2624. constexpr bool is_number_unsigned() const noexcept
  2625. {
  2626. return m_type == value_t::number_unsigned;
  2627. }
  2628. /*!
  2629. @brief return whether value is a floating-point number
  2630. This function returns true iff the JSON value is a floating-point number.
  2631. This excludes integer and unsigned integer values.
  2632. @return `true` if type is a floating-point number, `false` otherwise.
  2633. @complexity Constant.
  2634. @exceptionsafety No-throw guarantee: this member function never throws
  2635. exceptions.
  2636. @liveexample{The following code exemplifies `is_number_float()` for all
  2637. JSON types.,is_number_float}
  2638. @sa @ref is_number() -- check if value is number
  2639. @sa @ref is_number_integer() -- check if value is an integer number
  2640. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2641. number
  2642. @since version 1.0.0
  2643. */
  2644. constexpr bool is_number_float() const noexcept
  2645. {
  2646. return m_type == value_t::number_float;
  2647. }
  2648. /*!
  2649. @brief return whether value is an object
  2650. This function returns true iff the JSON value is an object.
  2651. @return `true` if type is object, `false` otherwise.
  2652. @complexity Constant.
  2653. @exceptionsafety No-throw guarantee: this member function never throws
  2654. exceptions.
  2655. @liveexample{The following code exemplifies `is_object()` for all JSON
  2656. types.,is_object}
  2657. @since version 1.0.0
  2658. */
  2659. constexpr bool is_object() const noexcept
  2660. {
  2661. return m_type == value_t::object;
  2662. }
  2663. /*!
  2664. @brief return whether value is an array
  2665. This function returns true iff the JSON value is an array.
  2666. @return `true` if type is array, `false` otherwise.
  2667. @complexity Constant.
  2668. @exceptionsafety No-throw guarantee: this member function never throws
  2669. exceptions.
  2670. @liveexample{The following code exemplifies `is_array()` for all JSON
  2671. types.,is_array}
  2672. @since version 1.0.0
  2673. */
  2674. constexpr bool is_array() const noexcept
  2675. {
  2676. return m_type == value_t::array;
  2677. }
  2678. /*!
  2679. @brief return whether value is a string
  2680. This function returns true iff the JSON value is a string.
  2681. @return `true` if type is string, `false` otherwise.
  2682. @complexity Constant.
  2683. @exceptionsafety No-throw guarantee: this member function never throws
  2684. exceptions.
  2685. @liveexample{The following code exemplifies `is_string()` for all JSON
  2686. types.,is_string}
  2687. @since version 1.0.0
  2688. */
  2689. constexpr bool is_string() const noexcept
  2690. {
  2691. return m_type == value_t::string;
  2692. }
  2693. /*!
  2694. @brief return whether value is discarded
  2695. This function returns true iff the JSON value was discarded during parsing
  2696. with a callback function (see @ref parser_callback_t).
  2697. @note This function will always be `false` for JSON values after parsing.
  2698. That is, discarded values can only occur during parsing, but will be
  2699. removed when inside a structured value or replaced by null in other cases.
  2700. @return `true` if type is discarded, `false` otherwise.
  2701. @complexity Constant.
  2702. @exceptionsafety No-throw guarantee: this member function never throws
  2703. exceptions.
  2704. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  2705. types.,is_discarded}
  2706. @since version 1.0.0
  2707. */
  2708. constexpr bool is_discarded() const noexcept
  2709. {
  2710. return m_type == value_t::discarded;
  2711. }
  2712. /*!
  2713. @brief return the type of the JSON value (implicit)
  2714. Implicitly return the type of the JSON value as a value from the @ref
  2715. value_t enumeration.
  2716. @return the type of the JSON value
  2717. @complexity Constant.
  2718. @exceptionsafety No-throw guarantee: this member function never throws
  2719. exceptions.
  2720. @liveexample{The following code exemplifies the @ref value_t operator for
  2721. all JSON types.,operator__value_t}
  2722. @since version 1.0.0
  2723. */
  2724. constexpr operator value_t() const noexcept
  2725. {
  2726. return m_type;
  2727. }
  2728. /// @}
  2729. private:
  2730. //////////////////
  2731. // value access //
  2732. //////////////////
  2733. /// get a boolean (explicit)
  2734. boolean_t get_impl(boolean_t* /*unused*/) const
  2735. {
  2736. if (is_boolean())
  2737. {
  2738. return m_value.boolean;
  2739. }
  2740. JSON_THROW(type_error::create(302, "type must be boolean, but is " + type_name()));
  2741. }
  2742. /// get a pointer to the value (object)
  2743. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  2744. {
  2745. return is_object() ? m_value.object : nullptr;
  2746. }
  2747. /// get a pointer to the value (object)
  2748. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  2749. {
  2750. return is_object() ? m_value.object : nullptr;
  2751. }
  2752. /// get a pointer to the value (array)
  2753. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  2754. {
  2755. return is_array() ? m_value.array : nullptr;
  2756. }
  2757. /// get a pointer to the value (array)
  2758. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  2759. {
  2760. return is_array() ? m_value.array : nullptr;
  2761. }
  2762. /// get a pointer to the value (string)
  2763. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  2764. {
  2765. return is_string() ? m_value.string : nullptr;
  2766. }
  2767. /// get a pointer to the value (string)
  2768. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  2769. {
  2770. return is_string() ? m_value.string : nullptr;
  2771. }
  2772. /// get a pointer to the value (boolean)
  2773. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  2774. {
  2775. return is_boolean() ? &m_value.boolean : nullptr;
  2776. }
  2777. /// get a pointer to the value (boolean)
  2778. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  2779. {
  2780. return is_boolean() ? &m_value.boolean : nullptr;
  2781. }
  2782. /// get a pointer to the value (integer number)
  2783. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  2784. {
  2785. return is_number_integer() ? &m_value.number_integer : nullptr;
  2786. }
  2787. /// get a pointer to the value (integer number)
  2788. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  2789. {
  2790. return is_number_integer() ? &m_value.number_integer : nullptr;
  2791. }
  2792. /// get a pointer to the value (unsigned number)
  2793. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  2794. {
  2795. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2796. }
  2797. /// get a pointer to the value (unsigned number)
  2798. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  2799. {
  2800. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2801. }
  2802. /// get a pointer to the value (floating-point number)
  2803. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  2804. {
  2805. return is_number_float() ? &m_value.number_float : nullptr;
  2806. }
  2807. /// get a pointer to the value (floating-point number)
  2808. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  2809. {
  2810. return is_number_float() ? &m_value.number_float : nullptr;
  2811. }
  2812. /*!
  2813. @brief helper function to implement get_ref()
  2814. This function helps to implement get_ref() without code duplication for
  2815. const and non-const overloads
  2816. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  2817. @throw type_error.303 if ReferenceType does not match underlying value
  2818. type of the current JSON
  2819. */
  2820. template<typename ReferenceType, typename ThisType>
  2821. static ReferenceType get_ref_impl(ThisType& obj)
  2822. {
  2823. // helper type
  2824. using PointerType = typename std::add_pointer<ReferenceType>::type;
  2825. // delegate the call to get_ptr<>()
  2826. auto ptr = obj.template get_ptr<PointerType>();
  2827. if (ptr != nullptr)
  2828. {
  2829. return *ptr;
  2830. }
  2831. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + obj.type_name()));
  2832. }
  2833. public:
  2834. /// @name value access
  2835. /// Direct access to the stored value of a JSON value.
  2836. /// @{
  2837. /*!
  2838. @brief get special-case overload
  2839. This overloads avoids a lot of template boilerplate, it can be seen as the
  2840. identity method
  2841. @tparam BasicJsonType == @ref basic_json
  2842. @return a copy of *this
  2843. @complexity Constant.
  2844. @since version 2.1.0
  2845. */
  2846. template <
  2847. typename BasicJsonType,
  2848. detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type,
  2849. basic_json_t>::value,
  2850. int> = 0 >
  2851. basic_json get() const
  2852. {
  2853. return *this;
  2854. }
  2855. /*!
  2856. @brief get a value (explicit)
  2857. Explicit type conversion between the JSON value and a compatible value
  2858. which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  2859. and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  2860. The value is converted by calling the @ref json_serializer<ValueType>
  2861. `from_json()` method.
  2862. The function is equivalent to executing
  2863. @code {.cpp}
  2864. ValueType ret;
  2865. JSONSerializer<ValueType>::from_json(*this, ret);
  2866. return ret;
  2867. @endcode
  2868. This overloads is chosen if:
  2869. - @a ValueType is not @ref basic_json,
  2870. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2871. `void from_json(const basic_json&, ValueType&)`, and
  2872. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  2873. the form `ValueType from_json(const basic_json&)`
  2874. @tparam ValueTypeCV the provided value type
  2875. @tparam ValueType the returned value type
  2876. @return copy of the JSON value, converted to @a ValueType
  2877. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2878. @liveexample{The example below shows several conversions from JSON values
  2879. to other types. There a few things to note: (1) Floating-point numbers can
  2880. be converted to integers\, (2) A JSON array can be converted to a standard
  2881. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2882. associative containers such as `std::unordered_map<std::string\,
  2883. json>`.,get__ValueType_const}
  2884. @since version 2.1.0
  2885. */
  2886. template <
  2887. typename ValueTypeCV,
  2888. typename ValueType = detail::uncvref_t<ValueTypeCV>,
  2889. detail::enable_if_t <
  2890. not std::is_same<basic_json_t, ValueType>::value and
  2891. detail::has_from_json<basic_json_t, ValueType>::value and
  2892. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  2893. int > = 0 >
  2894. ValueType get() const noexcept(noexcept(
  2895. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  2896. {
  2897. // we cannot static_assert on ValueTypeCV being non-const, because
  2898. // there is support for get<const basic_json_t>(), which is why we
  2899. // still need the uncvref
  2900. static_assert(not std::is_reference<ValueTypeCV>::value,
  2901. "get() cannot be used with reference types, you might want to use get_ref()");
  2902. static_assert(std::is_default_constructible<ValueType>::value,
  2903. "types must be DefaultConstructible when used with get()");
  2904. ValueType ret;
  2905. JSONSerializer<ValueType>::from_json(*this, ret);
  2906. return ret;
  2907. }
  2908. /*!
  2909. @brief get a value (explicit); special case
  2910. Explicit type conversion between the JSON value and a compatible value
  2911. which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  2912. and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  2913. The value is converted by calling the @ref json_serializer<ValueType>
  2914. `from_json()` method.
  2915. The function is equivalent to executing
  2916. @code {.cpp}
  2917. return JSONSerializer<ValueTypeCV>::from_json(*this);
  2918. @endcode
  2919. This overloads is chosen if:
  2920. - @a ValueType is not @ref basic_json and
  2921. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2922. `ValueType from_json(const basic_json&)`
  2923. @note If @ref json_serializer<ValueType> has both overloads of
  2924. `from_json()`, this one is chosen.
  2925. @tparam ValueTypeCV the provided value type
  2926. @tparam ValueType the returned value type
  2927. @return copy of the JSON value, converted to @a ValueType
  2928. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2929. @since version 2.1.0
  2930. */
  2931. template <
  2932. typename ValueTypeCV,
  2933. typename ValueType = detail::uncvref_t<ValueTypeCV>,
  2934. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  2935. detail::has_non_default_from_json<basic_json_t,
  2936. ValueType>::value, int> = 0 >
  2937. ValueType get() const noexcept(noexcept(
  2938. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  2939. {
  2940. static_assert(not std::is_reference<ValueTypeCV>::value,
  2941. "get() cannot be used with reference types, you might want to use get_ref()");
  2942. return JSONSerializer<ValueTypeCV>::from_json(*this);
  2943. }
  2944. /*!
  2945. @brief get a pointer value (explicit)
  2946. Explicit pointer access to the internally stored JSON value. No copies are
  2947. made.
  2948. @warning The pointer becomes invalid if the underlying JSON object
  2949. changes.
  2950. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2951. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2952. @ref number_unsigned_t, or @ref number_float_t.
  2953. @return pointer to the internally stored JSON value if the requested
  2954. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2955. @complexity Constant.
  2956. @liveexample{The example below shows how pointers to internal values of a
  2957. JSON value can be requested. Note that no type conversions are made and a
  2958. `nullptr` is returned if the value and the requested pointer type does not
  2959. match.,get__PointerType}
  2960. @sa @ref get_ptr() for explicit pointer-member access
  2961. @since version 1.0.0
  2962. */
  2963. template<typename PointerType, typename std::enable_if<
  2964. std::is_pointer<PointerType>::value, int>::type = 0>
  2965. PointerType get() noexcept
  2966. {
  2967. // delegate the call to get_ptr
  2968. return get_ptr<PointerType>();
  2969. }
  2970. /*!
  2971. @brief get a pointer value (explicit)
  2972. @copydoc get()
  2973. */
  2974. template<typename PointerType, typename std::enable_if<
  2975. std::is_pointer<PointerType>::value, int>::type = 0>
  2976. constexpr const PointerType get() const noexcept
  2977. {
  2978. // delegate the call to get_ptr
  2979. return get_ptr<PointerType>();
  2980. }
  2981. /*!
  2982. @brief get a pointer value (implicit)
  2983. Implicit pointer access to the internally stored JSON value. No copies are
  2984. made.
  2985. @warning Writing data to the pointee of the result yields an undefined
  2986. state.
  2987. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2988. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2989. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  2990. assertion.
  2991. @return pointer to the internally stored JSON value if the requested
  2992. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2993. @complexity Constant.
  2994. @liveexample{The example below shows how pointers to internal values of a
  2995. JSON value can be requested. Note that no type conversions are made and a
  2996. `nullptr` is returned if the value and the requested pointer type does not
  2997. match.,get_ptr}
  2998. @since version 1.0.0
  2999. */
  3000. template<typename PointerType, typename std::enable_if<
  3001. std::is_pointer<PointerType>::value, int>::type = 0>
  3002. PointerType get_ptr() noexcept
  3003. {
  3004. // get the type of the PointerType (remove pointer and const)
  3005. using pointee_t = typename std::remove_const<typename
  3006. std::remove_pointer<typename
  3007. std::remove_const<PointerType>::type>::type>::type;
  3008. // make sure the type matches the allowed types
  3009. static_assert(
  3010. std::is_same<object_t, pointee_t>::value
  3011. or std::is_same<array_t, pointee_t>::value
  3012. or std::is_same<string_t, pointee_t>::value
  3013. or std::is_same<boolean_t, pointee_t>::value
  3014. or std::is_same<number_integer_t, pointee_t>::value
  3015. or std::is_same<number_unsigned_t, pointee_t>::value
  3016. or std::is_same<number_float_t, pointee_t>::value
  3017. , "incompatible pointer type");
  3018. // delegate the call to get_impl_ptr<>()
  3019. return get_impl_ptr(static_cast<PointerType>(nullptr));
  3020. }
  3021. /*!
  3022. @brief get a pointer value (implicit)
  3023. @copydoc get_ptr()
  3024. */
  3025. template<typename PointerType, typename std::enable_if<
  3026. std::is_pointer<PointerType>::value and
  3027. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  3028. constexpr const PointerType get_ptr() const noexcept
  3029. {
  3030. // get the type of the PointerType (remove pointer and const)
  3031. using pointee_t = typename std::remove_const<typename
  3032. std::remove_pointer<typename
  3033. std::remove_const<PointerType>::type>::type>::type;
  3034. // make sure the type matches the allowed types
  3035. static_assert(
  3036. std::is_same<object_t, pointee_t>::value
  3037. or std::is_same<array_t, pointee_t>::value
  3038. or std::is_same<string_t, pointee_t>::value
  3039. or std::is_same<boolean_t, pointee_t>::value
  3040. or std::is_same<number_integer_t, pointee_t>::value
  3041. or std::is_same<number_unsigned_t, pointee_t>::value
  3042. or std::is_same<number_float_t, pointee_t>::value
  3043. , "incompatible pointer type");
  3044. // delegate the call to get_impl_ptr<>() const
  3045. return get_impl_ptr(static_cast<const PointerType>(nullptr));
  3046. }
  3047. /*!
  3048. @brief get a reference value (implicit)
  3049. Implicit reference access to the internally stored JSON value. No copies
  3050. are made.
  3051. @warning Writing data to the referee of the result yields an undefined
  3052. state.
  3053. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  3054. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  3055. @ref number_float_t. Enforced by static assertion.
  3056. @return reference to the internally stored JSON value if the requested
  3057. reference type @a ReferenceType fits to the JSON value; throws
  3058. type_error.303 otherwise
  3059. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  3060. with the stored JSON value; see example below
  3061. @complexity Constant.
  3062. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  3063. @since version 1.1.0
  3064. */
  3065. template<typename ReferenceType, typename std::enable_if<
  3066. std::is_reference<ReferenceType>::value, int>::type = 0>
  3067. ReferenceType get_ref()
  3068. {
  3069. // delegate call to get_ref_impl
  3070. return get_ref_impl<ReferenceType>(*this);
  3071. }
  3072. /*!
  3073. @brief get a reference value (implicit)
  3074. @copydoc get_ref()
  3075. */
  3076. template<typename ReferenceType, typename std::enable_if<
  3077. std::is_reference<ReferenceType>::value and
  3078. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  3079. ReferenceType get_ref() const
  3080. {
  3081. // delegate call to get_ref_impl
  3082. return get_ref_impl<ReferenceType>(*this);
  3083. }
  3084. /*!
  3085. @brief get a value (implicit)
  3086. Implicit type conversion between the JSON value and a compatible value.
  3087. The call is realized by calling @ref get() const.
  3088. @tparam ValueType non-pointer type compatible to the JSON value, for
  3089. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  3090. `std::vector` types for JSON arrays. The character type of @ref string_t
  3091. as well as an initializer list of this type is excluded to avoid
  3092. ambiguities as these types implicitly convert to `std::string`.
  3093. @return copy of the JSON value, converted to type @a ValueType
  3094. @throw type_error.302 in case passed type @a ValueType is incompatible
  3095. to the JSON value type (e.g., the JSON value is of type boolean, but a
  3096. string is requested); see example below
  3097. @complexity Linear in the size of the JSON value.
  3098. @liveexample{The example below shows several conversions from JSON values
  3099. to other types. There a few things to note: (1) Floating-point numbers can
  3100. be converted to integers\, (2) A JSON array can be converted to a standard
  3101. `std::vector<short>`\, (3) A JSON object can be converted to C++
  3102. associative containers such as `std::unordered_map<std::string\,
  3103. json>`.,operator__ValueType}
  3104. @since version 1.0.0
  3105. */
  3106. template < typename ValueType, typename std::enable_if <
  3107. not std::is_pointer<ValueType>::value and
  3108. not std::is_same<ValueType, typename string_t::value_type>::value
  3109. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  3110. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  3111. #endif
  3112. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSC_VER) && _MSC_VER >1900 && defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  3113. and not std::is_same<ValueType, typename std::string_view>::value
  3114. #endif
  3115. , int >::type = 0 >
  3116. operator ValueType() const
  3117. {
  3118. // delegate the call to get<>() const
  3119. return get<ValueType>();
  3120. }
  3121. /// @}
  3122. ////////////////////
  3123. // element access //
  3124. ////////////////////
  3125. /// @name element access
  3126. /// Access to the JSON value.
  3127. /// @{
  3128. /*!
  3129. @brief access specified array element with bounds checking
  3130. Returns a reference to the element at specified location @a idx, with
  3131. bounds checking.
  3132. @param[in] idx index of the element to access
  3133. @return reference to the element at index @a idx
  3134. @throw type_error.304 if the JSON value is not an array; in this case,
  3135. calling `at` with an index makes no sense. See example below.
  3136. @throw out_of_range.401 if the index @a idx is out of range of the array;
  3137. that is, `idx >= size()`. See example below.
  3138. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3139. changes in the JSON value.
  3140. @complexity Constant.
  3141. @since version 1.0.0
  3142. @liveexample{The example below shows how array elements can be read and
  3143. written using `at()`. It also demonstrates the different exceptions that
  3144. can be thrown.,at__size_type}
  3145. */
  3146. reference at(size_type idx)
  3147. {
  3148. // at only works for arrays
  3149. if (is_array())
  3150. {
  3151. JSON_TRY
  3152. {
  3153. return m_value.array->at(idx);
  3154. }
  3155. JSON_CATCH (std::out_of_range&)
  3156. {
  3157. // create better exception explanation
  3158. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3159. }
  3160. }
  3161. else
  3162. {
  3163. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3164. }
  3165. }
  3166. /*!
  3167. @brief access specified array element with bounds checking
  3168. Returns a const reference to the element at specified location @a idx,
  3169. with bounds checking.
  3170. @param[in] idx index of the element to access
  3171. @return const reference to the element at index @a idx
  3172. @throw type_error.304 if the JSON value is not an array; in this case,
  3173. calling `at` with an index makes no sense. See example below.
  3174. @throw out_of_range.401 if the index @a idx is out of range of the array;
  3175. that is, `idx >= size()`. See example below.
  3176. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3177. changes in the JSON value.
  3178. @complexity Constant.
  3179. @since version 1.0.0
  3180. @liveexample{The example below shows how array elements can be read using
  3181. `at()`. It also demonstrates the different exceptions that can be thrown.,
  3182. at__size_type_const}
  3183. */
  3184. const_reference at(size_type idx) const
  3185. {
  3186. // at only works for arrays
  3187. if (is_array())
  3188. {
  3189. JSON_TRY
  3190. {
  3191. return m_value.array->at(idx);
  3192. }
  3193. JSON_CATCH (std::out_of_range&)
  3194. {
  3195. // create better exception explanation
  3196. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3197. }
  3198. }
  3199. else
  3200. {
  3201. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3202. }
  3203. }
  3204. /*!
  3205. @brief access specified object element with bounds checking
  3206. Returns a reference to the element at with specified key @a key, with
  3207. bounds checking.
  3208. @param[in] key key of the element to access
  3209. @return reference to the element at key @a key
  3210. @throw type_error.304 if the JSON value is not an object; in this case,
  3211. calling `at` with a key makes no sense. See example below.
  3212. @throw out_of_range.403 if the key @a key is is not stored in the object;
  3213. that is, `find(key) == end()`. See example below.
  3214. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3215. changes in the JSON value.
  3216. @complexity Logarithmic in the size of the container.
  3217. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  3218. access by reference
  3219. @sa @ref value() for access by value with a default value
  3220. @since version 1.0.0
  3221. @liveexample{The example below shows how object elements can be read and
  3222. written using `at()`. It also demonstrates the different exceptions that
  3223. can be thrown.,at__object_t_key_type}
  3224. */
  3225. reference at(const typename object_t::key_type& key)
  3226. {
  3227. // at only works for objects
  3228. if (is_object())
  3229. {
  3230. JSON_TRY
  3231. {
  3232. return m_value.object->at(key);
  3233. }
  3234. JSON_CATCH (std::out_of_range&)
  3235. {
  3236. // create better exception explanation
  3237. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  3238. }
  3239. }
  3240. else
  3241. {
  3242. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3243. }
  3244. }
  3245. /*!
  3246. @brief access specified object element with bounds checking
  3247. Returns a const reference to the element at with specified key @a key,
  3248. with bounds checking.
  3249. @param[in] key key of the element to access
  3250. @return const reference to the element at key @a key
  3251. @throw type_error.304 if the JSON value is not an object; in this case,
  3252. calling `at` with a key makes no sense. See example below.
  3253. @throw out_of_range.403 if the key @a key is is not stored in the object;
  3254. that is, `find(key) == end()`. See example below.
  3255. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3256. changes in the JSON value.
  3257. @complexity Logarithmic in the size of the container.
  3258. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  3259. access by reference
  3260. @sa @ref value() for access by value with a default value
  3261. @since version 1.0.0
  3262. @liveexample{The example below shows how object elements can be read using
  3263. `at()`. It also demonstrates the different exceptions that can be thrown.,
  3264. at__object_t_key_type_const}
  3265. */
  3266. const_reference at(const typename object_t::key_type& key) const
  3267. {
  3268. // at only works for objects
  3269. if (is_object())
  3270. {
  3271. JSON_TRY
  3272. {
  3273. return m_value.object->at(key);
  3274. }
  3275. JSON_CATCH (std::out_of_range&)
  3276. {
  3277. // create better exception explanation
  3278. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  3279. }
  3280. }
  3281. else
  3282. {
  3283. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3284. }
  3285. }
  3286. /*!
  3287. @brief access specified array element
  3288. Returns a reference to the element at specified location @a idx.
  3289. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  3290. then the array is silently filled up with `null` values to make `idx` a
  3291. valid reference to the last stored element.
  3292. @param[in] idx index of the element to access
  3293. @return reference to the element at index @a idx
  3294. @throw type_error.305 if the JSON value is not an array or null; in that
  3295. cases, using the [] operator with an index makes no sense.
  3296. @complexity Constant if @a idx is in the range of the array. Otherwise
  3297. linear in `idx - size()`.
  3298. @liveexample{The example below shows how array elements can be read and
  3299. written using `[]` operator. Note the addition of `null`
  3300. values.,operatorarray__size_type}
  3301. @since version 1.0.0
  3302. */
  3303. reference operator[](size_type idx)
  3304. {
  3305. // implicitly convert null value to an empty array
  3306. if (is_null())
  3307. {
  3308. m_type = value_t::array;
  3309. m_value.array = create<array_t>();
  3310. assert_invariant();
  3311. }
  3312. // operator[] only works for arrays
  3313. if (is_array())
  3314. {
  3315. // fill up array with null values if given idx is outside range
  3316. if (idx >= m_value.array->size())
  3317. {
  3318. m_value.array->insert(m_value.array->end(),
  3319. idx - m_value.array->size() + 1,
  3320. basic_json());
  3321. }
  3322. return m_value.array->operator[](idx);
  3323. }
  3324. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3325. }
  3326. /*!
  3327. @brief access specified array element
  3328. Returns a const reference to the element at specified location @a idx.
  3329. @param[in] idx index of the element to access
  3330. @return const reference to the element at index @a idx
  3331. @throw type_error.305 if the JSON value is not an array; in that cases,
  3332. using the [] operator with an index makes no sense.
  3333. @complexity Constant.
  3334. @liveexample{The example below shows how array elements can be read using
  3335. the `[]` operator.,operatorarray__size_type_const}
  3336. @since version 1.0.0
  3337. */
  3338. const_reference operator[](size_type idx) const
  3339. {
  3340. // const operator[] only works for arrays
  3341. if (is_array())
  3342. {
  3343. return m_value.array->operator[](idx);
  3344. }
  3345. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3346. }
  3347. /*!
  3348. @brief access specified object element
  3349. Returns a reference to the element at with specified key @a key.
  3350. @note If @a key is not found in the object, then it is silently added to
  3351. the object and filled with a `null` value to make `key` a valid reference.
  3352. In case the value was `null` before, it is converted to an object.
  3353. @param[in] key key of the element to access
  3354. @return reference to the element at key @a key
  3355. @throw type_error.305 if the JSON value is not an object or null; in that
  3356. cases, using the [] operator with a key makes no sense.
  3357. @complexity Logarithmic in the size of the container.
  3358. @liveexample{The example below shows how object elements can be read and
  3359. written using the `[]` operator.,operatorarray__key_type}
  3360. @sa @ref at(const typename object_t::key_type&) for access by reference
  3361. with range checking
  3362. @sa @ref value() for access by value with a default value
  3363. @since version 1.0.0
  3364. */
  3365. reference operator[](const typename object_t::key_type& key)
  3366. {
  3367. // implicitly convert null value to an empty object
  3368. if (is_null())
  3369. {
  3370. m_type = value_t::object;
  3371. m_value.object = create<object_t>();
  3372. assert_invariant();
  3373. }
  3374. // operator[] only works for objects
  3375. if (is_object())
  3376. {
  3377. return m_value.object->operator[](key);
  3378. }
  3379. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3380. }
  3381. /*!
  3382. @brief read-only access specified object element
  3383. Returns a const reference to the element at with specified key @a key. No
  3384. bounds checking is performed.
  3385. @warning If the element with key @a key does not exist, the behavior is
  3386. undefined.
  3387. @param[in] key key of the element to access
  3388. @return const reference to the element at key @a key
  3389. @pre The element with key @a key must exist. **This precondition is
  3390. enforced with an assertion.**
  3391. @throw type_error.305 if the JSON value is not an object; in that cases,
  3392. using the [] operator with a key makes no sense.
  3393. @complexity Logarithmic in the size of the container.
  3394. @liveexample{The example below shows how object elements can be read using
  3395. the `[]` operator.,operatorarray__key_type_const}
  3396. @sa @ref at(const typename object_t::key_type&) for access by reference
  3397. with range checking
  3398. @sa @ref value() for access by value with a default value
  3399. @since version 1.0.0
  3400. */
  3401. const_reference operator[](const typename object_t::key_type& key) const
  3402. {
  3403. // const operator[] only works for objects
  3404. if (is_object())
  3405. {
  3406. assert(m_value.object->find(key) != m_value.object->end());
  3407. return m_value.object->find(key)->second;
  3408. }
  3409. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3410. }
  3411. /*!
  3412. @brief access specified object element
  3413. Returns a reference to the element at with specified key @a key.
  3414. @note If @a key is not found in the object, then it is silently added to
  3415. the object and filled with a `null` value to make `key` a valid reference.
  3416. In case the value was `null` before, it is converted to an object.
  3417. @param[in] key key of the element to access
  3418. @return reference to the element at key @a key
  3419. @throw type_error.305 if the JSON value is not an object or null; in that
  3420. cases, using the [] operator with a key makes no sense.
  3421. @complexity Logarithmic in the size of the container.
  3422. @liveexample{The example below shows how object elements can be read and
  3423. written using the `[]` operator.,operatorarray__key_type}
  3424. @sa @ref at(const typename object_t::key_type&) for access by reference
  3425. with range checking
  3426. @sa @ref value() for access by value with a default value
  3427. @since version 1.1.0
  3428. */
  3429. template<typename T>
  3430. reference operator[](T* key)
  3431. {
  3432. // implicitly convert null to object
  3433. if (is_null())
  3434. {
  3435. m_type = value_t::object;
  3436. m_value = value_t::object;
  3437. assert_invariant();
  3438. }
  3439. // at only works for objects
  3440. if (is_object())
  3441. {
  3442. return m_value.object->operator[](key);
  3443. }
  3444. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3445. }
  3446. /*!
  3447. @brief read-only access specified object element
  3448. Returns a const reference to the element at with specified key @a key. No
  3449. bounds checking is performed.
  3450. @warning If the element with key @a key does not exist, the behavior is
  3451. undefined.
  3452. @param[in] key key of the element to access
  3453. @return const reference to the element at key @a key
  3454. @pre The element with key @a key must exist. **This precondition is
  3455. enforced with an assertion.**
  3456. @throw type_error.305 if the JSON value is not an object; in that cases,
  3457. using the [] operator with a key makes no sense.
  3458. @complexity Logarithmic in the size of the container.
  3459. @liveexample{The example below shows how object elements can be read using
  3460. the `[]` operator.,operatorarray__key_type_const}
  3461. @sa @ref at(const typename object_t::key_type&) for access by reference
  3462. with range checking
  3463. @sa @ref value() for access by value with a default value
  3464. @since version 1.1.0
  3465. */
  3466. template<typename T>
  3467. const_reference operator[](T* key) const
  3468. {
  3469. // at only works for objects
  3470. if (is_object())
  3471. {
  3472. assert(m_value.object->find(key) != m_value.object->end());
  3473. return m_value.object->find(key)->second;
  3474. }
  3475. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3476. }
  3477. /*!
  3478. @brief access specified object element with default value
  3479. Returns either a copy of an object's element at the specified key @a key
  3480. or a given default value if no element with key @a key exists.
  3481. The function is basically equivalent to executing
  3482. @code {.cpp}
  3483. try {
  3484. return at(key);
  3485. } catch(out_of_range) {
  3486. return default_value;
  3487. }
  3488. @endcode
  3489. @note Unlike @ref at(const typename object_t::key_type&), this function
  3490. does not throw if the given key @a key was not found.
  3491. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  3492. function does not implicitly add an element to the position defined by @a
  3493. key. This function is furthermore also applicable to const objects.
  3494. @param[in] key key of the element to access
  3495. @param[in] default_value the value to return if @a key is not found
  3496. @tparam ValueType type compatible to JSON values, for instance `int` for
  3497. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  3498. JSON arrays. Note the type of the expected value at @a key and the default
  3499. value @a default_value must be compatible.
  3500. @return copy of the element at key @a key or @a default_value if @a key
  3501. is not found
  3502. @throw type_error.306 if the JSON value is not an objec; in that cases,
  3503. using `value()` with a key makes no sense.
  3504. @complexity Logarithmic in the size of the container.
  3505. @liveexample{The example below shows how object elements can be queried
  3506. with a default value.,basic_json__value}
  3507. @sa @ref at(const typename object_t::key_type&) for access by reference
  3508. with range checking
  3509. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  3510. access by reference
  3511. @since version 1.0.0
  3512. */
  3513. template<class ValueType, typename std::enable_if<
  3514. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  3515. ValueType value(const typename object_t::key_type& key, ValueType default_value) const
  3516. {
  3517. // at only works for objects
  3518. if (is_object())
  3519. {
  3520. // if key is found, return value and given default value otherwise
  3521. const auto it = find(key);
  3522. if (it != end())
  3523. {
  3524. return *it;
  3525. }
  3526. return default_value;
  3527. }
  3528. else
  3529. {
  3530. JSON_THROW(type_error::create(306, "cannot use value() with " + type_name()));
  3531. }
  3532. }
  3533. /*!
  3534. @brief overload for a default value of type const char*
  3535. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  3536. */
  3537. string_t value(const typename object_t::key_type& key, const char* default_value) const
  3538. {
  3539. return value(key, string_t(default_value));
  3540. }
  3541. /*!
  3542. @brief access specified object element via JSON Pointer with default value
  3543. Returns either a copy of an object's element at the specified key @a key
  3544. or a given default value if no element with key @a key exists.
  3545. The function is basically equivalent to executing
  3546. @code {.cpp}
  3547. try {
  3548. return at(ptr);
  3549. } catch(out_of_range) {
  3550. return default_value;
  3551. }
  3552. @endcode
  3553. @note Unlike @ref at(const json_pointer&), this function does not throw
  3554. if the given key @a key was not found.
  3555. @param[in] ptr a JSON pointer to the element to access
  3556. @param[in] default_value the value to return if @a ptr found no value
  3557. @tparam ValueType type compatible to JSON values, for instance `int` for
  3558. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  3559. JSON arrays. Note the type of the expected value at @a key and the default
  3560. value @a default_value must be compatible.
  3561. @return copy of the element at key @a key or @a default_value if @a key
  3562. is not found
  3563. @throw type_error.306 if the JSON value is not an objec; in that cases,
  3564. using `value()` with a key makes no sense.
  3565. @complexity Logarithmic in the size of the container.
  3566. @liveexample{The example below shows how object elements can be queried
  3567. with a default value.,basic_json__value_ptr}
  3568. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  3569. @since version 2.0.2
  3570. */
  3571. template<class ValueType, typename std::enable_if<
  3572. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  3573. ValueType value(const json_pointer& ptr, ValueType default_value) const
  3574. {
  3575. // at only works for objects
  3576. if (is_object())
  3577. {
  3578. // if pointer resolves a value, return it or use default value
  3579. JSON_TRY
  3580. {
  3581. return ptr.get_checked(this);
  3582. }
  3583. JSON_CATCH (out_of_range&)
  3584. {
  3585. return default_value;
  3586. }
  3587. }
  3588. JSON_THROW(type_error::create(306, "cannot use value() with " + type_name()));
  3589. }
  3590. /*!
  3591. @brief overload for a default value of type const char*
  3592. @copydoc basic_json::value(const json_pointer&, ValueType) const
  3593. */
  3594. string_t value(const json_pointer& ptr, const char* default_value) const
  3595. {
  3596. return value(ptr, string_t(default_value));
  3597. }
  3598. /*!
  3599. @brief access the first element
  3600. Returns a reference to the first element in the container. For a JSON
  3601. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  3602. @return In case of a structured type (array or object), a reference to the
  3603. first element is returned. In case of number, string, or boolean values, a
  3604. reference to the value is returned.
  3605. @complexity Constant.
  3606. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3607. or an empty array or object (undefined behavior, **guarded by
  3608. assertions**).
  3609. @post The JSON value remains unchanged.
  3610. @throw invalid_iterator.214 when called on `null` value
  3611. @liveexample{The following code shows an example for `front()`.,front}
  3612. @sa @ref back() -- access the last element
  3613. @since version 1.0.0
  3614. */
  3615. reference front()
  3616. {
  3617. return *begin();
  3618. }
  3619. /*!
  3620. @copydoc basic_json::front()
  3621. */
  3622. const_reference front() const
  3623. {
  3624. return *cbegin();
  3625. }
  3626. /*!
  3627. @brief access the last element
  3628. Returns a reference to the last element in the container. For a JSON
  3629. container `c`, the expression `c.back()` is equivalent to
  3630. @code {.cpp}
  3631. auto tmp = c.end();
  3632. --tmp;
  3633. return *tmp;
  3634. @endcode
  3635. @return In case of a structured type (array or object), a reference to the
  3636. last element is returned. In case of number, string, or boolean values, a
  3637. reference to the value is returned.
  3638. @complexity Constant.
  3639. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3640. or an empty array or object (undefined behavior, **guarded by
  3641. assertions**).
  3642. @post The JSON value remains unchanged.
  3643. @throw invalid_iterator.214 when called on a `null` value. See example
  3644. below.
  3645. @liveexample{The following code shows an example for `back()`.,back}
  3646. @sa @ref front() -- access the first element
  3647. @since version 1.0.0
  3648. */
  3649. reference back()
  3650. {
  3651. auto tmp = end();
  3652. --tmp;
  3653. return *tmp;
  3654. }
  3655. /*!
  3656. @copydoc basic_json::back()
  3657. */
  3658. const_reference back() const
  3659. {
  3660. auto tmp = cend();
  3661. --tmp;
  3662. return *tmp;
  3663. }
  3664. /*!
  3665. @brief remove element given an iterator
  3666. Removes the element specified by iterator @a pos. The iterator @a pos must
  3667. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  3668. but is not dereferenceable) cannot be used as a value for @a pos.
  3669. If called on a primitive type other than `null`, the resulting JSON value
  3670. will be `null`.
  3671. @param[in] pos iterator to the element to remove
  3672. @return Iterator following the last removed element. If the iterator @a
  3673. pos refers to the last element, the `end()` iterator is returned.
  3674. @tparam IteratorType an @ref iterator or @ref const_iterator
  3675. @post Invalidates iterators and references at or after the point of the
  3676. erase, including the `end()` iterator.
  3677. @throw type_error.307 if called on a `null` value; example: `"cannot use
  3678. erase() with null"`
  3679. @throw invalid_iterator.202 if called on an iterator which does not belong
  3680. to the current JSON value; example: `"iterator does not fit current
  3681. value"`
  3682. @throw invalid_iterator.205 if called on a primitive type with invalid
  3683. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  3684. out of range"`
  3685. @complexity The complexity depends on the type:
  3686. - objects: amortized constant
  3687. - arrays: linear in distance between @a pos and the end of the container
  3688. - strings: linear in the length of the string
  3689. - other types: constant
  3690. @liveexample{The example shows the result of `erase()` for different JSON
  3691. types.,erase__IteratorType}
  3692. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3693. the given range
  3694. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3695. from an object at the given key
  3696. @sa @ref erase(const size_type) -- removes the element from an array at
  3697. the given index
  3698. @since version 1.0.0
  3699. */
  3700. template<class IteratorType, typename std::enable_if<
  3701. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3702. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3703. = 0>
  3704. IteratorType erase(IteratorType pos)
  3705. {
  3706. // make sure iterator fits the current value
  3707. if (this != pos.m_object)
  3708. {
  3709. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  3710. }
  3711. IteratorType result = end();
  3712. switch (m_type)
  3713. {
  3714. case value_t::boolean:
  3715. case value_t::number_float:
  3716. case value_t::number_integer:
  3717. case value_t::number_unsigned:
  3718. case value_t::string:
  3719. {
  3720. if (not pos.m_it.primitive_iterator.is_begin())
  3721. {
  3722. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  3723. }
  3724. if (is_string())
  3725. {
  3726. AllocatorType<string_t> alloc;
  3727. alloc.destroy(m_value.string);
  3728. alloc.deallocate(m_value.string, 1);
  3729. m_value.string = nullptr;
  3730. }
  3731. m_type = value_t::null;
  3732. assert_invariant();
  3733. break;
  3734. }
  3735. case value_t::object:
  3736. {
  3737. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  3738. break;
  3739. }
  3740. case value_t::array:
  3741. {
  3742. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  3743. break;
  3744. }
  3745. default:
  3746. {
  3747. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3748. }
  3749. }
  3750. return result;
  3751. }
  3752. /*!
  3753. @brief remove elements given an iterator range
  3754. Removes the element specified by the range `[first; last)`. The iterator
  3755. @a first does not need to be dereferenceable if `first == last`: erasing
  3756. an empty range is a no-op.
  3757. If called on a primitive type other than `null`, the resulting JSON value
  3758. will be `null`.
  3759. @param[in] first iterator to the beginning of the range to remove
  3760. @param[in] last iterator past the end of the range to remove
  3761. @return Iterator following the last removed element. If the iterator @a
  3762. second refers to the last element, the `end()` iterator is returned.
  3763. @tparam IteratorType an @ref iterator or @ref const_iterator
  3764. @post Invalidates iterators and references at or after the point of the
  3765. erase, including the `end()` iterator.
  3766. @throw type_error.307 if called on a `null` value; example: `"cannot use
  3767. erase() with null"`
  3768. @throw invalid_iterator.203 if called on iterators which does not belong
  3769. to the current JSON value; example: `"iterators do not fit current value"`
  3770. @throw invalid_iterator.204 if called on a primitive type with invalid
  3771. iterators (i.e., if `first != begin()` and `last != end()`); example:
  3772. `"iterators out of range"`
  3773. @complexity The complexity depends on the type:
  3774. - objects: `log(size()) + std::distance(first, last)`
  3775. - arrays: linear in the distance between @a first and @a last, plus linear
  3776. in the distance between @a last and end of the container
  3777. - strings: linear in the length of the string
  3778. - other types: constant
  3779. @liveexample{The example shows the result of `erase()` for different JSON
  3780. types.,erase__IteratorType_IteratorType}
  3781. @sa @ref erase(IteratorType) -- removes the element at a given position
  3782. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3783. from an object at the given key
  3784. @sa @ref erase(const size_type) -- removes the element from an array at
  3785. the given index
  3786. @since version 1.0.0
  3787. */
  3788. template<class IteratorType, typename std::enable_if<
  3789. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3790. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3791. = 0>
  3792. IteratorType erase(IteratorType first, IteratorType last)
  3793. {
  3794. // make sure iterator fits the current value
  3795. if (this != first.m_object or this != last.m_object)
  3796. {
  3797. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  3798. }
  3799. IteratorType result = end();
  3800. switch (m_type)
  3801. {
  3802. case value_t::boolean:
  3803. case value_t::number_float:
  3804. case value_t::number_integer:
  3805. case value_t::number_unsigned:
  3806. case value_t::string:
  3807. {
  3808. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  3809. {
  3810. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  3811. }
  3812. if (is_string())
  3813. {
  3814. AllocatorType<string_t> alloc;
  3815. alloc.destroy(m_value.string);
  3816. alloc.deallocate(m_value.string, 1);
  3817. m_value.string = nullptr;
  3818. }
  3819. m_type = value_t::null;
  3820. assert_invariant();
  3821. break;
  3822. }
  3823. case value_t::object:
  3824. {
  3825. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  3826. last.m_it.object_iterator);
  3827. break;
  3828. }
  3829. case value_t::array:
  3830. {
  3831. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  3832. last.m_it.array_iterator);
  3833. break;
  3834. }
  3835. default:
  3836. {
  3837. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3838. }
  3839. }
  3840. return result;
  3841. }
  3842. /*!
  3843. @brief remove element from a JSON object given a key
  3844. Removes elements from a JSON object with the key value @a key.
  3845. @param[in] key value of the elements to remove
  3846. @return Number of elements removed. If @a ObjectType is the default
  3847. `std::map` type, the return value will always be `0` (@a key was not
  3848. found) or `1` (@a key was found).
  3849. @post References and iterators to the erased elements are invalidated.
  3850. Other references and iterators are not affected.
  3851. @throw type_error.307 when called on a type other than JSON object;
  3852. example: `"cannot use erase() with null"`
  3853. @complexity `log(size()) + count(key)`
  3854. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  3855. @sa @ref erase(IteratorType) -- removes the element at a given position
  3856. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3857. the given range
  3858. @sa @ref erase(const size_type) -- removes the element from an array at
  3859. the given index
  3860. @since version 1.0.0
  3861. */
  3862. size_type erase(const typename object_t::key_type& key)
  3863. {
  3864. // this erase only works for objects
  3865. if (is_object())
  3866. {
  3867. return m_value.object->erase(key);
  3868. }
  3869. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3870. }
  3871. /*!
  3872. @brief remove element from a JSON array given an index
  3873. Removes element from a JSON array at the index @a idx.
  3874. @param[in] idx index of the element to remove
  3875. @throw type_error.307 when called on a type other than JSON object;
  3876. example: `"cannot use erase() with null"`
  3877. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  3878. is out of range"`
  3879. @complexity Linear in distance between @a idx and the end of the container.
  3880. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  3881. @sa @ref erase(IteratorType) -- removes the element at a given position
  3882. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3883. the given range
  3884. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3885. from an object at the given key
  3886. @since version 1.0.0
  3887. */
  3888. void erase(const size_type idx)
  3889. {
  3890. // this erase only works for arrays
  3891. if (is_array())
  3892. {
  3893. if (idx >= size())
  3894. {
  3895. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3896. }
  3897. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  3898. }
  3899. else
  3900. {
  3901. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3902. }
  3903. }
  3904. /// @}
  3905. ////////////
  3906. // lookup //
  3907. ////////////
  3908. /// @name lookup
  3909. /// @{
  3910. /*!
  3911. @brief find an element in a JSON object
  3912. Finds an element in a JSON object with key equivalent to @a key. If the
  3913. element is not found or the JSON value is not an object, end() is
  3914. returned.
  3915. @note This method always returns @ref end() when executed on a JSON type
  3916. that is not an object.
  3917. @param[in] key key value of the element to search for
  3918. @return Iterator to an element with key equivalent to @a key. If no such
  3919. element is found or the JSON value is not an object, past-the-end (see
  3920. @ref end()) iterator is returned.
  3921. @complexity Logarithmic in the size of the JSON object.
  3922. @liveexample{The example shows how `find()` is used.,find__key_type}
  3923. @since version 1.0.0
  3924. */
  3925. iterator find(typename object_t::key_type key)
  3926. {
  3927. auto result = end();
  3928. if (is_object())
  3929. {
  3930. result.m_it.object_iterator = m_value.object->find(key);
  3931. }
  3932. return result;
  3933. }
  3934. /*!
  3935. @brief find an element in a JSON object
  3936. @copydoc find(typename object_t::key_type)
  3937. */
  3938. const_iterator find(typename object_t::key_type key) const
  3939. {
  3940. auto result = cend();
  3941. if (is_object())
  3942. {
  3943. result.m_it.object_iterator = m_value.object->find(key);
  3944. }
  3945. return result;
  3946. }
  3947. /*!
  3948. @brief returns the number of occurrences of a key in a JSON object
  3949. Returns the number of elements with key @a key. If ObjectType is the
  3950. default `std::map` type, the return value will always be `0` (@a key was
  3951. not found) or `1` (@a key was found).
  3952. @note This method always returns `0` when executed on a JSON type that is
  3953. not an object.
  3954. @param[in] key key value of the element to count
  3955. @return Number of elements with key @a key. If the JSON value is not an
  3956. object, the return value will be `0`.
  3957. @complexity Logarithmic in the size of the JSON object.
  3958. @liveexample{The example shows how `count()` is used.,count}
  3959. @since version 1.0.0
  3960. */
  3961. size_type count(typename object_t::key_type key) const
  3962. {
  3963. // return 0 for all nonobject types
  3964. return is_object() ? m_value.object->count(key) : 0;
  3965. }
  3966. /// @}
  3967. ///////////////
  3968. // iterators //
  3969. ///////////////
  3970. /// @name iterators
  3971. /// @{
  3972. /*!
  3973. @brief returns an iterator to the first element
  3974. Returns an iterator to the first element.
  3975. @image html range-begin-end.svg "Illustration from cppreference.com"
  3976. @return iterator to the first element
  3977. @complexity Constant.
  3978. @requirement This function helps `basic_json` satisfying the
  3979. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3980. requirements:
  3981. - The complexity is constant.
  3982. @liveexample{The following code shows an example for `begin()`.,begin}
  3983. @sa @ref cbegin() -- returns a const iterator to the beginning
  3984. @sa @ref end() -- returns an iterator to the end
  3985. @sa @ref cend() -- returns a const iterator to the end
  3986. @since version 1.0.0
  3987. */
  3988. iterator begin() noexcept
  3989. {
  3990. iterator result(this);
  3991. result.set_begin();
  3992. return result;
  3993. }
  3994. /*!
  3995. @copydoc basic_json::cbegin()
  3996. */
  3997. const_iterator begin() const noexcept
  3998. {
  3999. return cbegin();
  4000. }
  4001. /*!
  4002. @brief returns a const iterator to the first element
  4003. Returns a const iterator to the first element.
  4004. @image html range-begin-end.svg "Illustration from cppreference.com"
  4005. @return const iterator to the first element
  4006. @complexity Constant.
  4007. @requirement This function helps `basic_json` satisfying the
  4008. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4009. requirements:
  4010. - The complexity is constant.
  4011. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  4012. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  4013. @sa @ref begin() -- returns an iterator to the beginning
  4014. @sa @ref end() -- returns an iterator to the end
  4015. @sa @ref cend() -- returns a const iterator to the end
  4016. @since version 1.0.0
  4017. */
  4018. const_iterator cbegin() const noexcept
  4019. {
  4020. const_iterator result(this);
  4021. result.set_begin();
  4022. return result;
  4023. }
  4024. /*!
  4025. @brief returns an iterator to one past the last element
  4026. Returns an iterator to one past the last element.
  4027. @image html range-begin-end.svg "Illustration from cppreference.com"
  4028. @return iterator one past the last element
  4029. @complexity Constant.
  4030. @requirement This function helps `basic_json` satisfying the
  4031. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4032. requirements:
  4033. - The complexity is constant.
  4034. @liveexample{The following code shows an example for `end()`.,end}
  4035. @sa @ref cend() -- returns a const iterator to the end
  4036. @sa @ref begin() -- returns an iterator to the beginning
  4037. @sa @ref cbegin() -- returns a const iterator to the beginning
  4038. @since version 1.0.0
  4039. */
  4040. iterator end() noexcept
  4041. {
  4042. iterator result(this);
  4043. result.set_end();
  4044. return result;
  4045. }
  4046. /*!
  4047. @copydoc basic_json::cend()
  4048. */
  4049. const_iterator end() const noexcept
  4050. {
  4051. return cend();
  4052. }
  4053. /*!
  4054. @brief returns a const iterator to one past the last element
  4055. Returns a const iterator to one past the last element.
  4056. @image html range-begin-end.svg "Illustration from cppreference.com"
  4057. @return const iterator one past the last element
  4058. @complexity Constant.
  4059. @requirement This function helps `basic_json` satisfying the
  4060. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4061. requirements:
  4062. - The complexity is constant.
  4063. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  4064. @liveexample{The following code shows an example for `cend()`.,cend}
  4065. @sa @ref end() -- returns an iterator to the end
  4066. @sa @ref begin() -- returns an iterator to the beginning
  4067. @sa @ref cbegin() -- returns a const iterator to the beginning
  4068. @since version 1.0.0
  4069. */
  4070. const_iterator cend() const noexcept
  4071. {
  4072. const_iterator result(this);
  4073. result.set_end();
  4074. return result;
  4075. }
  4076. /*!
  4077. @brief returns an iterator to the reverse-beginning
  4078. Returns an iterator to the reverse-beginning; that is, the last element.
  4079. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4080. @complexity Constant.
  4081. @requirement This function helps `basic_json` satisfying the
  4082. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4083. requirements:
  4084. - The complexity is constant.
  4085. - Has the semantics of `reverse_iterator(end())`.
  4086. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  4087. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  4088. @sa @ref rend() -- returns a reverse iterator to the end
  4089. @sa @ref crend() -- returns a const reverse iterator to the end
  4090. @since version 1.0.0
  4091. */
  4092. reverse_iterator rbegin() noexcept
  4093. {
  4094. return reverse_iterator(end());
  4095. }
  4096. /*!
  4097. @copydoc basic_json::crbegin()
  4098. */
  4099. const_reverse_iterator rbegin() const noexcept
  4100. {
  4101. return crbegin();
  4102. }
  4103. /*!
  4104. @brief returns an iterator to the reverse-end
  4105. Returns an iterator to the reverse-end; that is, one before the first
  4106. element.
  4107. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4108. @complexity Constant.
  4109. @requirement This function helps `basic_json` satisfying the
  4110. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4111. requirements:
  4112. - The complexity is constant.
  4113. - Has the semantics of `reverse_iterator(begin())`.
  4114. @liveexample{The following code shows an example for `rend()`.,rend}
  4115. @sa @ref crend() -- returns a const reverse iterator to the end
  4116. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  4117. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  4118. @since version 1.0.0
  4119. */
  4120. reverse_iterator rend() noexcept
  4121. {
  4122. return reverse_iterator(begin());
  4123. }
  4124. /*!
  4125. @copydoc basic_json::crend()
  4126. */
  4127. const_reverse_iterator rend() const noexcept
  4128. {
  4129. return crend();
  4130. }
  4131. /*!
  4132. @brief returns a const reverse iterator to the last element
  4133. Returns a const iterator to the reverse-beginning; that is, the last
  4134. element.
  4135. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4136. @complexity Constant.
  4137. @requirement This function helps `basic_json` satisfying the
  4138. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4139. requirements:
  4140. - The complexity is constant.
  4141. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  4142. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  4143. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  4144. @sa @ref rend() -- returns a reverse iterator to the end
  4145. @sa @ref crend() -- returns a const reverse iterator to the end
  4146. @since version 1.0.0
  4147. */
  4148. const_reverse_iterator crbegin() const noexcept
  4149. {
  4150. return const_reverse_iterator(cend());
  4151. }
  4152. /*!
  4153. @brief returns a const reverse iterator to one before the first
  4154. Returns a const reverse iterator to the reverse-end; that is, one before
  4155. the first element.
  4156. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4157. @complexity Constant.
  4158. @requirement This function helps `basic_json` satisfying the
  4159. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4160. requirements:
  4161. - The complexity is constant.
  4162. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  4163. @liveexample{The following code shows an example for `crend()`.,crend}
  4164. @sa @ref rend() -- returns a reverse iterator to the end
  4165. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  4166. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  4167. @since version 1.0.0
  4168. */
  4169. const_reverse_iterator crend() const noexcept
  4170. {
  4171. return const_reverse_iterator(cbegin());
  4172. }
  4173. private:
  4174. // forward declaration
  4175. template<typename IteratorType> class iteration_proxy;
  4176. public:
  4177. /*!
  4178. @brief wrapper to access iterator member functions in range-based for
  4179. This function allows to access @ref iterator::key() and @ref
  4180. iterator::value() during range-based for loops. In these loops, a
  4181. reference to the JSON values is returned, so there is no access to the
  4182. underlying iterator.
  4183. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  4184. @note The name of this function is not yet final and may change in the
  4185. future.
  4186. */
  4187. static iteration_proxy<iterator> iterator_wrapper(reference cont)
  4188. {
  4189. return iteration_proxy<iterator>(cont);
  4190. }
  4191. /*!
  4192. @copydoc iterator_wrapper(reference)
  4193. */
  4194. static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
  4195. {
  4196. return iteration_proxy<const_iterator>(cont);
  4197. }
  4198. /// @}
  4199. //////////////
  4200. // capacity //
  4201. //////////////
  4202. /// @name capacity
  4203. /// @{
  4204. /*!
  4205. @brief checks whether the container is empty
  4206. Checks if a JSON value has no elements.
  4207. @return The return value depends on the different types and is
  4208. defined as follows:
  4209. Value type | return value
  4210. ----------- | -------------
  4211. null | `true`
  4212. boolean | `false`
  4213. string | `false`
  4214. number | `false`
  4215. object | result of function `object_t::empty()`
  4216. array | result of function `array_t::empty()`
  4217. @note This function does not return whether a string stored as JSON value
  4218. is empty - it returns whether the JSON container itself is empty which is
  4219. false in the case of a string.
  4220. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  4221. the Container concept; that is, their `empty()` functions have constant
  4222. complexity.
  4223. @requirement This function helps `basic_json` satisfying the
  4224. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4225. requirements:
  4226. - The complexity is constant.
  4227. - Has the semantics of `begin() == end()`.
  4228. @liveexample{The following code uses `empty()` to check if a JSON
  4229. object contains any elements.,empty}
  4230. @sa @ref size() -- returns the number of elements
  4231. @since version 1.0.0
  4232. */
  4233. bool empty() const noexcept
  4234. {
  4235. switch (m_type)
  4236. {
  4237. case value_t::null:
  4238. {
  4239. // null values are empty
  4240. return true;
  4241. }
  4242. case value_t::array:
  4243. {
  4244. // delegate call to array_t::empty()
  4245. return m_value.array->empty();
  4246. }
  4247. case value_t::object:
  4248. {
  4249. // delegate call to object_t::empty()
  4250. return m_value.object->empty();
  4251. }
  4252. default:
  4253. {
  4254. // all other types are nonempty
  4255. return false;
  4256. }
  4257. }
  4258. }
  4259. /*!
  4260. @brief returns the number of elements
  4261. Returns the number of elements in a JSON value.
  4262. @return The return value depends on the different types and is
  4263. defined as follows:
  4264. Value type | return value
  4265. ----------- | -------------
  4266. null | `0`
  4267. boolean | `1`
  4268. string | `1`
  4269. number | `1`
  4270. object | result of function object_t::size()
  4271. array | result of function array_t::size()
  4272. @note This function does not return the length of a string stored as JSON
  4273. value - it returns the number of elements in the JSON value which is 1 in
  4274. the case of a string.
  4275. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  4276. the Container concept; that is, their size() functions have constant
  4277. complexity.
  4278. @requirement This function helps `basic_json` satisfying the
  4279. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4280. requirements:
  4281. - The complexity is constant.
  4282. - Has the semantics of `std::distance(begin(), end())`.
  4283. @liveexample{The following code calls `size()` on the different value
  4284. types.,size}
  4285. @sa @ref empty() -- checks whether the container is empty
  4286. @sa @ref max_size() -- returns the maximal number of elements
  4287. @since version 1.0.0
  4288. */
  4289. size_type size() const noexcept
  4290. {
  4291. switch (m_type)
  4292. {
  4293. case value_t::null:
  4294. {
  4295. // null values are empty
  4296. return 0;
  4297. }
  4298. case value_t::array:
  4299. {
  4300. // delegate call to array_t::size()
  4301. return m_value.array->size();
  4302. }
  4303. case value_t::object:
  4304. {
  4305. // delegate call to object_t::size()
  4306. return m_value.object->size();
  4307. }
  4308. default:
  4309. {
  4310. // all other types have size 1
  4311. return 1;
  4312. }
  4313. }
  4314. }
  4315. /*!
  4316. @brief returns the maximum possible number of elements
  4317. Returns the maximum number of elements a JSON value is able to hold due to
  4318. system or library implementation limitations, i.e. `std::distance(begin(),
  4319. end())` for the JSON value.
  4320. @return The return value depends on the different types and is
  4321. defined as follows:
  4322. Value type | return value
  4323. ----------- | -------------
  4324. null | `0` (same as `size()`)
  4325. boolean | `1` (same as `size()`)
  4326. string | `1` (same as `size()`)
  4327. number | `1` (same as `size()`)
  4328. object | result of function `object_t::max_size()`
  4329. array | result of function `array_t::max_size()`
  4330. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  4331. the Container concept; that is, their `max_size()` functions have constant
  4332. complexity.
  4333. @requirement This function helps `basic_json` satisfying the
  4334. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4335. requirements:
  4336. - The complexity is constant.
  4337. - Has the semantics of returning `b.size()` where `b` is the largest
  4338. possible JSON value.
  4339. @liveexample{The following code calls `max_size()` on the different value
  4340. types. Note the output is implementation specific.,max_size}
  4341. @sa @ref size() -- returns the number of elements
  4342. @since version 1.0.0
  4343. */
  4344. size_type max_size() const noexcept
  4345. {
  4346. switch (m_type)
  4347. {
  4348. case value_t::array:
  4349. {
  4350. // delegate call to array_t::max_size()
  4351. return m_value.array->max_size();
  4352. }
  4353. case value_t::object:
  4354. {
  4355. // delegate call to object_t::max_size()
  4356. return m_value.object->max_size();
  4357. }
  4358. default:
  4359. {
  4360. // all other types have max_size() == size()
  4361. return size();
  4362. }
  4363. }
  4364. }
  4365. /// @}
  4366. ///////////////
  4367. // modifiers //
  4368. ///////////////
  4369. /// @name modifiers
  4370. /// @{
  4371. /*!
  4372. @brief clears the contents
  4373. Clears the content of a JSON value and resets it to the default value as
  4374. if @ref basic_json(value_t) would have been called:
  4375. Value type | initial value
  4376. ----------- | -------------
  4377. null | `null`
  4378. boolean | `false`
  4379. string | `""`
  4380. number | `0`
  4381. object | `{}`
  4382. array | `[]`
  4383. @complexity Linear in the size of the JSON value.
  4384. @liveexample{The example below shows the effect of `clear()` to different
  4385. JSON types.,clear}
  4386. @since version 1.0.0
  4387. */
  4388. void clear() noexcept
  4389. {
  4390. switch (m_type)
  4391. {
  4392. case value_t::number_integer:
  4393. {
  4394. m_value.number_integer = 0;
  4395. break;
  4396. }
  4397. case value_t::number_unsigned:
  4398. {
  4399. m_value.number_unsigned = 0;
  4400. break;
  4401. }
  4402. case value_t::number_float:
  4403. {
  4404. m_value.number_float = 0.0;
  4405. break;
  4406. }
  4407. case value_t::boolean:
  4408. {
  4409. m_value.boolean = false;
  4410. break;
  4411. }
  4412. case value_t::string:
  4413. {
  4414. m_value.string->clear();
  4415. break;
  4416. }
  4417. case value_t::array:
  4418. {
  4419. m_value.array->clear();
  4420. break;
  4421. }
  4422. case value_t::object:
  4423. {
  4424. m_value.object->clear();
  4425. break;
  4426. }
  4427. default:
  4428. {
  4429. break;
  4430. }
  4431. }
  4432. }
  4433. /*!
  4434. @brief add an object to an array
  4435. Appends the given element @a val to the end of the JSON value. If the
  4436. function is called on a JSON null value, an empty array is created before
  4437. appending @a val.
  4438. @param[in] val the value to add to the JSON array
  4439. @throw type_error.308 when called on a type other than JSON array or
  4440. null; example: `"cannot use push_back() with number"`
  4441. @complexity Amortized constant.
  4442. @liveexample{The example shows how `push_back()` and `+=` can be used to
  4443. add elements to a JSON array. Note how the `null` value was silently
  4444. converted to a JSON array.,push_back}
  4445. @since version 1.0.0
  4446. */
  4447. void push_back(basic_json&& val)
  4448. {
  4449. // push_back only works for null objects or arrays
  4450. if (not(is_null() or is_array()))
  4451. {
  4452. JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name()));
  4453. }
  4454. // transform null object into an array
  4455. if (is_null())
  4456. {
  4457. m_type = value_t::array;
  4458. m_value = value_t::array;
  4459. assert_invariant();
  4460. }
  4461. // add element to array (move semantics)
  4462. m_value.array->push_back(std::move(val));
  4463. // invalidate object
  4464. val.m_type = value_t::null;
  4465. }
  4466. /*!
  4467. @brief add an object to an array
  4468. @copydoc push_back(basic_json&&)
  4469. */
  4470. reference operator+=(basic_json&& val)
  4471. {
  4472. push_back(std::move(val));
  4473. return *this;
  4474. }
  4475. /*!
  4476. @brief add an object to an array
  4477. @copydoc push_back(basic_json&&)
  4478. */
  4479. void push_back(const basic_json& val)
  4480. {
  4481. // push_back only works for null objects or arrays
  4482. if (not(is_null() or is_array()))
  4483. {
  4484. JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name()));
  4485. }
  4486. // transform null object into an array
  4487. if (is_null())
  4488. {
  4489. m_type = value_t::array;
  4490. m_value = value_t::array;
  4491. assert_invariant();
  4492. }
  4493. // add element to array
  4494. m_value.array->push_back(val);
  4495. }
  4496. /*!
  4497. @brief add an object to an array
  4498. @copydoc push_back(basic_json&&)
  4499. */
  4500. reference operator+=(const basic_json& val)
  4501. {
  4502. push_back(val);
  4503. return *this;
  4504. }
  4505. /*!
  4506. @brief add an object to an object
  4507. Inserts the given element @a val to the JSON object. If the function is
  4508. called on a JSON null value, an empty object is created before inserting
  4509. @a val.
  4510. @param[in] val the value to add to the JSON object
  4511. @throw type_error.308 when called on a type other than JSON object or
  4512. null; example: `"cannot use push_back() with number"`
  4513. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4514. @liveexample{The example shows how `push_back()` and `+=` can be used to
  4515. add elements to a JSON object. Note how the `null` value was silently
  4516. converted to a JSON object.,push_back__object_t__value}
  4517. @since version 1.0.0
  4518. */
  4519. void push_back(const typename object_t::value_type& val)
  4520. {
  4521. // push_back only works for null objects or objects
  4522. if (not(is_null() or is_object()))
  4523. {
  4524. JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name()));
  4525. }
  4526. // transform null object into an object
  4527. if (is_null())
  4528. {
  4529. m_type = value_t::object;
  4530. m_value = value_t::object;
  4531. assert_invariant();
  4532. }
  4533. // add element to array
  4534. m_value.object->insert(val);
  4535. }
  4536. /*!
  4537. @brief add an object to an object
  4538. @copydoc push_back(const typename object_t::value_type&)
  4539. */
  4540. reference operator+=(const typename object_t::value_type& val)
  4541. {
  4542. push_back(val);
  4543. return *this;
  4544. }
  4545. /*!
  4546. @brief add an object to an object
  4547. This function allows to use `push_back` with an initializer list. In case
  4548. 1. the current value is an object,
  4549. 2. the initializer list @a init contains only two elements, and
  4550. 3. the first element of @a init is a string,
  4551. @a init is converted into an object element and added using
  4552. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  4553. is converted to a JSON value and added using @ref push_back(basic_json&&).
  4554. @param[in] init an initializer list
  4555. @complexity Linear in the size of the initializer list @a init.
  4556. @note This function is required to resolve an ambiguous overload error,
  4557. because pairs like `{"key", "value"}` can be both interpreted as
  4558. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  4559. https://github.com/nlohmann/json/issues/235 for more information.
  4560. @liveexample{The example shows how initializer lists are treated as
  4561. objects when possible.,push_back__initializer_list}
  4562. */
  4563. void push_back(std::initializer_list<basic_json> init)
  4564. {
  4565. if (is_object() and init.size() == 2 and init.begin()->is_string())
  4566. {
  4567. const string_t key = *init.begin();
  4568. push_back(typename object_t::value_type(key, *(init.begin() + 1)));
  4569. }
  4570. else
  4571. {
  4572. push_back(basic_json(init));
  4573. }
  4574. }
  4575. /*!
  4576. @brief add an object to an object
  4577. @copydoc push_back(std::initializer_list<basic_json>)
  4578. */
  4579. reference operator+=(std::initializer_list<basic_json> init)
  4580. {
  4581. push_back(init);
  4582. return *this;
  4583. }
  4584. /*!
  4585. @brief add an object to an array
  4586. Creates a JSON value from the passed parameters @a args to the end of the
  4587. JSON value. If the function is called on a JSON null value, an empty array
  4588. is created before appending the value created from @a args.
  4589. @param[in] args arguments to forward to a constructor of @ref basic_json
  4590. @tparam Args compatible types to create a @ref basic_json object
  4591. @throw type_error.311 when called on a type other than JSON array or
  4592. null; example: `"cannot use emplace_back() with number"`
  4593. @complexity Amortized constant.
  4594. @liveexample{The example shows how `push_back()` can be used to add
  4595. elements to a JSON array. Note how the `null` value was silently converted
  4596. to a JSON array.,emplace_back}
  4597. @since version 2.0.8
  4598. */
  4599. template<class... Args>
  4600. void emplace_back(Args&& ... args)
  4601. {
  4602. // emplace_back only works for null objects or arrays
  4603. if (not(is_null() or is_array()))
  4604. {
  4605. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + type_name()));
  4606. }
  4607. // transform null object into an array
  4608. if (is_null())
  4609. {
  4610. m_type = value_t::array;
  4611. m_value = value_t::array;
  4612. assert_invariant();
  4613. }
  4614. // add element to array (perfect forwarding)
  4615. m_value.array->emplace_back(std::forward<Args>(args)...);
  4616. }
  4617. /*!
  4618. @brief add an object to an object if key does not exist
  4619. Inserts a new element into a JSON object constructed in-place with the
  4620. given @a args if there is no element with the key in the container. If the
  4621. function is called on a JSON null value, an empty object is created before
  4622. appending the value created from @a args.
  4623. @param[in] args arguments to forward to a constructor of @ref basic_json
  4624. @tparam Args compatible types to create a @ref basic_json object
  4625. @return a pair consisting of an iterator to the inserted element, or the
  4626. already-existing element if no insertion happened, and a bool
  4627. denoting whether the insertion took place.
  4628. @throw type_error.311 when called on a type other than JSON object or
  4629. null; example: `"cannot use emplace() with number"`
  4630. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4631. @liveexample{The example shows how `emplace()` can be used to add elements
  4632. to a JSON object. Note how the `null` value was silently converted to a
  4633. JSON object. Further note how no value is added if there was already one
  4634. value stored with the same key.,emplace}
  4635. @since version 2.0.8
  4636. */
  4637. template<class... Args>
  4638. std::pair<iterator, bool> emplace(Args&& ... args)
  4639. {
  4640. // emplace only works for null objects or arrays
  4641. if (not(is_null() or is_object()))
  4642. {
  4643. JSON_THROW(type_error::create(311, "cannot use emplace() with " + type_name()));
  4644. }
  4645. // transform null object into an object
  4646. if (is_null())
  4647. {
  4648. m_type = value_t::object;
  4649. m_value = value_t::object;
  4650. assert_invariant();
  4651. }
  4652. // add element to array (perfect forwarding)
  4653. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  4654. // create result iterator and set iterator to the result of emplace
  4655. auto it = begin();
  4656. it.m_it.object_iterator = res.first;
  4657. // return pair of iterator and boolean
  4658. return {it, res.second};
  4659. }
  4660. /*!
  4661. @brief inserts element
  4662. Inserts element @a val before iterator @a pos.
  4663. @param[in] pos iterator before which the content will be inserted; may be
  4664. the end() iterator
  4665. @param[in] val element to insert
  4666. @return iterator pointing to the inserted @a val.
  4667. @throw type_error.309 if called on JSON values other than arrays;
  4668. example: `"cannot use insert() with string"`
  4669. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4670. example: `"iterator does not fit current value"`
  4671. @complexity Constant plus linear in the distance between @a pos and end of
  4672. the container.
  4673. @liveexample{The example shows how `insert()` is used.,insert}
  4674. @since version 1.0.0
  4675. */
  4676. iterator insert(const_iterator pos, const basic_json& val)
  4677. {
  4678. // insert only works for arrays
  4679. if (is_array())
  4680. {
  4681. // check if iterator pos fits to this JSON value
  4682. if (pos.m_object != this)
  4683. {
  4684. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4685. }
  4686. // insert to array and return iterator
  4687. iterator result(this);
  4688. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  4689. return result;
  4690. }
  4691. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4692. }
  4693. /*!
  4694. @brief inserts element
  4695. @copydoc insert(const_iterator, const basic_json&)
  4696. */
  4697. iterator insert(const_iterator pos, basic_json&& val)
  4698. {
  4699. return insert(pos, val);
  4700. }
  4701. /*!
  4702. @brief inserts elements
  4703. Inserts @a cnt copies of @a val before iterator @a pos.
  4704. @param[in] pos iterator before which the content will be inserted; may be
  4705. the end() iterator
  4706. @param[in] cnt number of copies of @a val to insert
  4707. @param[in] val element to insert
  4708. @return iterator pointing to the first element inserted, or @a pos if
  4709. `cnt==0`
  4710. @throw type_error.309 if called on JSON values other than arrays; example:
  4711. `"cannot use insert() with string"`
  4712. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4713. example: `"iterator does not fit current value"`
  4714. @complexity Linear in @a cnt plus linear in the distance between @a pos
  4715. and end of the container.
  4716. @liveexample{The example shows how `insert()` is used.,insert__count}
  4717. @since version 1.0.0
  4718. */
  4719. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  4720. {
  4721. // insert only works for arrays
  4722. if (is_array())
  4723. {
  4724. // check if iterator pos fits to this JSON value
  4725. if (pos.m_object != this)
  4726. {
  4727. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4728. }
  4729. // insert to array and return iterator
  4730. iterator result(this);
  4731. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  4732. return result;
  4733. }
  4734. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4735. }
  4736. /*!
  4737. @brief inserts elements
  4738. Inserts elements from range `[first, last)` before iterator @a pos.
  4739. @param[in] pos iterator before which the content will be inserted; may be
  4740. the end() iterator
  4741. @param[in] first begin of the range of elements to insert
  4742. @param[in] last end of the range of elements to insert
  4743. @throw type_error.309 if called on JSON values other than arrays; example:
  4744. `"cannot use insert() with string"`
  4745. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4746. example: `"iterator does not fit current value"`
  4747. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4748. same JSON value; example: `"iterators do not fit"`
  4749. @throw invalid_iterator.211 if @a first or @a last are iterators into
  4750. container for which insert is called; example: `"passed iterators may not
  4751. belong to container"`
  4752. @return iterator pointing to the first element inserted, or @a pos if
  4753. `first==last`
  4754. @complexity Linear in `std::distance(first, last)` plus linear in the
  4755. distance between @a pos and end of the container.
  4756. @liveexample{The example shows how `insert()` is used.,insert__range}
  4757. @since version 1.0.0
  4758. */
  4759. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  4760. {
  4761. // insert only works for arrays
  4762. if (not is_array())
  4763. {
  4764. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4765. }
  4766. // check if iterator pos fits to this JSON value
  4767. if (pos.m_object != this)
  4768. {
  4769. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4770. }
  4771. // check if range iterators belong to the same JSON object
  4772. if (first.m_object != last.m_object)
  4773. {
  4774. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4775. }
  4776. if (first.m_object == this or last.m_object == this)
  4777. {
  4778. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  4779. }
  4780. // insert to array and return iterator
  4781. iterator result(this);
  4782. result.m_it.array_iterator = m_value.array->insert(
  4783. pos.m_it.array_iterator,
  4784. first.m_it.array_iterator,
  4785. last.m_it.array_iterator);
  4786. return result;
  4787. }
  4788. /*!
  4789. @brief inserts elements
  4790. Inserts elements from initializer list @a ilist before iterator @a pos.
  4791. @param[in] pos iterator before which the content will be inserted; may be
  4792. the end() iterator
  4793. @param[in] ilist initializer list to insert the values from
  4794. @throw type_error.309 if called on JSON values other than arrays; example:
  4795. `"cannot use insert() with string"`
  4796. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4797. example: `"iterator does not fit current value"`
  4798. @return iterator pointing to the first element inserted, or @a pos if
  4799. `ilist` is empty
  4800. @complexity Linear in `ilist.size()` plus linear in the distance between
  4801. @a pos and end of the container.
  4802. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  4803. @since version 1.0.0
  4804. */
  4805. iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
  4806. {
  4807. // insert only works for arrays
  4808. if (not is_array())
  4809. {
  4810. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4811. }
  4812. // check if iterator pos fits to this JSON value
  4813. if (pos.m_object != this)
  4814. {
  4815. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4816. }
  4817. // insert to array and return iterator
  4818. iterator result(this);
  4819. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
  4820. return result;
  4821. }
  4822. /*!
  4823. @brief inserts elements
  4824. Inserts elements from range `[first, last)`.
  4825. @param[in] first begin of the range of elements to insert
  4826. @param[in] last end of the range of elements to insert
  4827. @throw type_error.309 if called on JSON values other than objects; example:
  4828. `"cannot use insert() with string"`
  4829. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  4830. point to an object; example: `"iterators first and last must point to
  4831. objects"`
  4832. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4833. same JSON value; example: `"iterators do not fit"`
  4834. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  4835. of elements to insert.
  4836. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  4837. @since version 3.0.0
  4838. */
  4839. void insert(const_iterator first, const_iterator last)
  4840. {
  4841. // insert only works for objects
  4842. if (not is_object())
  4843. {
  4844. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4845. }
  4846. // check if range iterators belong to the same JSON object
  4847. if (first.m_object != last.m_object)
  4848. {
  4849. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4850. }
  4851. // passed iterators must belong to objects
  4852. if (not first.m_object->is_object() or not first.m_object->is_object())
  4853. {
  4854. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  4855. }
  4856. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  4857. }
  4858. /*!
  4859. @brief exchanges the values
  4860. Exchanges the contents of the JSON value with those of @a other. Does not
  4861. invoke any move, copy, or swap operations on individual elements. All
  4862. iterators and references remain valid. The past-the-end iterator is
  4863. invalidated.
  4864. @param[in,out] other JSON value to exchange the contents with
  4865. @complexity Constant.
  4866. @liveexample{The example below shows how JSON values can be swapped with
  4867. `swap()`.,swap__reference}
  4868. @since version 1.0.0
  4869. */
  4870. void swap(reference other) noexcept (
  4871. std::is_nothrow_move_constructible<value_t>::value and
  4872. std::is_nothrow_move_assignable<value_t>::value and
  4873. std::is_nothrow_move_constructible<json_value>::value and
  4874. std::is_nothrow_move_assignable<json_value>::value
  4875. )
  4876. {
  4877. std::swap(m_type, other.m_type);
  4878. std::swap(m_value, other.m_value);
  4879. assert_invariant();
  4880. }
  4881. /*!
  4882. @brief exchanges the values
  4883. Exchanges the contents of a JSON array with those of @a other. Does not
  4884. invoke any move, copy, or swap operations on individual elements. All
  4885. iterators and references remain valid. The past-the-end iterator is
  4886. invalidated.
  4887. @param[in,out] other array to exchange the contents with
  4888. @throw type_error.310 when JSON value is not an array; example: `"cannot
  4889. use swap() with string"`
  4890. @complexity Constant.
  4891. @liveexample{The example below shows how arrays can be swapped with
  4892. `swap()`.,swap__array_t}
  4893. @since version 1.0.0
  4894. */
  4895. void swap(array_t& other)
  4896. {
  4897. // swap only works for arrays
  4898. if (is_array())
  4899. {
  4900. std::swap(*(m_value.array), other);
  4901. }
  4902. else
  4903. {
  4904. JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name()));
  4905. }
  4906. }
  4907. /*!
  4908. @brief exchanges the values
  4909. Exchanges the contents of a JSON object with those of @a other. Does not
  4910. invoke any move, copy, or swap operations on individual elements. All
  4911. iterators and references remain valid. The past-the-end iterator is
  4912. invalidated.
  4913. @param[in,out] other object to exchange the contents with
  4914. @throw type_error.310 when JSON value is not an object; example:
  4915. `"cannot use swap() with string"`
  4916. @complexity Constant.
  4917. @liveexample{The example below shows how objects can be swapped with
  4918. `swap()`.,swap__object_t}
  4919. @since version 1.0.0
  4920. */
  4921. void swap(object_t& other)
  4922. {
  4923. // swap only works for objects
  4924. if (is_object())
  4925. {
  4926. std::swap(*(m_value.object), other);
  4927. }
  4928. else
  4929. {
  4930. JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name()));
  4931. }
  4932. }
  4933. /*!
  4934. @brief exchanges the values
  4935. Exchanges the contents of a JSON string with those of @a other. Does not
  4936. invoke any move, copy, or swap operations on individual elements. All
  4937. iterators and references remain valid. The past-the-end iterator is
  4938. invalidated.
  4939. @param[in,out] other string to exchange the contents with
  4940. @throw type_error.310 when JSON value is not a string; example: `"cannot
  4941. use swap() with boolean"`
  4942. @complexity Constant.
  4943. @liveexample{The example below shows how strings can be swapped with
  4944. `swap()`.,swap__string_t}
  4945. @since version 1.0.0
  4946. */
  4947. void swap(string_t& other)
  4948. {
  4949. // swap only works for strings
  4950. if (is_string())
  4951. {
  4952. std::swap(*(m_value.string), other);
  4953. }
  4954. else
  4955. {
  4956. JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name()));
  4957. }
  4958. }
  4959. /// @}
  4960. public:
  4961. //////////////////////////////////////////
  4962. // lexicographical comparison operators //
  4963. //////////////////////////////////////////
  4964. /// @name lexicographical comparison operators
  4965. /// @{
  4966. /*!
  4967. @brief comparison: equal
  4968. Compares two JSON values for equality according to the following rules:
  4969. - Two JSON values are equal if (1) they are from the same type and (2)
  4970. their stored values are the same according to their respective
  4971. `operator==`.
  4972. - Integer and floating-point numbers are automatically converted before
  4973. comparison. Note than two NaN values are always treated as unequal.
  4974. - Two JSON null values are equal.
  4975. @note NaN values never compare equal to themselves or to other NaN values.
  4976. @param[in] lhs first JSON value to consider
  4977. @param[in] rhs second JSON value to consider
  4978. @return whether the values @a lhs and @a rhs are equal
  4979. @complexity Linear.
  4980. @liveexample{The example demonstrates comparing several JSON
  4981. types.,operator__equal}
  4982. @since version 1.0.0
  4983. */
  4984. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  4985. {
  4986. const auto lhs_type = lhs.type();
  4987. const auto rhs_type = rhs.type();
  4988. if (lhs_type == rhs_type)
  4989. {
  4990. switch (lhs_type)
  4991. {
  4992. case value_t::array:
  4993. {
  4994. return *lhs.m_value.array == *rhs.m_value.array;
  4995. }
  4996. case value_t::object:
  4997. {
  4998. return *lhs.m_value.object == *rhs.m_value.object;
  4999. }
  5000. case value_t::null:
  5001. {
  5002. return true;
  5003. }
  5004. case value_t::string:
  5005. {
  5006. return *lhs.m_value.string == *rhs.m_value.string;
  5007. }
  5008. case value_t::boolean:
  5009. {
  5010. return lhs.m_value.boolean == rhs.m_value.boolean;
  5011. }
  5012. case value_t::number_integer:
  5013. {
  5014. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  5015. }
  5016. case value_t::number_unsigned:
  5017. {
  5018. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  5019. }
  5020. case value_t::number_float:
  5021. {
  5022. return lhs.m_value.number_float == rhs.m_value.number_float;
  5023. }
  5024. default:
  5025. {
  5026. return false;
  5027. }
  5028. }
  5029. }
  5030. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  5031. {
  5032. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  5033. }
  5034. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  5035. {
  5036. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  5037. }
  5038. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  5039. {
  5040. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  5041. }
  5042. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  5043. {
  5044. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  5045. }
  5046. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  5047. {
  5048. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  5049. }
  5050. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  5051. {
  5052. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  5053. }
  5054. return false;
  5055. }
  5056. /*!
  5057. @brief comparison: equal
  5058. @copydoc operator==(const_reference, const_reference)
  5059. */
  5060. template<typename ScalarType, typename std::enable_if<
  5061. std::is_scalar<ScalarType>::value, int>::type = 0>
  5062. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  5063. {
  5064. return (lhs == basic_json(rhs));
  5065. }
  5066. /*!
  5067. @brief comparison: equal
  5068. @copydoc operator==(const_reference, const_reference)
  5069. */
  5070. template<typename ScalarType, typename std::enable_if<
  5071. std::is_scalar<ScalarType>::value, int>::type = 0>
  5072. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  5073. {
  5074. return (basic_json(lhs) == rhs);
  5075. }
  5076. /*!
  5077. @brief comparison: not equal
  5078. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  5079. @param[in] lhs first JSON value to consider
  5080. @param[in] rhs second JSON value to consider
  5081. @return whether the values @a lhs and @a rhs are not equal
  5082. @complexity Linear.
  5083. @liveexample{The example demonstrates comparing several JSON
  5084. types.,operator__notequal}
  5085. @since version 1.0.0
  5086. */
  5087. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  5088. {
  5089. return not (lhs == rhs);
  5090. }
  5091. /*!
  5092. @brief comparison: not equal
  5093. @copydoc operator!=(const_reference, const_reference)
  5094. */
  5095. template<typename ScalarType, typename std::enable_if<
  5096. std::is_scalar<ScalarType>::value, int>::type = 0>
  5097. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  5098. {
  5099. return (lhs != basic_json(rhs));
  5100. }
  5101. /*!
  5102. @brief comparison: not equal
  5103. @copydoc operator!=(const_reference, const_reference)
  5104. */
  5105. template<typename ScalarType, typename std::enable_if<
  5106. std::is_scalar<ScalarType>::value, int>::type = 0>
  5107. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  5108. {
  5109. return (basic_json(lhs) != rhs);
  5110. }
  5111. /*!
  5112. @brief comparison: less than
  5113. Compares whether one JSON value @a lhs is less than another JSON value @a
  5114. rhs according to the following rules:
  5115. - If @a lhs and @a rhs have the same type, the values are compared using
  5116. the default `<` operator.
  5117. - Integer and floating-point numbers are automatically converted before
  5118. comparison
  5119. - In case @a lhs and @a rhs have different types, the values are ignored
  5120. and the order of the types is considered, see
  5121. @ref operator<(const value_t, const value_t).
  5122. @param[in] lhs first JSON value to consider
  5123. @param[in] rhs second JSON value to consider
  5124. @return whether @a lhs is less than @a rhs
  5125. @complexity Linear.
  5126. @liveexample{The example demonstrates comparing several JSON
  5127. types.,operator__less}
  5128. @since version 1.0.0
  5129. */
  5130. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  5131. {
  5132. const auto lhs_type = lhs.type();
  5133. const auto rhs_type = rhs.type();
  5134. if (lhs_type == rhs_type)
  5135. {
  5136. switch (lhs_type)
  5137. {
  5138. case value_t::array:
  5139. {
  5140. return (*lhs.m_value.array) < (*rhs.m_value.array);
  5141. }
  5142. case value_t::object:
  5143. {
  5144. return *lhs.m_value.object < *rhs.m_value.object;
  5145. }
  5146. case value_t::null:
  5147. {
  5148. return false;
  5149. }
  5150. case value_t::string:
  5151. {
  5152. return *lhs.m_value.string < *rhs.m_value.string;
  5153. }
  5154. case value_t::boolean:
  5155. {
  5156. return lhs.m_value.boolean < rhs.m_value.boolean;
  5157. }
  5158. case value_t::number_integer:
  5159. {
  5160. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  5161. }
  5162. case value_t::number_unsigned:
  5163. {
  5164. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  5165. }
  5166. case value_t::number_float:
  5167. {
  5168. return lhs.m_value.number_float < rhs.m_value.number_float;
  5169. }
  5170. default:
  5171. {
  5172. return false;
  5173. }
  5174. }
  5175. }
  5176. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  5177. {
  5178. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  5179. }
  5180. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  5181. {
  5182. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  5183. }
  5184. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  5185. {
  5186. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  5187. }
  5188. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  5189. {
  5190. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  5191. }
  5192. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  5193. {
  5194. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  5195. }
  5196. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  5197. {
  5198. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  5199. }
  5200. // We only reach this line if we cannot compare values. In that case,
  5201. // we compare types. Note we have to call the operator explicitly,
  5202. // because MSVC has problems otherwise.
  5203. return operator<(lhs_type, rhs_type);
  5204. }
  5205. /*!
  5206. @brief comparison: less than
  5207. @copydoc operator<(const_reference, const_reference)
  5208. */
  5209. template<typename ScalarType, typename std::enable_if<
  5210. std::is_scalar<ScalarType>::value, int>::type = 0>
  5211. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  5212. {
  5213. return (lhs < basic_json(rhs));
  5214. }
  5215. /*!
  5216. @brief comparison: less than
  5217. @copydoc operator<(const_reference, const_reference)
  5218. */
  5219. template<typename ScalarType, typename std::enable_if<
  5220. std::is_scalar<ScalarType>::value, int>::type = 0>
  5221. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  5222. {
  5223. return (basic_json(lhs) < rhs);
  5224. }
  5225. /*!
  5226. @brief comparison: less than or equal
  5227. Compares whether one JSON value @a lhs is less than or equal to another
  5228. JSON value by calculating `not (rhs < lhs)`.
  5229. @param[in] lhs first JSON value to consider
  5230. @param[in] rhs second JSON value to consider
  5231. @return whether @a lhs is less than or equal to @a rhs
  5232. @complexity Linear.
  5233. @liveexample{The example demonstrates comparing several JSON
  5234. types.,operator__greater}
  5235. @since version 1.0.0
  5236. */
  5237. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  5238. {
  5239. return not (rhs < lhs);
  5240. }
  5241. /*!
  5242. @brief comparison: less than or equal
  5243. @copydoc operator<=(const_reference, const_reference)
  5244. */
  5245. template<typename ScalarType, typename std::enable_if<
  5246. std::is_scalar<ScalarType>::value, int>::type = 0>
  5247. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  5248. {
  5249. return (lhs <= basic_json(rhs));
  5250. }
  5251. /*!
  5252. @brief comparison: less than or equal
  5253. @copydoc operator<=(const_reference, const_reference)
  5254. */
  5255. template<typename ScalarType, typename std::enable_if<
  5256. std::is_scalar<ScalarType>::value, int>::type = 0>
  5257. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  5258. {
  5259. return (basic_json(lhs) <= rhs);
  5260. }
  5261. /*!
  5262. @brief comparison: greater than
  5263. Compares whether one JSON value @a lhs is greater than another
  5264. JSON value by calculating `not (lhs <= rhs)`.
  5265. @param[in] lhs first JSON value to consider
  5266. @param[in] rhs second JSON value to consider
  5267. @return whether @a lhs is greater than to @a rhs
  5268. @complexity Linear.
  5269. @liveexample{The example demonstrates comparing several JSON
  5270. types.,operator__lessequal}
  5271. @since version 1.0.0
  5272. */
  5273. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  5274. {
  5275. return not (lhs <= rhs);
  5276. }
  5277. /*!
  5278. @brief comparison: greater than
  5279. @copydoc operator>(const_reference, const_reference)
  5280. */
  5281. template<typename ScalarType, typename std::enable_if<
  5282. std::is_scalar<ScalarType>::value, int>::type = 0>
  5283. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  5284. {
  5285. return (lhs > basic_json(rhs));
  5286. }
  5287. /*!
  5288. @brief comparison: greater than
  5289. @copydoc operator>(const_reference, const_reference)
  5290. */
  5291. template<typename ScalarType, typename std::enable_if<
  5292. std::is_scalar<ScalarType>::value, int>::type = 0>
  5293. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  5294. {
  5295. return (basic_json(lhs) > rhs);
  5296. }
  5297. /*!
  5298. @brief comparison: greater than or equal
  5299. Compares whether one JSON value @a lhs is greater than or equal to another
  5300. JSON value by calculating `not (lhs < rhs)`.
  5301. @param[in] lhs first JSON value to consider
  5302. @param[in] rhs second JSON value to consider
  5303. @return whether @a lhs is greater than or equal to @a rhs
  5304. @complexity Linear.
  5305. @liveexample{The example demonstrates comparing several JSON
  5306. types.,operator__greaterequal}
  5307. @since version 1.0.0
  5308. */
  5309. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  5310. {
  5311. return not (lhs < rhs);
  5312. }
  5313. /*!
  5314. @brief comparison: greater than or equal
  5315. @copydoc operator>=(const_reference, const_reference)
  5316. */
  5317. template<typename ScalarType, typename std::enable_if<
  5318. std::is_scalar<ScalarType>::value, int>::type = 0>
  5319. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  5320. {
  5321. return (lhs >= basic_json(rhs));
  5322. }
  5323. /*!
  5324. @brief comparison: greater than or equal
  5325. @copydoc operator>=(const_reference, const_reference)
  5326. */
  5327. template<typename ScalarType, typename std::enable_if<
  5328. std::is_scalar<ScalarType>::value, int>::type = 0>
  5329. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  5330. {
  5331. return (basic_json(lhs) >= rhs);
  5332. }
  5333. /// @}
  5334. private:
  5335. /////////////////////
  5336. // output adapters //
  5337. /////////////////////
  5338. /// abstract output adapter interface
  5339. template<typename CharType>
  5340. class output_adapter
  5341. {
  5342. public:
  5343. virtual void write_character(CharType c) = 0;
  5344. virtual void write_characters(const CharType* s, size_t length) = 0;
  5345. virtual ~output_adapter() {}
  5346. static std::shared_ptr<output_adapter<CharType>> create(std::vector<CharType>& vec)
  5347. {
  5348. return std::make_shared<output_vector_adapter<CharType>>(vec);
  5349. }
  5350. static std::shared_ptr<output_adapter<CharType>> create(std::ostream& s)
  5351. {
  5352. return std::make_shared<output_stream_adapter<CharType>>(s);
  5353. }
  5354. static std::shared_ptr<output_adapter<CharType>> create(std::string& s)
  5355. {
  5356. return std::make_shared<output_string_adapter<CharType>>(s);
  5357. }
  5358. };
  5359. /// a type to simplify interfaces
  5360. template<typename CharType>
  5361. using output_adapter_t = std::shared_ptr<output_adapter<CharType>>;
  5362. /// output adapter for byte vectors
  5363. template<typename CharType>
  5364. class output_vector_adapter : public output_adapter<CharType>
  5365. {
  5366. public:
  5367. output_vector_adapter(std::vector<CharType>& vec)
  5368. : v(vec)
  5369. {}
  5370. void write_character(CharType c) override
  5371. {
  5372. v.push_back(c);
  5373. }
  5374. void write_characters(const CharType* s, size_t length) override
  5375. {
  5376. std::copy(s, s + length, std::back_inserter(v));
  5377. }
  5378. private:
  5379. std::vector<CharType>& v;
  5380. };
  5381. /// output adapter for output streams
  5382. template<typename CharType>
  5383. class output_stream_adapter : public output_adapter<CharType>
  5384. {
  5385. public:
  5386. output_stream_adapter(std::basic_ostream<CharType>& s)
  5387. : stream(s)
  5388. {}
  5389. void write_character(CharType c) override
  5390. {
  5391. stream.put(c);
  5392. }
  5393. void write_characters(const CharType* s, size_t length) override
  5394. {
  5395. stream.write(s, static_cast<std::streamsize>(length));
  5396. }
  5397. private:
  5398. std::basic_ostream<CharType>& stream;
  5399. };
  5400. /// output adapter for basic_string
  5401. template<typename CharType>
  5402. class output_string_adapter : public output_adapter<CharType>
  5403. {
  5404. public:
  5405. output_string_adapter(std::string& s)
  5406. : str(s)
  5407. {}
  5408. void write_character(CharType c) override
  5409. {
  5410. str.push_back(c);
  5411. }
  5412. void write_characters(const CharType* s, size_t length) override
  5413. {
  5414. str.append(s, length);
  5415. }
  5416. private:
  5417. std::basic_string<CharType>& str;
  5418. };
  5419. ///////////////////
  5420. // serialization //
  5421. ///////////////////
  5422. /// @name serialization
  5423. /// @{
  5424. private:
  5425. /*!
  5426. @brief wrapper around the serialization functions
  5427. */
  5428. class serializer
  5429. {
  5430. public:
  5431. /*!
  5432. @param[in] s output stream to serialize to
  5433. @param[in] ichar indentation character to use
  5434. */
  5435. serializer(output_adapter_t<char> s, const char ichar)
  5436. : o(s), loc(std::localeconv()),
  5437. thousands_sep(!loc->thousands_sep ? '\0' : loc->thousands_sep[0]),
  5438. decimal_point(!loc->decimal_point ? '\0' : loc->decimal_point[0]),
  5439. indent_char(ichar), indent_string(512, indent_char)
  5440. {}
  5441. // delete because of pointer members
  5442. serializer(const serializer&) = delete;
  5443. serializer& operator=(const serializer&) = delete;
  5444. /*!
  5445. @brief internal implementation of the serialization function
  5446. This function is called by the public member function dump and
  5447. organizes the serialization internally. The indentation level is
  5448. propagated as additional parameter. In case of arrays and objects, the
  5449. function is called recursively.
  5450. - strings and object keys are escaped using `escape_string()`
  5451. - integer numbers are converted implicitly via `operator<<`
  5452. - floating-point numbers are converted to a string using `"%g"` format
  5453. @param[in] val value to serialize
  5454. @param[in] pretty_print whether the output shall be pretty-printed
  5455. @param[in] indent_step the indent level
  5456. @param[in] current_indent the current indent level (only used internally)
  5457. */
  5458. void dump(const basic_json& val,
  5459. const bool pretty_print,
  5460. const unsigned int indent_step,
  5461. const unsigned int current_indent = 0)
  5462. {
  5463. switch (val.m_type)
  5464. {
  5465. case value_t::object:
  5466. {
  5467. if (val.m_value.object->empty())
  5468. {
  5469. o->write_characters("{}", 2);
  5470. return;
  5471. }
  5472. if (pretty_print)
  5473. {
  5474. o->write_characters("{\n", 2);
  5475. // variable to hold indentation for recursive calls
  5476. const auto new_indent = current_indent + indent_step;
  5477. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  5478. {
  5479. indent_string.resize(indent_string.size() * 2, ' ');
  5480. }
  5481. // first n-1 elements
  5482. auto i = val.m_value.object->cbegin();
  5483. for (size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5484. {
  5485. o->write_characters(indent_string.c_str(), new_indent);
  5486. o->write_character('\"');
  5487. dump_escaped(i->first);
  5488. o->write_characters("\": ", 3);
  5489. dump(i->second, true, indent_step, new_indent);
  5490. o->write_characters(",\n", 2);
  5491. }
  5492. // last element
  5493. assert(i != val.m_value.object->cend());
  5494. o->write_characters(indent_string.c_str(), new_indent);
  5495. o->write_character('\"');
  5496. dump_escaped(i->first);
  5497. o->write_characters("\": ", 3);
  5498. dump(i->second, true, indent_step, new_indent);
  5499. o->write_character('\n');
  5500. o->write_characters(indent_string.c_str(), current_indent);
  5501. o->write_character('}');
  5502. }
  5503. else
  5504. {
  5505. o->write_character('{');
  5506. // first n-1 elements
  5507. auto i = val.m_value.object->cbegin();
  5508. for (size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5509. {
  5510. o->write_character('\"');
  5511. dump_escaped(i->first);
  5512. o->write_characters("\":", 2);
  5513. dump(i->second, false, indent_step, current_indent);
  5514. o->write_character(',');
  5515. }
  5516. // last element
  5517. assert(i != val.m_value.object->cend());
  5518. o->write_character('\"');
  5519. dump_escaped(i->first);
  5520. o->write_characters("\":", 2);
  5521. dump(i->second, false, indent_step, current_indent);
  5522. o->write_character('}');
  5523. }
  5524. return;
  5525. }
  5526. case value_t::array:
  5527. {
  5528. if (val.m_value.array->empty())
  5529. {
  5530. o->write_characters("[]", 2);
  5531. return;
  5532. }
  5533. if (pretty_print)
  5534. {
  5535. o->write_characters("[\n", 2);
  5536. // variable to hold indentation for recursive calls
  5537. const auto new_indent = current_indent + indent_step;
  5538. if (indent_string.size() < new_indent)
  5539. {
  5540. indent_string.resize(new_indent, ' ');
  5541. }
  5542. // first n-1 elements
  5543. for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i)
  5544. {
  5545. o->write_characters(indent_string.c_str(), new_indent);
  5546. dump(*i, true, indent_step, new_indent);
  5547. o->write_characters(",\n", 2);
  5548. }
  5549. // last element
  5550. assert(not val.m_value.array->empty());
  5551. o->write_characters(indent_string.c_str(), new_indent);
  5552. dump(val.m_value.array->back(), true, indent_step, new_indent);
  5553. o->write_character('\n');
  5554. o->write_characters(indent_string.c_str(), current_indent);
  5555. o->write_character(']');
  5556. }
  5557. else
  5558. {
  5559. o->write_character('[');
  5560. // first n-1 elements
  5561. for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i)
  5562. {
  5563. dump(*i, false, indent_step, current_indent);
  5564. o->write_character(',');
  5565. }
  5566. // last element
  5567. assert(not val.m_value.array->empty());
  5568. dump(val.m_value.array->back(), false, indent_step, current_indent);
  5569. o->write_character(']');
  5570. }
  5571. return;
  5572. }
  5573. case value_t::string:
  5574. {
  5575. o->write_character('\"');
  5576. dump_escaped(*val.m_value.string);
  5577. o->write_character('\"');
  5578. return;
  5579. }
  5580. case value_t::boolean:
  5581. {
  5582. if (val.m_value.boolean)
  5583. {
  5584. o->write_characters("true", 4);
  5585. }
  5586. else
  5587. {
  5588. o->write_characters("false", 5);
  5589. }
  5590. return;
  5591. }
  5592. case value_t::number_integer:
  5593. {
  5594. dump_integer(val.m_value.number_integer);
  5595. return;
  5596. }
  5597. case value_t::number_unsigned:
  5598. {
  5599. dump_integer(val.m_value.number_unsigned);
  5600. return;
  5601. }
  5602. case value_t::number_float:
  5603. {
  5604. dump_float(val.m_value.number_float);
  5605. return;
  5606. }
  5607. case value_t::discarded:
  5608. {
  5609. o->write_characters("<discarded>", 11);
  5610. return;
  5611. }
  5612. case value_t::null:
  5613. {
  5614. o->write_characters("null", 4);
  5615. return;
  5616. }
  5617. }
  5618. }
  5619. private:
  5620. /*!
  5621. @brief calculates the extra space to escape a JSON string
  5622. @param[in] s the string to escape
  5623. @return the number of characters required to escape string @a s
  5624. @complexity Linear in the length of string @a s.
  5625. */
  5626. static std::size_t extra_space(const string_t& s) noexcept
  5627. {
  5628. return std::accumulate(s.begin(), s.end(), size_t{},
  5629. [](size_t res, typename string_t::value_type c)
  5630. {
  5631. switch (c)
  5632. {
  5633. case '"':
  5634. case '\\':
  5635. case '\b':
  5636. case '\f':
  5637. case '\n':
  5638. case '\r':
  5639. case '\t':
  5640. {
  5641. // from c (1 byte) to \x (2 bytes)
  5642. return res + 1;
  5643. }
  5644. case 0x00:
  5645. case 0x01:
  5646. case 0x02:
  5647. case 0x03:
  5648. case 0x04:
  5649. case 0x05:
  5650. case 0x06:
  5651. case 0x07:
  5652. case 0x0b:
  5653. case 0x0e:
  5654. case 0x0f:
  5655. case 0x10:
  5656. case 0x11:
  5657. case 0x12:
  5658. case 0x13:
  5659. case 0x14:
  5660. case 0x15:
  5661. case 0x16:
  5662. case 0x17:
  5663. case 0x18:
  5664. case 0x19:
  5665. case 0x1a:
  5666. case 0x1b:
  5667. case 0x1c:
  5668. case 0x1d:
  5669. case 0x1e:
  5670. case 0x1f:
  5671. {
  5672. // from c (1 byte) to \uxxxx (6 bytes)
  5673. return res + 5;
  5674. }
  5675. default:
  5676. {
  5677. return res;
  5678. }
  5679. }
  5680. });
  5681. }
  5682. /*!
  5683. @brief dump escaped string
  5684. Escape a string by replacing certain special characters by a sequence
  5685. of an escape character (backslash) and another character and other
  5686. control characters by a sequence of "\u" followed by a four-digit hex
  5687. representation. The escaped string is written to output stream @a o.
  5688. @param[in] s the string to escape
  5689. @complexity Linear in the length of string @a s.
  5690. */
  5691. void dump_escaped(const string_t& s) const
  5692. {
  5693. const auto space = extra_space(s);
  5694. if (space == 0)
  5695. {
  5696. o->write_characters(s.c_str(), s.size());
  5697. return;
  5698. }
  5699. // create a result string of necessary size
  5700. string_t result(s.size() + space, '\\');
  5701. std::size_t pos = 0;
  5702. for (const auto& c : s)
  5703. {
  5704. switch (c)
  5705. {
  5706. // quotation mark (0x22)
  5707. case '"':
  5708. {
  5709. result[pos + 1] = '"';
  5710. pos += 2;
  5711. break;
  5712. }
  5713. // reverse solidus (0x5c)
  5714. case '\\':
  5715. {
  5716. // nothing to change
  5717. pos += 2;
  5718. break;
  5719. }
  5720. // backspace (0x08)
  5721. case '\b':
  5722. {
  5723. result[pos + 1] = 'b';
  5724. pos += 2;
  5725. break;
  5726. }
  5727. // formfeed (0x0c)
  5728. case '\f':
  5729. {
  5730. result[pos + 1] = 'f';
  5731. pos += 2;
  5732. break;
  5733. }
  5734. // newline (0x0a)
  5735. case '\n':
  5736. {
  5737. result[pos + 1] = 'n';
  5738. pos += 2;
  5739. break;
  5740. }
  5741. // carriage return (0x0d)
  5742. case '\r':
  5743. {
  5744. result[pos + 1] = 'r';
  5745. pos += 2;
  5746. break;
  5747. }
  5748. // horizontal tab (0x09)
  5749. case '\t':
  5750. {
  5751. result[pos + 1] = 't';
  5752. pos += 2;
  5753. break;
  5754. }
  5755. case 0x00:
  5756. case 0x01:
  5757. case 0x02:
  5758. case 0x03:
  5759. case 0x04:
  5760. case 0x05:
  5761. case 0x06:
  5762. case 0x07:
  5763. case 0x0b:
  5764. case 0x0e:
  5765. case 0x0f:
  5766. case 0x10:
  5767. case 0x11:
  5768. case 0x12:
  5769. case 0x13:
  5770. case 0x14:
  5771. case 0x15:
  5772. case 0x16:
  5773. case 0x17:
  5774. case 0x18:
  5775. case 0x19:
  5776. case 0x1a:
  5777. case 0x1b:
  5778. case 0x1c:
  5779. case 0x1d:
  5780. case 0x1e:
  5781. case 0x1f:
  5782. {
  5783. // convert a number 0..15 to its hex representation
  5784. // (0..f)
  5785. static const char hexify[16] =
  5786. {
  5787. '0', '1', '2', '3', '4', '5', '6', '7',
  5788. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  5789. };
  5790. // print character c as \uxxxx
  5791. for (const char m :
  5792. { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f]
  5793. })
  5794. {
  5795. result[++pos] = m;
  5796. }
  5797. ++pos;
  5798. break;
  5799. }
  5800. default:
  5801. {
  5802. // all other characters are added as-is
  5803. result[pos++] = c;
  5804. break;
  5805. }
  5806. }
  5807. }
  5808. assert(pos == s.size() + space);
  5809. o->write_characters(result.c_str(), result.size());
  5810. }
  5811. /*!
  5812. @brief dump an integer
  5813. Dump a given integer to output stream @a o. Works internally with
  5814. @a number_buffer.
  5815. @param[in] x integer number (signed or unsigned) to dump
  5816. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  5817. */
  5818. template<typename NumberType, detail::enable_if_t <
  5819. std::is_same<NumberType, number_unsigned_t>::value or
  5820. std::is_same<NumberType, number_integer_t>::value, int> = 0>
  5821. void dump_integer(NumberType x)
  5822. {
  5823. // special case for "0"
  5824. if (x == 0)
  5825. {
  5826. o->write_character('0');
  5827. return;
  5828. }
  5829. const bool is_negative = x < 0;
  5830. size_t i = 0;
  5831. // spare 1 byte for '\0'
  5832. while (x != 0 and i < number_buffer.size() - 1)
  5833. {
  5834. const auto digit = std::labs(static_cast<long>(x % 10));
  5835. number_buffer[i++] = static_cast<char>('0' + digit);
  5836. x /= 10;
  5837. }
  5838. // make sure the number has been processed completely
  5839. assert(x == 0);
  5840. if (is_negative)
  5841. {
  5842. // make sure there is capacity for the '-'
  5843. assert(i < number_buffer.size() - 2);
  5844. number_buffer[i++] = '-';
  5845. }
  5846. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  5847. o->write_characters(number_buffer.data(), i);
  5848. }
  5849. /*!
  5850. @brief dump a floating-point number
  5851. Dump a given floating-point number to output stream @a o. Works
  5852. internally with @a number_buffer.
  5853. @param[in] x floating-point number to dump
  5854. */
  5855. void dump_float(number_float_t x)
  5856. {
  5857. // NaN / inf
  5858. if (not std::isfinite(x) or std::isnan(x))
  5859. {
  5860. o->write_characters("null", 4);
  5861. return;
  5862. }
  5863. // special case for 0.0 and -0.0
  5864. if (x == 0)
  5865. {
  5866. if (std::signbit(x))
  5867. {
  5868. o->write_characters("-0.0", 4);
  5869. }
  5870. else
  5871. {
  5872. o->write_characters("0.0", 3);
  5873. }
  5874. return;
  5875. }
  5876. // get number of digits for a text -> float -> text round-trip
  5877. static constexpr auto d = std::numeric_limits<number_float_t>::digits10;
  5878. // the actual conversion
  5879. std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(),
  5880. "%.*g", d, x);
  5881. // negative value indicates an error
  5882. assert(len > 0);
  5883. // check if buffer was large enough
  5884. assert(static_cast<size_t>(len) < number_buffer.size());
  5885. // erase thousands separator
  5886. if (thousands_sep != '\0')
  5887. {
  5888. const auto end = std::remove(number_buffer.begin(),
  5889. number_buffer.begin() + len,
  5890. thousands_sep);
  5891. std::fill(end, number_buffer.end(), '\0');
  5892. assert((end - number_buffer.begin()) <= len);
  5893. len = (end - number_buffer.begin());
  5894. }
  5895. // convert decimal point to '.'
  5896. if (decimal_point != '\0' and decimal_point != '.')
  5897. {
  5898. for (auto& c : number_buffer)
  5899. {
  5900. if (c == decimal_point)
  5901. {
  5902. c = '.';
  5903. break;
  5904. }
  5905. }
  5906. }
  5907. o->write_characters(number_buffer.data(), static_cast<size_t>(len));
  5908. // determine if need to append ".0"
  5909. const bool value_is_int_like = std::none_of(number_buffer.begin(),
  5910. number_buffer.begin() + len + 1,
  5911. [](char c)
  5912. {
  5913. return c == '.' or c == 'e';
  5914. });
  5915. if (value_is_int_like)
  5916. {
  5917. o->write_characters(".0", 2);
  5918. }
  5919. }
  5920. private:
  5921. /// the output of the serializer
  5922. output_adapter_t<char> o = nullptr;
  5923. /// a (hopefully) large enough character buffer
  5924. std::array<char, 64> number_buffer{{}};
  5925. /// the locale
  5926. const std::lconv* loc = nullptr;
  5927. /// the locale's thousand separator character
  5928. const char thousands_sep = '\0';
  5929. /// the locale's decimal point character
  5930. const char decimal_point = '\0';
  5931. /// the indentation character
  5932. const char indent_char;
  5933. /// the indentation string
  5934. string_t indent_string;
  5935. };
  5936. public:
  5937. /*!
  5938. @brief serialize to stream
  5939. Serialize the given JSON value @a j to the output stream @a o. The JSON
  5940. value will be serialized using the @ref dump member function.
  5941. - The indentation of the output can be controlled with the member variable
  5942. `width` of the output stream @a o. For instance, using the manipulator
  5943. `std::setw(4)` on @a o sets the indentation level to `4` and the
  5944. serialization result is the same as calling `dump(4)`.
  5945. - The indentation characrer can be controlled with the member variable
  5946. `fill` of the output stream @a o. For instance, the manipulator
  5947. `std::setfill('\\t')` sets indentation to use a tab character rather than
  5948. the default space character.
  5949. @param[in,out] o stream to serialize to
  5950. @param[in] j JSON value to serialize
  5951. @return the stream @a o
  5952. @complexity Linear.
  5953. @liveexample{The example below shows the serialization with different
  5954. parameters to `width` to adjust the indentation level.,operator_serialize}
  5955. @since version 1.0.0; indentaction character added in version 3.0.0
  5956. */
  5957. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  5958. {
  5959. // read width member and use it as indentation parameter if nonzero
  5960. const bool pretty_print = (o.width() > 0);
  5961. const auto indentation = (pretty_print ? o.width() : 0);
  5962. // reset width to 0 for subsequent calls to this stream
  5963. o.width(0);
  5964. // do the actual serialization
  5965. serializer s(output_adapter<char>::create(o), o.fill());
  5966. s.dump(j, pretty_print, static_cast<unsigned int>(indentation));
  5967. return o;
  5968. }
  5969. /*!
  5970. @brief serialize to stream
  5971. @deprecated This stream operator is deprecated and will be removed in a
  5972. future version of the library. Please use
  5973. @ref std::ostream& operator<<(std::ostream&, const basic_json&)
  5974. instead; that is, replace calls like `j >> o;` with `o << j;`.
  5975. */
  5976. JSON_DEPRECATED
  5977. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  5978. {
  5979. return o << j;
  5980. }
  5981. /// @}
  5982. /////////////////////
  5983. // deserialization //
  5984. /////////////////////
  5985. /// @name deserialization
  5986. /// @{
  5987. /*!
  5988. @brief deserialize from an array
  5989. This function reads from an array of 1-byte values.
  5990. @pre Each element of the container has a size of 1 byte. Violating this
  5991. precondition yields undefined behavior. **This precondition is enforced
  5992. with a static assertion.**
  5993. @param[in] array array to read from
  5994. @param[in] cb a parser callback function of type @ref parser_callback_t
  5995. which is used to control the deserialization by filtering unwanted values
  5996. (optional)
  5997. @return result of the deserialization
  5998. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  5999. of input; expected string literal""`
  6000. @throw parse_error.102 if to_unicode fails or surrogate error
  6001. @throw parse_error.103 if to_unicode fails
  6002. @complexity Linear in the length of the input. The parser is a predictive
  6003. LL(1) parser. The complexity can be higher if the parser callback function
  6004. @a cb has a super-linear complexity.
  6005. @note A UTF-8 byte order mark is silently ignored.
  6006. @liveexample{The example below demonstrates the `parse()` function reading
  6007. from an array.,parse__array__parser_callback_t}
  6008. @since version 2.0.3
  6009. */
  6010. template<class T, std::size_t N>
  6011. static basic_json parse(T (&array)[N],
  6012. const parser_callback_t cb = nullptr)
  6013. {
  6014. // delegate the call to the iterator-range parse overload
  6015. return parse(std::begin(array), std::end(array), cb);
  6016. }
  6017. template<class T, std::size_t N>
  6018. static bool accept(T (&array)[N])
  6019. {
  6020. // delegate the call to the iterator-range accept overload
  6021. return accept(std::begin(array), std::end(array));
  6022. }
  6023. /*!
  6024. @brief deserialize from string literal
  6025. @tparam CharT character/literal type with size of 1 byte
  6026. @param[in] s string literal to read a serialized JSON value from
  6027. @param[in] cb a parser callback function of type @ref parser_callback_t
  6028. which is used to control the deserialization by filtering unwanted values
  6029. (optional)
  6030. @return result of the deserialization
  6031. @throw parse_error.101 in case of an unexpected token
  6032. @throw parse_error.102 if to_unicode fails or surrogate error
  6033. @throw parse_error.103 if to_unicode fails
  6034. @complexity Linear in the length of the input. The parser is a predictive
  6035. LL(1) parser. The complexity can be higher if the parser callback function
  6036. @a cb has a super-linear complexity.
  6037. @note A UTF-8 byte order mark is silently ignored.
  6038. @note String containers like `std::string` or @ref string_t can be parsed
  6039. with @ref parse(const ContiguousContainer&, const parser_callback_t)
  6040. @liveexample{The example below demonstrates the `parse()` function with
  6041. and without callback function.,parse__string__parser_callback_t}
  6042. @sa @ref parse(std::istream&, const parser_callback_t) for a version that
  6043. reads from an input stream
  6044. @since version 1.0.0 (originally for @ref string_t)
  6045. */
  6046. template<typename CharT, typename std::enable_if<
  6047. std::is_pointer<CharT>::value and
  6048. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  6049. sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0>
  6050. static basic_json parse(const CharT s,
  6051. const parser_callback_t cb = nullptr)
  6052. {
  6053. return parser(input_adapter::create(s), cb).parse(true);
  6054. }
  6055. template<typename CharT, typename std::enable_if<
  6056. std::is_pointer<CharT>::value and
  6057. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  6058. sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0>
  6059. static bool accept(const CharT s)
  6060. {
  6061. return parser(input_adapter::create(s)).accept(true);
  6062. }
  6063. /*!
  6064. @brief deserialize from stream
  6065. @param[in,out] i stream to read a serialized JSON value from
  6066. @param[in] cb a parser callback function of type @ref parser_callback_t
  6067. which is used to control the deserialization by filtering unwanted values
  6068. (optional)
  6069. @return result of the deserialization
  6070. @throw parse_error.101 in case of an unexpected token
  6071. @throw parse_error.102 if to_unicode fails or surrogate error
  6072. @throw parse_error.103 if to_unicode fails
  6073. @complexity Linear in the length of the input. The parser is a predictive
  6074. LL(1) parser. The complexity can be higher if the parser callback function
  6075. @a cb has a super-linear complexity.
  6076. @note A UTF-8 byte order mark is silently ignored.
  6077. @liveexample{The example below demonstrates the `parse()` function with
  6078. and without callback function.,parse__istream__parser_callback_t}
  6079. @sa @ref parse(const CharT, const parser_callback_t) for a version
  6080. that reads from a string
  6081. @since version 1.0.0
  6082. */
  6083. static basic_json parse(std::istream& i,
  6084. const parser_callback_t cb = nullptr)
  6085. {
  6086. return parser(input_adapter::create(i), cb).parse(true);
  6087. }
  6088. static bool accept(std::istream& i)
  6089. {
  6090. return parser(input_adapter::create(i)).accept(true);
  6091. }
  6092. /*!
  6093. @copydoc parse(std::istream&, const parser_callback_t)
  6094. */
  6095. static basic_json parse(std::istream&& i,
  6096. const parser_callback_t cb = nullptr)
  6097. {
  6098. return parser(input_adapter::create(i), cb).parse(true);
  6099. }
  6100. static bool accept(std::istream&& i)
  6101. {
  6102. return parser(input_adapter::create(i)).accept(true);
  6103. }
  6104. /*!
  6105. @brief deserialize from an iterator range with contiguous storage
  6106. This function reads from an iterator range of a container with contiguous
  6107. storage of 1-byte values. Compatible container types include
  6108. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  6109. `std::initializer_list`. Furthermore, C-style arrays can be used with
  6110. `std::begin()`/`std::end()`. User-defined containers can be used as long
  6111. as they implement random-access iterators and a contiguous storage.
  6112. @pre The iterator range is contiguous. Violating this precondition yields
  6113. undefined behavior. **This precondition is enforced with an assertion.**
  6114. @pre Each element in the range has a size of 1 byte. Violating this
  6115. precondition yields undefined behavior. **This precondition is enforced
  6116. with a static assertion.**
  6117. @warning There is no way to enforce all preconditions at compile-time. If
  6118. the function is called with noncompliant iterators and with
  6119. assertions switched off, the behavior is undefined and will most
  6120. likely yield segmentation violation.
  6121. @tparam IteratorType iterator of container with contiguous storage
  6122. @param[in] first begin of the range to parse (included)
  6123. @param[in] last end of the range to parse (excluded)
  6124. @param[in] cb a parser callback function of type @ref parser_callback_t
  6125. which is used to control the deserialization by filtering unwanted values
  6126. (optional)
  6127. @return result of the deserialization
  6128. @throw parse_error.101 in case of an unexpected token
  6129. @throw parse_error.102 if to_unicode fails or surrogate error
  6130. @throw parse_error.103 if to_unicode fails
  6131. @complexity Linear in the length of the input. The parser is a predictive
  6132. LL(1) parser. The complexity can be higher if the parser callback function
  6133. @a cb has a super-linear complexity.
  6134. @note A UTF-8 byte order mark is silently ignored.
  6135. @liveexample{The example below demonstrates the `parse()` function reading
  6136. from an iterator range.,parse__iteratortype__parser_callback_t}
  6137. @since version 2.0.3
  6138. */
  6139. template<class IteratorType, typename std::enable_if<
  6140. std::is_base_of<
  6141. std::random_access_iterator_tag,
  6142. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  6143. static basic_json parse(IteratorType first, IteratorType last,
  6144. const parser_callback_t cb = nullptr)
  6145. {
  6146. return parser(input_adapter::create(first, last), cb).parse(true);
  6147. }
  6148. template<class IteratorType, typename std::enable_if<
  6149. std::is_base_of<
  6150. std::random_access_iterator_tag,
  6151. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  6152. static bool accept(IteratorType first, IteratorType last)
  6153. {
  6154. return parser(input_adapter::create(first, last)).accept(true);
  6155. }
  6156. /*!
  6157. @brief deserialize from a container with contiguous storage
  6158. This function reads from a container with contiguous storage of 1-byte
  6159. values. Compatible container types include `std::vector`, `std::string`,
  6160. `std::array`, and `std::initializer_list`. User-defined containers can be
  6161. used as long as they implement random-access iterators and a contiguous
  6162. storage.
  6163. @pre The container storage is contiguous. Violating this precondition
  6164. yields undefined behavior. **This precondition is enforced with an
  6165. assertion.**
  6166. @pre Each element of the container has a size of 1 byte. Violating this
  6167. precondition yields undefined behavior. **This precondition is enforced
  6168. with a static assertion.**
  6169. @warning There is no way to enforce all preconditions at compile-time. If
  6170. the function is called with a noncompliant container and with
  6171. assertions switched off, the behavior is undefined and will most
  6172. likely yield segmentation violation.
  6173. @tparam ContiguousContainer container type with contiguous storage
  6174. @param[in] c container to read from
  6175. @param[in] cb a parser callback function of type @ref parser_callback_t
  6176. which is used to control the deserialization by filtering unwanted values
  6177. (optional)
  6178. @return result of the deserialization
  6179. @throw parse_error.101 in case of an unexpected token
  6180. @throw parse_error.102 if to_unicode fails or surrogate error
  6181. @throw parse_error.103 if to_unicode fails
  6182. @complexity Linear in the length of the input. The parser is a predictive
  6183. LL(1) parser. The complexity can be higher if the parser callback function
  6184. @a cb has a super-linear complexity.
  6185. @note A UTF-8 byte order mark is silently ignored.
  6186. @liveexample{The example below demonstrates the `parse()` function reading
  6187. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  6188. @since version 2.0.3
  6189. */
  6190. template<class ContiguousContainer, typename std::enable_if<
  6191. not std::is_pointer<ContiguousContainer>::value and
  6192. std::is_base_of<
  6193. std::random_access_iterator_tag,
  6194. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
  6195. , int>::type = 0>
  6196. static basic_json parse(const ContiguousContainer& c,
  6197. const parser_callback_t cb = nullptr)
  6198. {
  6199. // delegate the call to the iterator-range parse overload
  6200. return parse(std::begin(c), std::end(c), cb);
  6201. }
  6202. template<class ContiguousContainer, typename std::enable_if<
  6203. not std::is_pointer<ContiguousContainer>::value and
  6204. std::is_base_of<
  6205. std::random_access_iterator_tag,
  6206. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
  6207. , int>::type = 0>
  6208. static bool accept(const ContiguousContainer& c)
  6209. {
  6210. // delegate the call to the iterator-range accept overload
  6211. return accept(std::begin(c), std::end(c));
  6212. }
  6213. /*!
  6214. @brief deserialize from stream
  6215. @deprecated This stream operator is deprecated and will be removed in a
  6216. future version of the library. Please use
  6217. @ref std::istream& operator>>(std::istream&, basic_json&)
  6218. instead; that is, replace calls like `j << i;` with `i >> j;`.
  6219. */
  6220. JSON_DEPRECATED
  6221. friend std::istream& operator<<(basic_json& j, std::istream& i)
  6222. {
  6223. j = parser(input_adapter::create(i)).parse(false);
  6224. return i;
  6225. }
  6226. /*!
  6227. @brief deserialize from stream
  6228. Deserializes an input stream to a JSON value.
  6229. @param[in,out] i input stream to read a serialized JSON value from
  6230. @param[in,out] j JSON value to write the deserialized input to
  6231. @throw parse_error.101 in case of an unexpected token
  6232. @throw parse_error.102 if to_unicode fails or surrogate error
  6233. @throw parse_error.103 if to_unicode fails
  6234. @complexity Linear in the length of the input. The parser is a predictive
  6235. LL(1) parser.
  6236. @note A UTF-8 byte order mark is silently ignored.
  6237. @liveexample{The example below shows how a JSON value is constructed by
  6238. reading a serialization from a stream.,operator_deserialize}
  6239. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  6240. parser callback function to filter values while parsing
  6241. @since version 1.0.0
  6242. */
  6243. friend std::istream& operator>>(std::istream& i, basic_json& j)
  6244. {
  6245. j = parser(input_adapter::create(i)).parse(false);
  6246. return i;
  6247. }
  6248. /// @}
  6249. ///////////////////////////
  6250. // convenience functions //
  6251. ///////////////////////////
  6252. /*!
  6253. @brief return the type as string
  6254. Returns the type name as string to be used in error messages - usually to
  6255. indicate that a function was called on a wrong JSON type.
  6256. @return basically a string representation of a the @a m_type member
  6257. @complexity Constant.
  6258. @liveexample{The following code exemplifies `type_name()` for all JSON
  6259. types.,type_name}
  6260. @since version 1.0.0, public since 2.1.0
  6261. */
  6262. std::string type_name() const
  6263. {
  6264. {
  6265. switch (m_type)
  6266. {
  6267. case value_t::null:
  6268. return "null";
  6269. case value_t::object:
  6270. return "object";
  6271. case value_t::array:
  6272. return "array";
  6273. case value_t::string:
  6274. return "string";
  6275. case value_t::boolean:
  6276. return "boolean";
  6277. case value_t::discarded:
  6278. return "discarded";
  6279. default:
  6280. return "number";
  6281. }
  6282. }
  6283. }
  6284. private:
  6285. //////////////////////
  6286. // member variables //
  6287. //////////////////////
  6288. /// the type of the current element
  6289. value_t m_type = value_t::null;
  6290. /// the value of the current element
  6291. json_value m_value = {};
  6292. private:
  6293. ///////////////
  6294. // iterators //
  6295. ///////////////
  6296. /*!
  6297. @brief an iterator for primitive JSON types
  6298. This class models an iterator for primitive JSON types (boolean, number,
  6299. string). It's only purpose is to allow the iterator/const_iterator classes
  6300. to "iterate" over primitive values. Internally, the iterator is modeled by
  6301. a `difference_type` variable. Value begin_value (`0`) models the begin,
  6302. end_value (`1`) models past the end.
  6303. */
  6304. class primitive_iterator_t
  6305. {
  6306. public:
  6307. difference_type get_value() const noexcept
  6308. {
  6309. return m_it;
  6310. }
  6311. /// set iterator to a defined beginning
  6312. void set_begin() noexcept
  6313. {
  6314. m_it = begin_value;
  6315. }
  6316. /// set iterator to a defined past the end
  6317. void set_end() noexcept
  6318. {
  6319. m_it = end_value;
  6320. }
  6321. /// return whether the iterator can be dereferenced
  6322. constexpr bool is_begin() const noexcept
  6323. {
  6324. return (m_it == begin_value);
  6325. }
  6326. /// return whether the iterator is at end
  6327. constexpr bool is_end() const noexcept
  6328. {
  6329. return (m_it == end_value);
  6330. }
  6331. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6332. {
  6333. return lhs.m_it == rhs.m_it;
  6334. }
  6335. friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6336. {
  6337. return !(lhs == rhs);
  6338. }
  6339. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6340. {
  6341. return lhs.m_it < rhs.m_it;
  6342. }
  6343. friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6344. {
  6345. return lhs.m_it <= rhs.m_it;
  6346. }
  6347. friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6348. {
  6349. return lhs.m_it > rhs.m_it;
  6350. }
  6351. friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6352. {
  6353. return lhs.m_it >= rhs.m_it;
  6354. }
  6355. primitive_iterator_t operator+(difference_type i)
  6356. {
  6357. auto result = *this;
  6358. result += i;
  6359. return result;
  6360. }
  6361. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6362. {
  6363. return lhs.m_it - rhs.m_it;
  6364. }
  6365. friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
  6366. {
  6367. return os << it.m_it;
  6368. }
  6369. primitive_iterator_t& operator++()
  6370. {
  6371. ++m_it;
  6372. return *this;
  6373. }
  6374. primitive_iterator_t operator++(int)
  6375. {
  6376. auto result = *this;
  6377. m_it++;
  6378. return result;
  6379. }
  6380. primitive_iterator_t& operator--()
  6381. {
  6382. --m_it;
  6383. return *this;
  6384. }
  6385. primitive_iterator_t operator--(int)
  6386. {
  6387. auto result = *this;
  6388. m_it--;
  6389. return result;
  6390. }
  6391. primitive_iterator_t& operator+=(difference_type n)
  6392. {
  6393. m_it += n;
  6394. return *this;
  6395. }
  6396. primitive_iterator_t& operator-=(difference_type n)
  6397. {
  6398. m_it -= n;
  6399. return *this;
  6400. }
  6401. private:
  6402. static constexpr difference_type begin_value = 0;
  6403. static constexpr difference_type end_value = begin_value + 1;
  6404. /// iterator as signed integer type
  6405. difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
  6406. };
  6407. /*!
  6408. @brief an iterator value
  6409. @note This structure could easily be a union, but MSVC currently does not
  6410. allow unions members with complex constructors, see
  6411. https://github.com/nlohmann/json/pull/105.
  6412. */
  6413. struct internal_iterator
  6414. {
  6415. /// iterator for JSON objects
  6416. typename object_t::iterator object_iterator;
  6417. /// iterator for JSON arrays
  6418. typename array_t::iterator array_iterator;
  6419. /// generic iterator for all other types
  6420. primitive_iterator_t primitive_iterator;
  6421. /// create an uninitialized internal_iterator
  6422. internal_iterator() noexcept
  6423. : object_iterator(), array_iterator(), primitive_iterator()
  6424. {}
  6425. };
  6426. /// proxy class for the iterator_wrapper functions
  6427. template<typename IteratorType>
  6428. class iteration_proxy
  6429. {
  6430. private:
  6431. /// helper class for iteration
  6432. class iteration_proxy_internal
  6433. {
  6434. private:
  6435. /// the iterator
  6436. IteratorType anchor;
  6437. /// an index for arrays (used to create key names)
  6438. size_t array_index = 0;
  6439. public:
  6440. explicit iteration_proxy_internal(IteratorType it) noexcept
  6441. : anchor(it)
  6442. {}
  6443. /// dereference operator (needed for range-based for)
  6444. iteration_proxy_internal& operator*()
  6445. {
  6446. return *this;
  6447. }
  6448. /// increment operator (needed for range-based for)
  6449. iteration_proxy_internal& operator++()
  6450. {
  6451. ++anchor;
  6452. ++array_index;
  6453. return *this;
  6454. }
  6455. /// inequality operator (needed for range-based for)
  6456. bool operator!= (const iteration_proxy_internal& o) const
  6457. {
  6458. return anchor != o.anchor;
  6459. }
  6460. /// return key of the iterator
  6461. typename basic_json::string_t key() const
  6462. {
  6463. assert(anchor.m_object != nullptr);
  6464. switch (anchor.m_object->type())
  6465. {
  6466. // use integer array index as key
  6467. case value_t::array:
  6468. {
  6469. return std::to_string(array_index);
  6470. }
  6471. // use key from the object
  6472. case value_t::object:
  6473. {
  6474. return anchor.key();
  6475. }
  6476. // use an empty key for all primitive types
  6477. default:
  6478. {
  6479. return "";
  6480. }
  6481. }
  6482. }
  6483. /// return value of the iterator
  6484. typename IteratorType::reference value() const
  6485. {
  6486. return anchor.value();
  6487. }
  6488. };
  6489. /// the container to iterate
  6490. typename IteratorType::reference container;
  6491. public:
  6492. /// construct iteration proxy from a container
  6493. explicit iteration_proxy(typename IteratorType::reference cont)
  6494. : container(cont)
  6495. {}
  6496. /// return iterator begin (needed for range-based for)
  6497. iteration_proxy_internal begin() noexcept
  6498. {
  6499. return iteration_proxy_internal(container.begin());
  6500. }
  6501. /// return iterator end (needed for range-based for)
  6502. iteration_proxy_internal end() noexcept
  6503. {
  6504. return iteration_proxy_internal(container.end());
  6505. }
  6506. };
  6507. public:
  6508. /*!
  6509. @brief a template for a random access iterator for the @ref basic_json class
  6510. This class implements a both iterators (iterator and const_iterator) for the
  6511. @ref basic_json class.
  6512. @note An iterator is called *initialized* when a pointer to a JSON value
  6513. has been set (e.g., by a constructor or a copy assignment). If the
  6514. iterator is default-constructed, it is *uninitialized* and most
  6515. methods are undefined. **The library uses assertions to detect calls
  6516. on uninitialized iterators.**
  6517. @requirement The class satisfies the following concept requirements:
  6518. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  6519. The iterator that can be moved to point (forward and backward) to any
  6520. element in constant time.
  6521. @since version 1.0.0, simplified in version 2.0.9
  6522. */
  6523. template<typename U>
  6524. class iter_impl : public std::iterator<std::random_access_iterator_tag, U>
  6525. {
  6526. /// allow basic_json to access private members
  6527. friend class basic_json;
  6528. // make sure U is basic_json or const basic_json
  6529. static_assert(std::is_same<U, basic_json>::value
  6530. or std::is_same<U, const basic_json>::value,
  6531. "iter_impl only accepts (const) basic_json");
  6532. public:
  6533. /// the type of the values when the iterator is dereferenced
  6534. using value_type = typename basic_json::value_type;
  6535. /// a type to represent differences between iterators
  6536. using difference_type = typename basic_json::difference_type;
  6537. /// defines a pointer to the type iterated over (value_type)
  6538. using pointer = typename std::conditional<std::is_const<U>::value,
  6539. typename basic_json::const_pointer,
  6540. typename basic_json::pointer>::type;
  6541. /// defines a reference to the type iterated over (value_type)
  6542. using reference = typename std::conditional<std::is_const<U>::value,
  6543. typename basic_json::const_reference,
  6544. typename basic_json::reference>::type;
  6545. /// the category of the iterator
  6546. using iterator_category = std::bidirectional_iterator_tag;
  6547. /// default constructor
  6548. iter_impl() = default;
  6549. /*!
  6550. @brief constructor for a given JSON instance
  6551. @param[in] object pointer to a JSON object for this iterator
  6552. @pre object != nullptr
  6553. @post The iterator is initialized; i.e. `m_object != nullptr`.
  6554. */
  6555. explicit iter_impl(pointer object) noexcept
  6556. : m_object(object)
  6557. {
  6558. assert(m_object != nullptr);
  6559. switch (m_object->m_type)
  6560. {
  6561. case basic_json::value_t::object:
  6562. {
  6563. m_it.object_iterator = typename object_t::iterator();
  6564. break;
  6565. }
  6566. case basic_json::value_t::array:
  6567. {
  6568. m_it.array_iterator = typename array_t::iterator();
  6569. break;
  6570. }
  6571. default:
  6572. {
  6573. m_it.primitive_iterator = primitive_iterator_t();
  6574. break;
  6575. }
  6576. }
  6577. }
  6578. /*!
  6579. @note The conventional copy constructor and copy assignment are
  6580. implicitly defined.
  6581. Combined with the following converting constructor and assignment,
  6582. they support: copy from iterator to iterator,
  6583. copy from const iterator to const iterator,
  6584. and conversion from iterator to const iterator.
  6585. However conversion from const iterator to iterator is not defined.
  6586. */
  6587. /*!
  6588. @brief converting constructor
  6589. @param[in] other non-const iterator to copy from
  6590. @note It is not checked whether @a other is initialized.
  6591. */
  6592. iter_impl(const iter_impl<basic_json>& other) noexcept
  6593. : m_object(other.m_object), m_it(other.m_it)
  6594. {}
  6595. /*!
  6596. @brief converting assignment
  6597. @param[in,out] other non-const iterator to copy from
  6598. @return const/non-const iterator
  6599. @note It is not checked whether @a other is initialized.
  6600. */
  6601. iter_impl& operator=(const iter_impl<basic_json>& other) noexcept
  6602. {
  6603. m_object = other.m_object;
  6604. m_it = other.m_it;
  6605. return *this;
  6606. }
  6607. private:
  6608. /*!
  6609. @brief set the iterator to the first value
  6610. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6611. */
  6612. void set_begin() noexcept
  6613. {
  6614. assert(m_object != nullptr);
  6615. switch (m_object->m_type)
  6616. {
  6617. case basic_json::value_t::object:
  6618. {
  6619. m_it.object_iterator = m_object->m_value.object->begin();
  6620. break;
  6621. }
  6622. case basic_json::value_t::array:
  6623. {
  6624. m_it.array_iterator = m_object->m_value.array->begin();
  6625. break;
  6626. }
  6627. case basic_json::value_t::null:
  6628. {
  6629. // set to end so begin()==end() is true: null is empty
  6630. m_it.primitive_iterator.set_end();
  6631. break;
  6632. }
  6633. default:
  6634. {
  6635. m_it.primitive_iterator.set_begin();
  6636. break;
  6637. }
  6638. }
  6639. }
  6640. /*!
  6641. @brief set the iterator past the last value
  6642. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6643. */
  6644. void set_end() noexcept
  6645. {
  6646. assert(m_object != nullptr);
  6647. switch (m_object->m_type)
  6648. {
  6649. case basic_json::value_t::object:
  6650. {
  6651. m_it.object_iterator = m_object->m_value.object->end();
  6652. break;
  6653. }
  6654. case basic_json::value_t::array:
  6655. {
  6656. m_it.array_iterator = m_object->m_value.array->end();
  6657. break;
  6658. }
  6659. default:
  6660. {
  6661. m_it.primitive_iterator.set_end();
  6662. break;
  6663. }
  6664. }
  6665. }
  6666. public:
  6667. /*!
  6668. @brief return a reference to the value pointed to by the iterator
  6669. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6670. */
  6671. reference operator*() const
  6672. {
  6673. assert(m_object != nullptr);
  6674. switch (m_object->m_type)
  6675. {
  6676. case basic_json::value_t::object:
  6677. {
  6678. assert(m_it.object_iterator != m_object->m_value.object->end());
  6679. return m_it.object_iterator->second;
  6680. }
  6681. case basic_json::value_t::array:
  6682. {
  6683. assert(m_it.array_iterator != m_object->m_value.array->end());
  6684. return *m_it.array_iterator;
  6685. }
  6686. case basic_json::value_t::null:
  6687. {
  6688. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6689. }
  6690. default:
  6691. {
  6692. if (m_it.primitive_iterator.is_begin())
  6693. {
  6694. return *m_object;
  6695. }
  6696. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6697. }
  6698. }
  6699. }
  6700. /*!
  6701. @brief dereference the iterator
  6702. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6703. */
  6704. pointer operator->() const
  6705. {
  6706. assert(m_object != nullptr);
  6707. switch (m_object->m_type)
  6708. {
  6709. case basic_json::value_t::object:
  6710. {
  6711. assert(m_it.object_iterator != m_object->m_value.object->end());
  6712. return &(m_it.object_iterator->second);
  6713. }
  6714. case basic_json::value_t::array:
  6715. {
  6716. assert(m_it.array_iterator != m_object->m_value.array->end());
  6717. return &*m_it.array_iterator;
  6718. }
  6719. default:
  6720. {
  6721. if (m_it.primitive_iterator.is_begin())
  6722. {
  6723. return m_object;
  6724. }
  6725. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6726. }
  6727. }
  6728. }
  6729. /*!
  6730. @brief post-increment (it++)
  6731. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6732. */
  6733. iter_impl operator++(int)
  6734. {
  6735. auto result = *this;
  6736. ++(*this);
  6737. return result;
  6738. }
  6739. /*!
  6740. @brief pre-increment (++it)
  6741. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6742. */
  6743. iter_impl& operator++()
  6744. {
  6745. assert(m_object != nullptr);
  6746. switch (m_object->m_type)
  6747. {
  6748. case basic_json::value_t::object:
  6749. {
  6750. std::advance(m_it.object_iterator, 1);
  6751. break;
  6752. }
  6753. case basic_json::value_t::array:
  6754. {
  6755. std::advance(m_it.array_iterator, 1);
  6756. break;
  6757. }
  6758. default:
  6759. {
  6760. ++m_it.primitive_iterator;
  6761. break;
  6762. }
  6763. }
  6764. return *this;
  6765. }
  6766. /*!
  6767. @brief post-decrement (it--)
  6768. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6769. */
  6770. iter_impl operator--(int)
  6771. {
  6772. auto result = *this;
  6773. --(*this);
  6774. return result;
  6775. }
  6776. /*!
  6777. @brief pre-decrement (--it)
  6778. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6779. */
  6780. iter_impl& operator--()
  6781. {
  6782. assert(m_object != nullptr);
  6783. switch (m_object->m_type)
  6784. {
  6785. case basic_json::value_t::object:
  6786. {
  6787. std::advance(m_it.object_iterator, -1);
  6788. break;
  6789. }
  6790. case basic_json::value_t::array:
  6791. {
  6792. std::advance(m_it.array_iterator, -1);
  6793. break;
  6794. }
  6795. default:
  6796. {
  6797. --m_it.primitive_iterator;
  6798. break;
  6799. }
  6800. }
  6801. return *this;
  6802. }
  6803. /*!
  6804. @brief comparison: equal
  6805. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6806. */
  6807. bool operator==(const iter_impl& other) const
  6808. {
  6809. // if objects are not the same, the comparison is undefined
  6810. if (m_object != other.m_object)
  6811. {
  6812. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  6813. }
  6814. assert(m_object != nullptr);
  6815. switch (m_object->m_type)
  6816. {
  6817. case basic_json::value_t::object:
  6818. {
  6819. return (m_it.object_iterator == other.m_it.object_iterator);
  6820. }
  6821. case basic_json::value_t::array:
  6822. {
  6823. return (m_it.array_iterator == other.m_it.array_iterator);
  6824. }
  6825. default:
  6826. {
  6827. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  6828. }
  6829. }
  6830. }
  6831. /*!
  6832. @brief comparison: not equal
  6833. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6834. */
  6835. bool operator!=(const iter_impl& other) const
  6836. {
  6837. return not operator==(other);
  6838. }
  6839. /*!
  6840. @brief comparison: smaller
  6841. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6842. */
  6843. bool operator<(const iter_impl& other) const
  6844. {
  6845. // if objects are not the same, the comparison is undefined
  6846. if (m_object != other.m_object)
  6847. {
  6848. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  6849. }
  6850. assert(m_object != nullptr);
  6851. switch (m_object->m_type)
  6852. {
  6853. case basic_json::value_t::object:
  6854. {
  6855. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  6856. }
  6857. case basic_json::value_t::array:
  6858. {
  6859. return (m_it.array_iterator < other.m_it.array_iterator);
  6860. }
  6861. default:
  6862. {
  6863. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  6864. }
  6865. }
  6866. }
  6867. /*!
  6868. @brief comparison: less than or equal
  6869. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6870. */
  6871. bool operator<=(const iter_impl& other) const
  6872. {
  6873. return not other.operator < (*this);
  6874. }
  6875. /*!
  6876. @brief comparison: greater than
  6877. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6878. */
  6879. bool operator>(const iter_impl& other) const
  6880. {
  6881. return not operator<=(other);
  6882. }
  6883. /*!
  6884. @brief comparison: greater than or equal
  6885. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6886. */
  6887. bool operator>=(const iter_impl& other) const
  6888. {
  6889. return not operator<(other);
  6890. }
  6891. /*!
  6892. @brief add to iterator
  6893. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6894. */
  6895. iter_impl& operator+=(difference_type i)
  6896. {
  6897. assert(m_object != nullptr);
  6898. switch (m_object->m_type)
  6899. {
  6900. case basic_json::value_t::object:
  6901. {
  6902. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  6903. }
  6904. case basic_json::value_t::array:
  6905. {
  6906. std::advance(m_it.array_iterator, i);
  6907. break;
  6908. }
  6909. default:
  6910. {
  6911. m_it.primitive_iterator += i;
  6912. break;
  6913. }
  6914. }
  6915. return *this;
  6916. }
  6917. /*!
  6918. @brief subtract from iterator
  6919. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6920. */
  6921. iter_impl& operator-=(difference_type i)
  6922. {
  6923. return operator+=(-i);
  6924. }
  6925. /*!
  6926. @brief add to iterator
  6927. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6928. */
  6929. iter_impl operator+(difference_type i) const
  6930. {
  6931. auto result = *this;
  6932. result += i;
  6933. return result;
  6934. }
  6935. /*!
  6936. @brief addition of distance and iterator
  6937. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6938. */
  6939. friend iter_impl operator+(difference_type i, const iter_impl& it)
  6940. {
  6941. auto result = it;
  6942. result += i;
  6943. return result;
  6944. }
  6945. /*!
  6946. @brief subtract from iterator
  6947. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6948. */
  6949. iter_impl operator-(difference_type i) const
  6950. {
  6951. auto result = *this;
  6952. result -= i;
  6953. return result;
  6954. }
  6955. /*!
  6956. @brief return difference
  6957. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6958. */
  6959. difference_type operator-(const iter_impl& other) const
  6960. {
  6961. assert(m_object != nullptr);
  6962. switch (m_object->m_type)
  6963. {
  6964. case basic_json::value_t::object:
  6965. {
  6966. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  6967. }
  6968. case basic_json::value_t::array:
  6969. {
  6970. return m_it.array_iterator - other.m_it.array_iterator;
  6971. }
  6972. default:
  6973. {
  6974. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  6975. }
  6976. }
  6977. }
  6978. /*!
  6979. @brief access to successor
  6980. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6981. */
  6982. reference operator[](difference_type n) const
  6983. {
  6984. assert(m_object != nullptr);
  6985. switch (m_object->m_type)
  6986. {
  6987. case basic_json::value_t::object:
  6988. {
  6989. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  6990. }
  6991. case basic_json::value_t::array:
  6992. {
  6993. return *std::next(m_it.array_iterator, n);
  6994. }
  6995. case basic_json::value_t::null:
  6996. {
  6997. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6998. }
  6999. default:
  7000. {
  7001. if (m_it.primitive_iterator.get_value() == -n)
  7002. {
  7003. return *m_object;
  7004. }
  7005. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  7006. }
  7007. }
  7008. }
  7009. /*!
  7010. @brief return the key of an object iterator
  7011. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7012. */
  7013. typename object_t::key_type key() const
  7014. {
  7015. assert(m_object != nullptr);
  7016. if (m_object->is_object())
  7017. {
  7018. return m_it.object_iterator->first;
  7019. }
  7020. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  7021. }
  7022. /*!
  7023. @brief return the value of an iterator
  7024. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7025. */
  7026. reference value() const
  7027. {
  7028. return operator*();
  7029. }
  7030. private:
  7031. /// associated JSON instance
  7032. pointer m_object = nullptr;
  7033. /// the actual iterator of the associated instance
  7034. struct internal_iterator m_it = internal_iterator();
  7035. };
  7036. /*!
  7037. @brief a template for a reverse iterator class
  7038. @tparam Base the base iterator type to reverse. Valid types are @ref
  7039. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  7040. create @ref const_reverse_iterator).
  7041. @requirement The class satisfies the following concept requirements:
  7042. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  7043. The iterator that can be moved to point (forward and backward) to any
  7044. element in constant time.
  7045. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  7046. It is possible to write to the pointed-to element (only if @a Base is
  7047. @ref iterator).
  7048. @since version 1.0.0
  7049. */
  7050. template<typename Base>
  7051. class json_reverse_iterator : public std::reverse_iterator<Base>
  7052. {
  7053. public:
  7054. /// shortcut to the reverse iterator adaptor
  7055. using base_iterator = std::reverse_iterator<Base>;
  7056. /// the reference type for the pointed-to element
  7057. using reference = typename Base::reference;
  7058. /// create reverse iterator from iterator
  7059. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  7060. : base_iterator(it)
  7061. {}
  7062. /// create reverse iterator from base class
  7063. json_reverse_iterator(const base_iterator& it) noexcept
  7064. : base_iterator(it)
  7065. {}
  7066. /// post-increment (it++)
  7067. json_reverse_iterator operator++(int)
  7068. {
  7069. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  7070. }
  7071. /// pre-increment (++it)
  7072. json_reverse_iterator& operator++()
  7073. {
  7074. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  7075. }
  7076. /// post-decrement (it--)
  7077. json_reverse_iterator operator--(int)
  7078. {
  7079. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  7080. }
  7081. /// pre-decrement (--it)
  7082. json_reverse_iterator& operator--()
  7083. {
  7084. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  7085. }
  7086. /// add to iterator
  7087. json_reverse_iterator& operator+=(difference_type i)
  7088. {
  7089. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  7090. }
  7091. /// add to iterator
  7092. json_reverse_iterator operator+(difference_type i) const
  7093. {
  7094. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  7095. }
  7096. /// subtract from iterator
  7097. json_reverse_iterator operator-(difference_type i) const
  7098. {
  7099. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  7100. }
  7101. /// return difference
  7102. difference_type operator-(const json_reverse_iterator& other) const
  7103. {
  7104. return base_iterator(*this) - base_iterator(other);
  7105. }
  7106. /// access to successor
  7107. reference operator[](difference_type n) const
  7108. {
  7109. return *(this->operator+(n));
  7110. }
  7111. /// return the key of an object iterator
  7112. typename object_t::key_type key() const
  7113. {
  7114. auto it = --this->base();
  7115. return it.key();
  7116. }
  7117. /// return the value of an iterator
  7118. reference value() const
  7119. {
  7120. auto it = --this->base();
  7121. return it.operator * ();
  7122. }
  7123. };
  7124. private:
  7125. ////////////////////
  7126. // input adapters //
  7127. ////////////////////
  7128. /// abstract input adapter interface
  7129. class input_adapter
  7130. {
  7131. public:
  7132. virtual int get_character() = 0;
  7133. virtual std::string read(size_t offset, size_t length) = 0;
  7134. virtual ~input_adapter() {}
  7135. // native support
  7136. /// input adapter for input stream
  7137. static std::shared_ptr<input_adapter> create(std::istream& i)
  7138. {
  7139. return std::make_shared<cached_input_stream_adapter<16384>> (i);
  7140. }
  7141. /// input adapter for input stream
  7142. static std::shared_ptr<input_adapter> create(std::istream&& i)
  7143. {
  7144. return std::make_shared<cached_input_stream_adapter<16384>>(i);
  7145. }
  7146. /// input adapter for buffer
  7147. static std::shared_ptr<input_adapter> create(const char* b, size_t l)
  7148. {
  7149. return std::make_shared<input_buffer_adapter>(b, l);
  7150. }
  7151. // derived support
  7152. /// input adapter for string literal
  7153. template<typename CharT, typename std::enable_if<
  7154. std::is_pointer<CharT>::value and
  7155. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  7156. sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0>
  7157. static std::shared_ptr<input_adapter> create(CharT b)
  7158. {
  7159. return create(reinterpret_cast<const char*>(b),
  7160. std::strlen(reinterpret_cast<const char*>(b)));
  7161. }
  7162. /// input adapter for iterator range with contiguous storage
  7163. template<class IteratorType, typename std::enable_if<
  7164. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value
  7165. , int>::type
  7166. = 0>
  7167. static std::shared_ptr<input_adapter> create(IteratorType first, IteratorType last)
  7168. {
  7169. // assertion to check that the iterator range is indeed contiguous,
  7170. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  7171. assert(std::accumulate(first, last, std::pair<bool, int>(true, 0),
  7172. [&first](std::pair<bool, int> res, decltype(*first) val)
  7173. {
  7174. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  7175. return res;
  7176. }).first);
  7177. // assertion to check that each element is 1 byte long
  7178. static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  7179. "each element in the iterator range must have the size of 1 byte");
  7180. const auto len = static_cast<size_t>(std::distance(first, last));
  7181. if (JSON_LIKELY(len > 0))
  7182. {
  7183. // there is at least one element: use the address of first
  7184. return create(reinterpret_cast<const char*>(&(*first)), len);
  7185. }
  7186. else
  7187. {
  7188. // the address of first cannot be used - use nullptr
  7189. return create(nullptr, len);
  7190. }
  7191. }
  7192. /// input adapter for array
  7193. template<class T, std::size_t N>
  7194. static std::shared_ptr<input_adapter> create(T (&array)[N])
  7195. {
  7196. // delegate the call to the iterator-range overload
  7197. return create(std::begin(array), std::end(array));
  7198. }
  7199. /// input adapter for contiguous container
  7200. template<class ContiguousContainer, typename std::enable_if<
  7201. not std::is_pointer<ContiguousContainer>::value and
  7202. std::is_base_of<
  7203. std::random_access_iterator_tag,
  7204. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
  7205. , int>::type = 0>
  7206. static std::shared_ptr<input_adapter> create(const ContiguousContainer& c)
  7207. {
  7208. // delegate the call to the iterator-range overload
  7209. return create(std::begin(c), std::end(c));
  7210. }
  7211. };
  7212. /// a type to simplify interfaces
  7213. using input_adapter_t = std::shared_ptr<input_adapter>;
  7214. /// input adapter for cached stream input
  7215. template<std::size_t N>
  7216. class cached_input_stream_adapter : public input_adapter
  7217. {
  7218. public:
  7219. cached_input_stream_adapter(std::istream& i)
  7220. : is(i), start_position(is.tellg())
  7221. {
  7222. fill_buffer();
  7223. // skip byte order mark
  7224. if (fill_size >= 3 and buffer[0] == '\xEF' and buffer[1] == '\xBB' and buffer[2] == '\xBF')
  7225. {
  7226. buffer_pos += 3;
  7227. processed_chars += 3;
  7228. }
  7229. }
  7230. ~cached_input_stream_adapter() override
  7231. {
  7232. // clear stream flags
  7233. is.clear();
  7234. // We initially read a lot of characters into the buffer, and we
  7235. // may not have processed all of them. Therefore, we need to
  7236. // "rewind" the stream after the last processed char.
  7237. is.seekg(start_position);
  7238. is.ignore(static_cast<std::streamsize>(processed_chars));
  7239. // clear stream flags
  7240. is.clear();
  7241. }
  7242. int get_character() override
  7243. {
  7244. // check if refilling is necessary and possible
  7245. if (buffer_pos == fill_size and not eof)
  7246. {
  7247. fill_buffer();
  7248. // check and remember that filling did not yield new input
  7249. if (fill_size == 0)
  7250. {
  7251. eof = true;
  7252. return std::char_traits<char>::eof();
  7253. }
  7254. // the buffer is ready
  7255. buffer_pos = 0;
  7256. }
  7257. ++processed_chars;
  7258. assert(buffer_pos < buffer.size());
  7259. return buffer[buffer_pos++] & 0xFF;
  7260. }
  7261. std::string read(size_t offset, size_t length) override
  7262. {
  7263. // create buffer
  7264. std::string result(length, '\0');
  7265. // save stream position
  7266. const auto current_pos = is.tellg();
  7267. // save stream flags
  7268. const auto flags = is.rdstate();
  7269. // clear stream flags
  7270. is.clear();
  7271. // set stream position
  7272. is.seekg(static_cast<std::streamoff>(offset));
  7273. // read bytes
  7274. is.read(&result[0], static_cast<std::streamsize>(length));
  7275. // reset stream position
  7276. is.seekg(current_pos);
  7277. // reset stream flags
  7278. is.setstate(flags);
  7279. return result;
  7280. }
  7281. private:
  7282. void fill_buffer()
  7283. {
  7284. // fill
  7285. is.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
  7286. // store number of bytes in the buffer
  7287. fill_size = static_cast<size_t>(is.gcount());
  7288. }
  7289. /// the associated input stream
  7290. std::istream& is;
  7291. /// chars returned via get_character()
  7292. size_t processed_chars = 0;
  7293. /// chars processed in the current buffer
  7294. size_t buffer_pos = 0;
  7295. /// whether stream reached eof
  7296. bool eof = false;
  7297. /// how many chars have been copied to the buffer by last (re)fill
  7298. size_t fill_size = 0;
  7299. /// position of the stream when we started
  7300. const std::streampos start_position;
  7301. /// internal buffer
  7302. std::array<char, N> buffer{{}};
  7303. };
  7304. /// input adapter for buffer input
  7305. class input_buffer_adapter : public input_adapter
  7306. {
  7307. public:
  7308. input_buffer_adapter(const char* b, size_t l)
  7309. : input_adapter(), cursor(b), limit(b + l), start(b)
  7310. {
  7311. // skip byte order mark
  7312. if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
  7313. {
  7314. cursor += 3;
  7315. }
  7316. }
  7317. // delete because of pointer members
  7318. input_buffer_adapter(const input_buffer_adapter&) = delete;
  7319. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  7320. int get_character() noexcept override
  7321. {
  7322. if (JSON_LIKELY(cursor < limit))
  7323. {
  7324. return *(cursor++) & 0xFF;
  7325. }
  7326. else
  7327. {
  7328. return std::char_traits<char>::eof();
  7329. }
  7330. }
  7331. std::string read(size_t offset, size_t length) override
  7332. {
  7333. // avoid reading too many characters
  7334. const size_t max_length = static_cast<size_t>(limit - start);
  7335. return std::string(start + offset, (std::min)(length, max_length - offset));
  7336. }
  7337. private:
  7338. /// pointer to the current character
  7339. const char* cursor;
  7340. /// pointer past the last character
  7341. const char* limit;
  7342. /// pointer to the first character
  7343. const char* start;
  7344. };
  7345. //////////////////////////////////////////
  7346. // binary serialization/deserialization //
  7347. //////////////////////////////////////////
  7348. /// @name binary serialization/deserialization support
  7349. /// @{
  7350. private:
  7351. /*!
  7352. @brief deserialization of CBOR and MessagePack values
  7353. */
  7354. class binary_reader
  7355. {
  7356. public:
  7357. /*!
  7358. @brief create a binary reader
  7359. @param[in] adapter input adapter to read from
  7360. */
  7361. explicit binary_reader(input_adapter_t adapter)
  7362. : ia(adapter), is_little_endian(little_endianess())
  7363. {
  7364. assert(ia);
  7365. }
  7366. /*!
  7367. @brief create a JSON value from CBOR input
  7368. @param[in] get_char whether a new character should be retrieved from
  7369. the input (true, default) or whether the last
  7370. read character should be considered instead
  7371. @return JSON value created from CBOR input
  7372. @throw parse_error.110 if input ended unexpectedly
  7373. @throw parse_error.112 if unsupported byte was read
  7374. */
  7375. basic_json parse_cbor(const bool get_char = true)
  7376. {
  7377. switch (get_char ? get() : current)
  7378. {
  7379. // EOF
  7380. case std::char_traits<char>::eof():
  7381. {
  7382. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  7383. }
  7384. // Integer 0x00..0x17 (0..23)
  7385. case 0x00:
  7386. case 0x01:
  7387. case 0x02:
  7388. case 0x03:
  7389. case 0x04:
  7390. case 0x05:
  7391. case 0x06:
  7392. case 0x07:
  7393. case 0x08:
  7394. case 0x09:
  7395. case 0x0a:
  7396. case 0x0b:
  7397. case 0x0c:
  7398. case 0x0d:
  7399. case 0x0e:
  7400. case 0x0f:
  7401. case 0x10:
  7402. case 0x11:
  7403. case 0x12:
  7404. case 0x13:
  7405. case 0x14:
  7406. case 0x15:
  7407. case 0x16:
  7408. case 0x17:
  7409. {
  7410. return static_cast<number_unsigned_t>(current);
  7411. }
  7412. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7413. {
  7414. return get_number<uint8_t>();
  7415. }
  7416. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7417. {
  7418. return get_number<uint16_t>();
  7419. }
  7420. case 0x1a: // Unsigned integer (four-byte uint32_t follows)
  7421. {
  7422. return get_number<uint32_t>();
  7423. }
  7424. case 0x1b: // Unsigned integer (eight-byte uint64_t follows)
  7425. {
  7426. return get_number<uint64_t>();
  7427. }
  7428. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7429. case 0x20:
  7430. case 0x21:
  7431. case 0x22:
  7432. case 0x23:
  7433. case 0x24:
  7434. case 0x25:
  7435. case 0x26:
  7436. case 0x27:
  7437. case 0x28:
  7438. case 0x29:
  7439. case 0x2a:
  7440. case 0x2b:
  7441. case 0x2c:
  7442. case 0x2d:
  7443. case 0x2e:
  7444. case 0x2f:
  7445. case 0x30:
  7446. case 0x31:
  7447. case 0x32:
  7448. case 0x33:
  7449. case 0x34:
  7450. case 0x35:
  7451. case 0x36:
  7452. case 0x37:
  7453. {
  7454. return static_cast<int8_t>(0x20 - 1 - current);
  7455. }
  7456. case 0x38: // Negative integer (one-byte uint8_t follows)
  7457. {
  7458. // must be uint8_t !
  7459. return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
  7460. }
  7461. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7462. {
  7463. return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
  7464. }
  7465. case 0x3a: // Negative integer -1-n (four-byte uint32_t follows)
  7466. {
  7467. return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
  7468. }
  7469. case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows)
  7470. {
  7471. return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_number<uint64_t>());
  7472. }
  7473. // UTF-8 string (0x00..0x17 bytes follow)
  7474. case 0x60:
  7475. case 0x61:
  7476. case 0x62:
  7477. case 0x63:
  7478. case 0x64:
  7479. case 0x65:
  7480. case 0x66:
  7481. case 0x67:
  7482. case 0x68:
  7483. case 0x69:
  7484. case 0x6a:
  7485. case 0x6b:
  7486. case 0x6c:
  7487. case 0x6d:
  7488. case 0x6e:
  7489. case 0x6f:
  7490. case 0x70:
  7491. case 0x71:
  7492. case 0x72:
  7493. case 0x73:
  7494. case 0x74:
  7495. case 0x75:
  7496. case 0x76:
  7497. case 0x77:
  7498. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7499. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7500. case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
  7501. case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
  7502. case 0x7f: // UTF-8 string (indefinite length)
  7503. {
  7504. return get_cbor_string();
  7505. }
  7506. // array (0x00..0x17 data items follow)
  7507. case 0x80:
  7508. case 0x81:
  7509. case 0x82:
  7510. case 0x83:
  7511. case 0x84:
  7512. case 0x85:
  7513. case 0x86:
  7514. case 0x87:
  7515. case 0x88:
  7516. case 0x89:
  7517. case 0x8a:
  7518. case 0x8b:
  7519. case 0x8c:
  7520. case 0x8d:
  7521. case 0x8e:
  7522. case 0x8f:
  7523. case 0x90:
  7524. case 0x91:
  7525. case 0x92:
  7526. case 0x93:
  7527. case 0x94:
  7528. case 0x95:
  7529. case 0x96:
  7530. case 0x97:
  7531. {
  7532. basic_json result = value_t::array;
  7533. const auto len = static_cast<size_t>(current & 0x1f);
  7534. for (size_t i = 0; i < len; ++i)
  7535. {
  7536. result.push_back(parse_cbor());
  7537. }
  7538. return result;
  7539. }
  7540. case 0x98: // array (one-byte uint8_t for n follows)
  7541. {
  7542. basic_json result = value_t::array;
  7543. const auto len = static_cast<size_t>(get_number<uint8_t>());
  7544. for (size_t i = 0; i < len; ++i)
  7545. {
  7546. result.push_back(parse_cbor());
  7547. }
  7548. return result;
  7549. }
  7550. case 0x99: // array (two-byte uint16_t for n follow)
  7551. {
  7552. basic_json result = value_t::array;
  7553. const auto len = static_cast<size_t>(get_number<uint16_t>());
  7554. for (size_t i = 0; i < len; ++i)
  7555. {
  7556. result.push_back(parse_cbor());
  7557. }
  7558. return result;
  7559. }
  7560. case 0x9a: // array (four-byte uint32_t for n follow)
  7561. {
  7562. basic_json result = value_t::array;
  7563. const auto len = static_cast<size_t>(get_number<uint32_t>());
  7564. for (size_t i = 0; i < len; ++i)
  7565. {
  7566. result.push_back(parse_cbor());
  7567. }
  7568. return result;
  7569. }
  7570. case 0x9b: // array (eight-byte uint64_t for n follow)
  7571. {
  7572. basic_json result = value_t::array;
  7573. const auto len = static_cast<size_t>(get_number<uint64_t>());
  7574. for (size_t i = 0; i < len; ++i)
  7575. {
  7576. result.push_back(parse_cbor());
  7577. }
  7578. return result;
  7579. }
  7580. case 0x9f: // array (indefinite length)
  7581. {
  7582. basic_json result = value_t::array;
  7583. while (get() != 0xff)
  7584. {
  7585. result.push_back(parse_cbor(false));
  7586. }
  7587. return result;
  7588. }
  7589. // map (0x00..0x17 pairs of data items follow)
  7590. case 0xa0:
  7591. case 0xa1:
  7592. case 0xa2:
  7593. case 0xa3:
  7594. case 0xa4:
  7595. case 0xa5:
  7596. case 0xa6:
  7597. case 0xa7:
  7598. case 0xa8:
  7599. case 0xa9:
  7600. case 0xaa:
  7601. case 0xab:
  7602. case 0xac:
  7603. case 0xad:
  7604. case 0xae:
  7605. case 0xaf:
  7606. case 0xb0:
  7607. case 0xb1:
  7608. case 0xb2:
  7609. case 0xb3:
  7610. case 0xb4:
  7611. case 0xb5:
  7612. case 0xb6:
  7613. case 0xb7:
  7614. {
  7615. basic_json result = value_t::object;
  7616. const auto len = static_cast<size_t>(current & 0x1f);
  7617. for (size_t i = 0; i < len; ++i)
  7618. {
  7619. get();
  7620. auto key = get_cbor_string();
  7621. result[key] = parse_cbor();
  7622. }
  7623. return result;
  7624. }
  7625. case 0xb8: // map (one-byte uint8_t for n follows)
  7626. {
  7627. basic_json result = value_t::object;
  7628. const auto len = static_cast<size_t>(get_number<uint8_t>());
  7629. for (size_t i = 0; i < len; ++i)
  7630. {
  7631. get();
  7632. auto key = get_cbor_string();
  7633. result[key] = parse_cbor();
  7634. }
  7635. return result;
  7636. }
  7637. case 0xb9: // map (two-byte uint16_t for n follow)
  7638. {
  7639. basic_json result = value_t::object;
  7640. const auto len = static_cast<size_t>(get_number<uint16_t>());
  7641. for (size_t i = 0; i < len; ++i)
  7642. {
  7643. get();
  7644. auto key = get_cbor_string();
  7645. result[key] = parse_cbor();
  7646. }
  7647. return result;
  7648. }
  7649. case 0xba: // map (four-byte uint32_t for n follow)
  7650. {
  7651. basic_json result = value_t::object;
  7652. const auto len = static_cast<size_t>(get_number<uint32_t>());
  7653. for (size_t i = 0; i < len; ++i)
  7654. {
  7655. get();
  7656. auto key = get_cbor_string();
  7657. result[key] = parse_cbor();
  7658. }
  7659. return result;
  7660. }
  7661. case 0xbb: // map (eight-byte uint64_t for n follow)
  7662. {
  7663. basic_json result = value_t::object;
  7664. const auto len = static_cast<size_t>(get_number<uint64_t>());
  7665. for (size_t i = 0; i < len; ++i)
  7666. {
  7667. get();
  7668. auto key = get_cbor_string();
  7669. result[key] = parse_cbor();
  7670. }
  7671. return result;
  7672. }
  7673. case 0xbf: // map (indefinite length)
  7674. {
  7675. basic_json result = value_t::object;
  7676. while (get() != 0xff)
  7677. {
  7678. auto key = get_cbor_string();
  7679. result[key] = parse_cbor();
  7680. }
  7681. return result;
  7682. }
  7683. case 0xf4: // false
  7684. {
  7685. return false;
  7686. }
  7687. case 0xf5: // true
  7688. {
  7689. return true;
  7690. }
  7691. case 0xf6: // null
  7692. {
  7693. return value_t::null;
  7694. }
  7695. case 0xf9: // Half-Precision Float (two-byte IEEE 754)
  7696. {
  7697. const int byte1 = get();
  7698. check_eof();
  7699. const int byte2 = get();
  7700. check_eof();
  7701. // code from RFC 7049, Appendix D, Figure 3:
  7702. // As half-precision floating-point numbers were only added
  7703. // to IEEE 754 in 2008, today's programming platforms often
  7704. // still only have limited support for them. It is very
  7705. // easy to include at least decoding support for them even
  7706. // without such support. An example of a small decoder for
  7707. // half-precision floating-point numbers in the C language
  7708. // is shown in Fig. 3.
  7709. const int half = (byte1 << 8) + byte2;
  7710. const int exp = (half >> 10) & 0x1f;
  7711. const int mant = half & 0x3ff;
  7712. double val;
  7713. if (exp == 0)
  7714. {
  7715. val = std::ldexp(mant, -24);
  7716. }
  7717. else if (exp != 31)
  7718. {
  7719. val = std::ldexp(mant + 1024, exp - 25);
  7720. }
  7721. else
  7722. {
  7723. val = (mant == 0)
  7724. ? std::numeric_limits<double>::infinity()
  7725. : std::numeric_limits<double>::quiet_NaN();
  7726. }
  7727. return (half & 0x8000) != 0 ? -val : val;
  7728. }
  7729. case 0xfa: // Single-Precision Float (four-byte IEEE 754)
  7730. {
  7731. return get_number<float>();
  7732. }
  7733. case 0xfb: // Double-Precision Float (eight-byte IEEE 754)
  7734. {
  7735. return get_number<double>();
  7736. }
  7737. default: // anything else (0xFF is handled inside the other types)
  7738. {
  7739. std::stringstream ss;
  7740. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  7741. JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
  7742. }
  7743. }
  7744. }
  7745. /*!
  7746. @brief create a JSON value from MessagePack input
  7747. @return JSON value created from MessagePack input
  7748. @throw parse_error.110 if input ended unexpectedly
  7749. @throw parse_error.112 if unsupported byte was read
  7750. */
  7751. basic_json parse_msgpack()
  7752. {
  7753. switch (get())
  7754. {
  7755. // EOF
  7756. case std::char_traits<char>::eof():
  7757. {
  7758. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  7759. }
  7760. // positive fixint
  7761. case 0x00:
  7762. case 0x01:
  7763. case 0x02:
  7764. case 0x03:
  7765. case 0x04:
  7766. case 0x05:
  7767. case 0x06:
  7768. case 0x07:
  7769. case 0x08:
  7770. case 0x09:
  7771. case 0x0a:
  7772. case 0x0b:
  7773. case 0x0c:
  7774. case 0x0d:
  7775. case 0x0e:
  7776. case 0x0f:
  7777. case 0x10:
  7778. case 0x11:
  7779. case 0x12:
  7780. case 0x13:
  7781. case 0x14:
  7782. case 0x15:
  7783. case 0x16:
  7784. case 0x17:
  7785. case 0x18:
  7786. case 0x19:
  7787. case 0x1a:
  7788. case 0x1b:
  7789. case 0x1c:
  7790. case 0x1d:
  7791. case 0x1e:
  7792. case 0x1f:
  7793. case 0x20:
  7794. case 0x21:
  7795. case 0x22:
  7796. case 0x23:
  7797. case 0x24:
  7798. case 0x25:
  7799. case 0x26:
  7800. case 0x27:
  7801. case 0x28:
  7802. case 0x29:
  7803. case 0x2a:
  7804. case 0x2b:
  7805. case 0x2c:
  7806. case 0x2d:
  7807. case 0x2e:
  7808. case 0x2f:
  7809. case 0x30:
  7810. case 0x31:
  7811. case 0x32:
  7812. case 0x33:
  7813. case 0x34:
  7814. case 0x35:
  7815. case 0x36:
  7816. case 0x37:
  7817. case 0x38:
  7818. case 0x39:
  7819. case 0x3a:
  7820. case 0x3b:
  7821. case 0x3c:
  7822. case 0x3d:
  7823. case 0x3e:
  7824. case 0x3f:
  7825. case 0x40:
  7826. case 0x41:
  7827. case 0x42:
  7828. case 0x43:
  7829. case 0x44:
  7830. case 0x45:
  7831. case 0x46:
  7832. case 0x47:
  7833. case 0x48:
  7834. case 0x49:
  7835. case 0x4a:
  7836. case 0x4b:
  7837. case 0x4c:
  7838. case 0x4d:
  7839. case 0x4e:
  7840. case 0x4f:
  7841. case 0x50:
  7842. case 0x51:
  7843. case 0x52:
  7844. case 0x53:
  7845. case 0x54:
  7846. case 0x55:
  7847. case 0x56:
  7848. case 0x57:
  7849. case 0x58:
  7850. case 0x59:
  7851. case 0x5a:
  7852. case 0x5b:
  7853. case 0x5c:
  7854. case 0x5d:
  7855. case 0x5e:
  7856. case 0x5f:
  7857. case 0x60:
  7858. case 0x61:
  7859. case 0x62:
  7860. case 0x63:
  7861. case 0x64:
  7862. case 0x65:
  7863. case 0x66:
  7864. case 0x67:
  7865. case 0x68:
  7866. case 0x69:
  7867. case 0x6a:
  7868. case 0x6b:
  7869. case 0x6c:
  7870. case 0x6d:
  7871. case 0x6e:
  7872. case 0x6f:
  7873. case 0x70:
  7874. case 0x71:
  7875. case 0x72:
  7876. case 0x73:
  7877. case 0x74:
  7878. case 0x75:
  7879. case 0x76:
  7880. case 0x77:
  7881. case 0x78:
  7882. case 0x79:
  7883. case 0x7a:
  7884. case 0x7b:
  7885. case 0x7c:
  7886. case 0x7d:
  7887. case 0x7e:
  7888. case 0x7f:
  7889. {
  7890. return static_cast<number_unsigned_t>(current);
  7891. }
  7892. // fixmap
  7893. case 0x80:
  7894. case 0x81:
  7895. case 0x82:
  7896. case 0x83:
  7897. case 0x84:
  7898. case 0x85:
  7899. case 0x86:
  7900. case 0x87:
  7901. case 0x88:
  7902. case 0x89:
  7903. case 0x8a:
  7904. case 0x8b:
  7905. case 0x8c:
  7906. case 0x8d:
  7907. case 0x8e:
  7908. case 0x8f:
  7909. {
  7910. basic_json result = value_t::object;
  7911. const auto len = static_cast<size_t>(current & 0x0f);
  7912. for (size_t i = 0; i < len; ++i)
  7913. {
  7914. get();
  7915. auto key = get_msgpack_string();
  7916. result[key] = parse_msgpack();
  7917. }
  7918. return result;
  7919. }
  7920. // fixarray
  7921. case 0x90:
  7922. case 0x91:
  7923. case 0x92:
  7924. case 0x93:
  7925. case 0x94:
  7926. case 0x95:
  7927. case 0x96:
  7928. case 0x97:
  7929. case 0x98:
  7930. case 0x99:
  7931. case 0x9a:
  7932. case 0x9b:
  7933. case 0x9c:
  7934. case 0x9d:
  7935. case 0x9e:
  7936. case 0x9f:
  7937. {
  7938. basic_json result = value_t::array;
  7939. const auto len = static_cast<size_t>(current & 0x0f);
  7940. for (size_t i = 0; i < len; ++i)
  7941. {
  7942. result.push_back(parse_msgpack());
  7943. }
  7944. return result;
  7945. }
  7946. // fixstr
  7947. case 0xa0:
  7948. case 0xa1:
  7949. case 0xa2:
  7950. case 0xa3:
  7951. case 0xa4:
  7952. case 0xa5:
  7953. case 0xa6:
  7954. case 0xa7:
  7955. case 0xa8:
  7956. case 0xa9:
  7957. case 0xaa:
  7958. case 0xab:
  7959. case 0xac:
  7960. case 0xad:
  7961. case 0xae:
  7962. case 0xaf:
  7963. case 0xb0:
  7964. case 0xb1:
  7965. case 0xb2:
  7966. case 0xb3:
  7967. case 0xb4:
  7968. case 0xb5:
  7969. case 0xb6:
  7970. case 0xb7:
  7971. case 0xb8:
  7972. case 0xb9:
  7973. case 0xba:
  7974. case 0xbb:
  7975. case 0xbc:
  7976. case 0xbd:
  7977. case 0xbe:
  7978. case 0xbf:
  7979. {
  7980. return get_msgpack_string();
  7981. }
  7982. case 0xc0: // nil
  7983. {
  7984. return value_t::null;
  7985. }
  7986. case 0xc2: // false
  7987. {
  7988. return false;
  7989. }
  7990. case 0xc3: // true
  7991. {
  7992. return true;
  7993. }
  7994. case 0xca: // float 32
  7995. {
  7996. return get_number<float>();
  7997. }
  7998. case 0xcb: // float 64
  7999. {
  8000. return get_number<double>();
  8001. }
  8002. case 0xcc: // uint 8
  8003. {
  8004. return get_number<uint8_t>();
  8005. }
  8006. case 0xcd: // uint 16
  8007. {
  8008. return get_number<uint16_t>();
  8009. }
  8010. case 0xce: // uint 32
  8011. {
  8012. return get_number<uint32_t>();
  8013. }
  8014. case 0xcf: // uint 64
  8015. {
  8016. return get_number<uint64_t>();
  8017. }
  8018. case 0xd0: // int 8
  8019. {
  8020. return get_number<int8_t>();
  8021. }
  8022. case 0xd1: // int 16
  8023. {
  8024. return get_number<int16_t>();
  8025. }
  8026. case 0xd2: // int 32
  8027. {
  8028. return get_number<int32_t>();
  8029. }
  8030. case 0xd3: // int 64
  8031. {
  8032. return get_number<int64_t>();
  8033. }
  8034. case 0xd9: // str 8
  8035. case 0xda: // str 16
  8036. case 0xdb: // str 32
  8037. {
  8038. return get_msgpack_string();
  8039. }
  8040. case 0xdc: // array 16
  8041. {
  8042. basic_json result = value_t::array;
  8043. const auto len = static_cast<size_t>(get_number<uint16_t>());
  8044. for (size_t i = 0; i < len; ++i)
  8045. {
  8046. result.push_back(parse_msgpack());
  8047. }
  8048. return result;
  8049. }
  8050. case 0xdd: // array 32
  8051. {
  8052. basic_json result = value_t::array;
  8053. const auto len = static_cast<size_t>(get_number<uint32_t>());
  8054. for (size_t i = 0; i < len; ++i)
  8055. {
  8056. result.push_back(parse_msgpack());
  8057. }
  8058. return result;
  8059. }
  8060. case 0xde: // map 16
  8061. {
  8062. basic_json result = value_t::object;
  8063. const auto len = static_cast<size_t>(get_number<uint16_t>());
  8064. for (size_t i = 0; i < len; ++i)
  8065. {
  8066. get();
  8067. auto key = get_msgpack_string();
  8068. result[key] = parse_msgpack();
  8069. }
  8070. return result;
  8071. }
  8072. case 0xdf: // map 32
  8073. {
  8074. basic_json result = value_t::object;
  8075. const auto len = static_cast<size_t>(get_number<uint32_t>());
  8076. for (size_t i = 0; i < len; ++i)
  8077. {
  8078. get();
  8079. auto key = get_msgpack_string();
  8080. result[key] = parse_msgpack();
  8081. }
  8082. return result;
  8083. }
  8084. // positive fixint
  8085. case 0xe0:
  8086. case 0xe1:
  8087. case 0xe2:
  8088. case 0xe3:
  8089. case 0xe4:
  8090. case 0xe5:
  8091. case 0xe6:
  8092. case 0xe7:
  8093. case 0xe8:
  8094. case 0xe9:
  8095. case 0xea:
  8096. case 0xeb:
  8097. case 0xec:
  8098. case 0xed:
  8099. case 0xee:
  8100. case 0xef:
  8101. case 0xf0:
  8102. case 0xf1:
  8103. case 0xf2:
  8104. case 0xf3:
  8105. case 0xf4:
  8106. case 0xf5:
  8107. case 0xf6:
  8108. case 0xf7:
  8109. case 0xf8:
  8110. case 0xf9:
  8111. case 0xfa:
  8112. case 0xfb:
  8113. case 0xfc:
  8114. case 0xfd:
  8115. case 0xfe:
  8116. case 0xff:
  8117. {
  8118. return static_cast<int8_t>(current);
  8119. }
  8120. default: // anything else
  8121. {
  8122. std::stringstream ss;
  8123. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  8124. JSON_THROW(parse_error::create(112, chars_read, "error reading MessagePack; last byte: 0x" + ss.str()));
  8125. }
  8126. }
  8127. }
  8128. /*!
  8129. @brief determine system byte order
  8130. @return true iff system's byte order is little endian
  8131. @note from http://stackoverflow.com/a/1001328/266378
  8132. */
  8133. static bool little_endianess() noexcept
  8134. {
  8135. int num = 1;
  8136. return (*reinterpret_cast<char*>(&num) == 1);
  8137. }
  8138. private:
  8139. /*!
  8140. @brief get next character from the input
  8141. This function provides the interface to the used input adapter. It does
  8142. not throw in case the input reached EOF, but returns
  8143. `std::char_traits<char>::eof()` in that case.
  8144. @return character read from the input
  8145. */
  8146. int get()
  8147. {
  8148. ++chars_read;
  8149. return (current = ia->get_character());
  8150. }
  8151. /*
  8152. @brief read a number from the input
  8153. @tparam NumberType the type of the number
  8154. @return number of type @a NumberType
  8155. @note This function needs to respect the system's endianess, because
  8156. bytes in CBOR and MessagePack are stored in network order (big
  8157. endian) and therefore need reordering on little endian systems.
  8158. @throw parse_error.110 if input has less than `sizeof(NumberType)`
  8159. bytes
  8160. */
  8161. template<typename NumberType>
  8162. NumberType get_number()
  8163. {
  8164. // step 1: read input into array with system's byte order
  8165. std::array<uint8_t, sizeof(NumberType)> vec;
  8166. for (size_t i = 0; i < sizeof(NumberType); ++i)
  8167. {
  8168. get();
  8169. check_eof();
  8170. // reverse byte order prior to conversion if necessary
  8171. if (is_little_endian)
  8172. {
  8173. vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
  8174. }
  8175. else
  8176. {
  8177. vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
  8178. }
  8179. }
  8180. // step 2: convert array into number of type T and return
  8181. NumberType result;
  8182. std::memcpy(&result, vec.data(), sizeof(NumberType));
  8183. return result;
  8184. }
  8185. /*!
  8186. @brief create a string by reading characters from the input
  8187. @param[in] len number of bytes to read
  8188. @note We can not reserve @a len bytes for the result, because @a len
  8189. may be too large. Usually, @ref check_eof() detects the end of
  8190. the input before we run out of string memory.
  8191. @return string created by reading @a len bytes
  8192. @throw parse_error.110 if input has less than @a len bytes
  8193. */
  8194. std::string get_string(const size_t len)
  8195. {
  8196. std::string result;
  8197. for (size_t i = 0; i < len; ++i)
  8198. {
  8199. get();
  8200. check_eof();
  8201. result.append(1, static_cast<char>(current));
  8202. }
  8203. return result;
  8204. }
  8205. /*!
  8206. @brief reads a CBOR string
  8207. This function first reads starting bytes to determine the expected
  8208. string length and then copies this number of bytes into a string.
  8209. Additionally, CBOR's strings with indefinite lengths are supported.
  8210. @return string
  8211. @throw parse_error.110 if input ended
  8212. @throw parse_error.113 if an unexpected byte is read
  8213. */
  8214. std::string get_cbor_string()
  8215. {
  8216. check_eof();
  8217. switch (current)
  8218. {
  8219. // UTF-8 string (0x00..0x17 bytes follow)
  8220. case 0x60:
  8221. case 0x61:
  8222. case 0x62:
  8223. case 0x63:
  8224. case 0x64:
  8225. case 0x65:
  8226. case 0x66:
  8227. case 0x67:
  8228. case 0x68:
  8229. case 0x69:
  8230. case 0x6a:
  8231. case 0x6b:
  8232. case 0x6c:
  8233. case 0x6d:
  8234. case 0x6e:
  8235. case 0x6f:
  8236. case 0x70:
  8237. case 0x71:
  8238. case 0x72:
  8239. case 0x73:
  8240. case 0x74:
  8241. case 0x75:
  8242. case 0x76:
  8243. case 0x77:
  8244. {
  8245. const auto len = static_cast<size_t>(current & 0x1f);
  8246. return get_string(len);
  8247. }
  8248. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  8249. {
  8250. const auto len = static_cast<size_t>(get_number<uint8_t>());
  8251. return get_string(len);
  8252. }
  8253. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  8254. {
  8255. const auto len = static_cast<size_t>(get_number<uint16_t>());
  8256. return get_string(len);
  8257. }
  8258. case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
  8259. {
  8260. const auto len = static_cast<size_t>(get_number<uint32_t>());
  8261. return get_string(len);
  8262. }
  8263. case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
  8264. {
  8265. const auto len = static_cast<size_t>(get_number<uint64_t>());
  8266. return get_string(len);
  8267. }
  8268. case 0x7f: // UTF-8 string (indefinite length)
  8269. {
  8270. std::string result;
  8271. while (get() != 0xff)
  8272. {
  8273. check_eof();
  8274. result.append(1, static_cast<char>(current));
  8275. }
  8276. return result;
  8277. }
  8278. default:
  8279. {
  8280. std::stringstream ss;
  8281. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  8282. JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
  8283. }
  8284. }
  8285. }
  8286. /*!
  8287. @brief reads a MessagePack string
  8288. This function first reads starting bytes to determine the expected
  8289. string length and then copies this number of bytes into a string.
  8290. @return string
  8291. @throw parse_error.110 if input ended
  8292. @throw parse_error.113 if an unexpected byte is read
  8293. */
  8294. std::string get_msgpack_string()
  8295. {
  8296. check_eof();
  8297. switch (current)
  8298. {
  8299. // fixstr
  8300. case 0xa0:
  8301. case 0xa1:
  8302. case 0xa2:
  8303. case 0xa3:
  8304. case 0xa4:
  8305. case 0xa5:
  8306. case 0xa6:
  8307. case 0xa7:
  8308. case 0xa8:
  8309. case 0xa9:
  8310. case 0xaa:
  8311. case 0xab:
  8312. case 0xac:
  8313. case 0xad:
  8314. case 0xae:
  8315. case 0xaf:
  8316. case 0xb0:
  8317. case 0xb1:
  8318. case 0xb2:
  8319. case 0xb3:
  8320. case 0xb4:
  8321. case 0xb5:
  8322. case 0xb6:
  8323. case 0xb7:
  8324. case 0xb8:
  8325. case 0xb9:
  8326. case 0xba:
  8327. case 0xbb:
  8328. case 0xbc:
  8329. case 0xbd:
  8330. case 0xbe:
  8331. case 0xbf:
  8332. {
  8333. const auto len = static_cast<size_t>(current & 0x1f);
  8334. return get_string(len);
  8335. }
  8336. case 0xd9: // str 8
  8337. {
  8338. const auto len = static_cast<size_t>(get_number<uint8_t>());
  8339. return get_string(len);
  8340. }
  8341. case 0xda: // str 16
  8342. {
  8343. const auto len = static_cast<size_t>(get_number<uint16_t>());
  8344. return get_string(len);
  8345. }
  8346. case 0xdb: // str 32
  8347. {
  8348. const auto len = static_cast<size_t>(get_number<uint32_t>());
  8349. return get_string(len);
  8350. }
  8351. default:
  8352. {
  8353. std::stringstream ss;
  8354. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  8355. JSON_THROW(parse_error::create(113, chars_read, "expected a MessagePack string; last byte: 0x" + ss.str()));
  8356. }
  8357. }
  8358. }
  8359. /*!
  8360. @brief check if input ended
  8361. @throw parse_error.110 if input ended
  8362. */
  8363. void check_eof() const
  8364. {
  8365. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  8366. {
  8367. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  8368. }
  8369. }
  8370. private:
  8371. /// input adapter
  8372. input_adapter_t ia = nullptr;
  8373. /// the current character
  8374. int current = std::char_traits<char>::eof();
  8375. /// the number of characters read
  8376. size_t chars_read = 0;
  8377. /// whether we can assume little endianess
  8378. const bool is_little_endian = true;
  8379. };
  8380. /*!
  8381. @brief serialization to CBOR and MessagePack values
  8382. */
  8383. class binary_writer
  8384. {
  8385. public:
  8386. /*!
  8387. @brief create a binary writer
  8388. @param[in] adapter output adapter to write to
  8389. */
  8390. explicit binary_writer(output_adapter_t<uint8_t> adapter)
  8391. : is_little_endian(binary_reader::little_endianess()), oa(adapter)
  8392. {
  8393. assert(oa);
  8394. }
  8395. /*!
  8396. @brief[in] j JSON value to serialize
  8397. */
  8398. void write_cbor(const basic_json& j)
  8399. {
  8400. switch (j.type())
  8401. {
  8402. case value_t::null:
  8403. {
  8404. oa->write_character(0xf6);
  8405. break;
  8406. }
  8407. case value_t::boolean:
  8408. {
  8409. oa->write_character(j.m_value.boolean ? 0xf5 : 0xf4);
  8410. break;
  8411. }
  8412. case value_t::number_integer:
  8413. {
  8414. if (j.m_value.number_integer >= 0)
  8415. {
  8416. // CBOR does not differentiate between positive signed
  8417. // integers and unsigned integers. Therefore, we used the
  8418. // code from the value_t::number_unsigned case here.
  8419. if (j.m_value.number_integer <= 0x17)
  8420. {
  8421. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  8422. }
  8423. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  8424. {
  8425. oa->write_character(0x18);
  8426. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  8427. }
  8428. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  8429. {
  8430. oa->write_character(0x19);
  8431. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  8432. }
  8433. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  8434. {
  8435. oa->write_character(0x1a);
  8436. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  8437. }
  8438. else
  8439. {
  8440. oa->write_character(0x1b);
  8441. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  8442. }
  8443. }
  8444. else
  8445. {
  8446. // The conversions below encode the sign in the first
  8447. // byte, and the value is converted to a positive number.
  8448. const auto positive_number = -1 - j.m_value.number_integer;
  8449. if (j.m_value.number_integer >= -24)
  8450. {
  8451. write_number(static_cast<uint8_t>(0x20 + positive_number));
  8452. }
  8453. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  8454. {
  8455. oa->write_character(0x38);
  8456. write_number(static_cast<uint8_t>(positive_number));
  8457. }
  8458. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  8459. {
  8460. oa->write_character(0x39);
  8461. write_number(static_cast<uint16_t>(positive_number));
  8462. }
  8463. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  8464. {
  8465. oa->write_character(0x3a);
  8466. write_number(static_cast<uint32_t>(positive_number));
  8467. }
  8468. else
  8469. {
  8470. oa->write_character(0x3b);
  8471. write_number(static_cast<uint64_t>(positive_number));
  8472. }
  8473. }
  8474. break;
  8475. }
  8476. case value_t::number_unsigned:
  8477. {
  8478. if (j.m_value.number_unsigned <= 0x17)
  8479. {
  8480. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  8481. }
  8482. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  8483. {
  8484. oa->write_character(0x18);
  8485. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  8486. }
  8487. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  8488. {
  8489. oa->write_character(0x19);
  8490. write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
  8491. }
  8492. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  8493. {
  8494. oa->write_character(0x1a);
  8495. write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
  8496. }
  8497. else
  8498. {
  8499. oa->write_character(0x1b);
  8500. write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
  8501. }
  8502. break;
  8503. }
  8504. case value_t::number_float:
  8505. {
  8506. // Double-Precision Float
  8507. oa->write_character(0xfb);
  8508. write_number(j.m_value.number_float);
  8509. break;
  8510. }
  8511. case value_t::string:
  8512. {
  8513. // step 1: write control byte and the string length
  8514. const auto N = j.m_value.string->size();
  8515. if (N <= 0x17)
  8516. {
  8517. write_number(static_cast<uint8_t>(0x60 + N));
  8518. }
  8519. else if (N <= 0xff)
  8520. {
  8521. oa->write_character(0x78);
  8522. write_number(static_cast<uint8_t>(N));
  8523. }
  8524. else if (N <= 0xffff)
  8525. {
  8526. oa->write_character(0x79);
  8527. write_number(static_cast<uint16_t>(N));
  8528. }
  8529. else if (N <= 0xffffffff)
  8530. {
  8531. oa->write_character(0x7a);
  8532. write_number(static_cast<uint32_t>(N));
  8533. }
  8534. // LCOV_EXCL_START
  8535. else if (N <= 0xffffffffffffffff)
  8536. {
  8537. oa->write_character(0x7b);
  8538. write_number(static_cast<uint64_t>(N));
  8539. }
  8540. // LCOV_EXCL_STOP
  8541. // step 2: write the string
  8542. oa->write_characters(reinterpret_cast<const uint8_t*>(j.m_value.string->c_str()),
  8543. j.m_value.string->size());
  8544. break;
  8545. }
  8546. case value_t::array:
  8547. {
  8548. // step 1: write control byte and the array size
  8549. const auto N = j.m_value.array->size();
  8550. if (N <= 0x17)
  8551. {
  8552. write_number(static_cast<uint8_t>(0x80 + N));
  8553. }
  8554. else if (N <= 0xff)
  8555. {
  8556. oa->write_character(0x98);
  8557. write_number(static_cast<uint8_t>(N));
  8558. }
  8559. else if (N <= 0xffff)
  8560. {
  8561. oa->write_character(0x99);
  8562. write_number(static_cast<uint16_t>(N));
  8563. }
  8564. else if (N <= 0xffffffff)
  8565. {
  8566. oa->write_character(0x9a);
  8567. write_number(static_cast<uint32_t>(N));
  8568. }
  8569. // LCOV_EXCL_START
  8570. else if (N <= 0xffffffffffffffff)
  8571. {
  8572. oa->write_character(0x9b);
  8573. write_number(static_cast<uint64_t>(N));
  8574. }
  8575. // LCOV_EXCL_STOP
  8576. // step 2: write each element
  8577. for (const auto& el : *j.m_value.array)
  8578. {
  8579. write_cbor(el);
  8580. }
  8581. break;
  8582. }
  8583. case value_t::object:
  8584. {
  8585. // step 1: write control byte and the object size
  8586. const auto N = j.m_value.object->size();
  8587. if (N <= 0x17)
  8588. {
  8589. write_number(static_cast<uint8_t>(0xa0 + N));
  8590. }
  8591. else if (N <= 0xff)
  8592. {
  8593. oa->write_character(0xb8);
  8594. write_number(static_cast<uint8_t>(N));
  8595. }
  8596. else if (N <= 0xffff)
  8597. {
  8598. oa->write_character(0xb9);
  8599. write_number(static_cast<uint16_t>(N));
  8600. }
  8601. else if (N <= 0xffffffff)
  8602. {
  8603. oa->write_character(0xba);
  8604. write_number(static_cast<uint32_t>(N));
  8605. }
  8606. // LCOV_EXCL_START
  8607. else if (N <= 0xffffffffffffffff)
  8608. {
  8609. oa->write_character(0xbb);
  8610. write_number(static_cast<uint64_t>(N));
  8611. }
  8612. // LCOV_EXCL_STOP
  8613. // step 2: write each element
  8614. for (const auto& el : *j.m_value.object)
  8615. {
  8616. write_cbor(el.first);
  8617. write_cbor(el.second);
  8618. }
  8619. break;
  8620. }
  8621. default:
  8622. {
  8623. break;
  8624. }
  8625. }
  8626. }
  8627. /*!
  8628. @brief[in] j JSON value to serialize
  8629. */
  8630. void write_msgpack(const basic_json& j)
  8631. {
  8632. switch (j.type())
  8633. {
  8634. case value_t::null:
  8635. {
  8636. // nil
  8637. oa->write_character(0xc0);
  8638. break;
  8639. }
  8640. case value_t::boolean:
  8641. {
  8642. // true and false
  8643. oa->write_character(j.m_value.boolean ? 0xc3 : 0xc2);
  8644. break;
  8645. }
  8646. case value_t::number_integer:
  8647. {
  8648. if (j.m_value.number_integer >= 0)
  8649. {
  8650. // MessagePack does not differentiate between positive
  8651. // signed integers and unsigned integers. Therefore, we
  8652. // used the code from the value_t::number_unsigned case
  8653. // here.
  8654. if (j.m_value.number_unsigned < 128)
  8655. {
  8656. // positive fixnum
  8657. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  8658. }
  8659. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  8660. {
  8661. // uint 8
  8662. oa->write_character(0xcc);
  8663. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  8664. }
  8665. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  8666. {
  8667. // uint 16
  8668. oa->write_character(0xcd);
  8669. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  8670. }
  8671. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  8672. {
  8673. // uint 32
  8674. oa->write_character(0xce);
  8675. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  8676. }
  8677. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  8678. {
  8679. // uint 64
  8680. oa->write_character(0xcf);
  8681. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  8682. }
  8683. }
  8684. else
  8685. {
  8686. if (j.m_value.number_integer >= -32)
  8687. {
  8688. // negative fixnum
  8689. write_number(static_cast<int8_t>(j.m_value.number_integer));
  8690. }
  8691. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  8692. {
  8693. // int 8
  8694. oa->write_character(0xd0);
  8695. write_number(static_cast<int8_t>(j.m_value.number_integer));
  8696. }
  8697. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  8698. {
  8699. // int 16
  8700. oa->write_character(0xd1);
  8701. write_number(static_cast<int16_t>(j.m_value.number_integer));
  8702. }
  8703. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  8704. {
  8705. // int 32
  8706. oa->write_character(0xd2);
  8707. write_number(static_cast<int32_t>(j.m_value.number_integer));
  8708. }
  8709. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  8710. {
  8711. // int 64
  8712. oa->write_character(0xd3);
  8713. write_number(static_cast<int64_t>(j.m_value.number_integer));
  8714. }
  8715. }
  8716. break;
  8717. }
  8718. case value_t::number_unsigned:
  8719. {
  8720. if (j.m_value.number_unsigned < 128)
  8721. {
  8722. // positive fixnum
  8723. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  8724. }
  8725. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  8726. {
  8727. // uint 8
  8728. oa->write_character(0xcc);
  8729. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  8730. }
  8731. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  8732. {
  8733. // uint 16
  8734. oa->write_character(0xcd);
  8735. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  8736. }
  8737. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  8738. {
  8739. // uint 32
  8740. oa->write_character(0xce);
  8741. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  8742. }
  8743. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  8744. {
  8745. // uint 64
  8746. oa->write_character(0xcf);
  8747. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  8748. }
  8749. break;
  8750. }
  8751. case value_t::number_float:
  8752. {
  8753. // float 64
  8754. oa->write_character(0xcb);
  8755. write_number(j.m_value.number_float);
  8756. break;
  8757. }
  8758. case value_t::string:
  8759. {
  8760. // step 1: write control byte and the string length
  8761. const auto N = j.m_value.string->size();
  8762. if (N <= 31)
  8763. {
  8764. // fixstr
  8765. write_number(static_cast<uint8_t>(0xa0 | N));
  8766. }
  8767. else if (N <= 255)
  8768. {
  8769. // str 8
  8770. oa->write_character(0xd9);
  8771. write_number(static_cast<uint8_t>(N));
  8772. }
  8773. else if (N <= 65535)
  8774. {
  8775. // str 16
  8776. oa->write_character(0xda);
  8777. write_number(static_cast<uint16_t>(N));
  8778. }
  8779. else if (N <= 4294967295)
  8780. {
  8781. // str 32
  8782. oa->write_character(0xdb);
  8783. write_number(static_cast<uint32_t>(N));
  8784. }
  8785. // step 2: write the string
  8786. oa->write_characters(reinterpret_cast<const uint8_t*>(j.m_value.string->c_str()),
  8787. j.m_value.string->size());
  8788. break;
  8789. }
  8790. case value_t::array:
  8791. {
  8792. // step 1: write control byte and the array size
  8793. const auto N = j.m_value.array->size();
  8794. if (N <= 15)
  8795. {
  8796. // fixarray
  8797. write_number(static_cast<uint8_t>(0x90 | N));
  8798. }
  8799. else if (N <= 0xffff)
  8800. {
  8801. // array 16
  8802. oa->write_character(0xdc);
  8803. write_number(static_cast<uint16_t>(N));
  8804. }
  8805. else if (N <= 0xffffffff)
  8806. {
  8807. // array 32
  8808. oa->write_character(0xdd);
  8809. write_number(static_cast<uint32_t>(N));
  8810. }
  8811. // step 2: write each element
  8812. for (const auto& el : *j.m_value.array)
  8813. {
  8814. write_msgpack(el);
  8815. }
  8816. break;
  8817. }
  8818. case value_t::object:
  8819. {
  8820. // step 1: write control byte and the object size
  8821. const auto N = j.m_value.object->size();
  8822. if (N <= 15)
  8823. {
  8824. // fixmap
  8825. write_number(static_cast<uint8_t>(0x80 | (N & 0xf)));
  8826. }
  8827. else if (N <= 65535)
  8828. {
  8829. // map 16
  8830. oa->write_character(0xde);
  8831. write_number(static_cast<uint16_t>(N));
  8832. }
  8833. else if (N <= 4294967295)
  8834. {
  8835. // map 32
  8836. oa->write_character(0xdf);
  8837. write_number(static_cast<uint32_t>(N));
  8838. }
  8839. // step 2: write each element
  8840. for (const auto& el : *j.m_value.object)
  8841. {
  8842. write_msgpack(el.first);
  8843. write_msgpack(el.second);
  8844. }
  8845. break;
  8846. }
  8847. default:
  8848. {
  8849. break;
  8850. }
  8851. }
  8852. }
  8853. private:
  8854. /*
  8855. @brief write a number to output input
  8856. @param[in] n number of type @a NumberType
  8857. @tparam NumberType the type of the number
  8858. @note This function needs to respect the system's endianess, because
  8859. bytes in CBOR and MessagePack are stored in network order (big
  8860. endian) and therefore need reordering on little endian systems.
  8861. */
  8862. template<typename NumberType>
  8863. void write_number(NumberType n)
  8864. {
  8865. // step 1: write number to array of length NumberType
  8866. std::array<uint8_t, sizeof(NumberType)> vec;
  8867. std::memcpy(vec.data(), &n, sizeof(NumberType));
  8868. // step 2: write array to output (with possible reordering)
  8869. if (is_little_endian)
  8870. {
  8871. // reverse byte order prior to conversion if necessary
  8872. std::reverse(vec.begin(), vec.end());
  8873. }
  8874. oa->write_characters(vec.data(), sizeof(NumberType));
  8875. }
  8876. private:
  8877. /// whether we can assume little endianess
  8878. const bool is_little_endian = true;
  8879. /// the output
  8880. output_adapter_t<uint8_t> oa = nullptr;
  8881. };
  8882. public:
  8883. /*!
  8884. @brief create a CBOR serialization of a given JSON value
  8885. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  8886. Binary Object Representation) serialization format. CBOR is a binary
  8887. serialization format which aims to be more compact than JSON itself, yet
  8888. more efficient to parse.
  8889. The library uses the following mapping from JSON values types to
  8890. CBOR types according to the CBOR specification (RFC 7049):
  8891. JSON value type | value/range | CBOR type | first byte
  8892. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  8893. null | `null` | Null | 0xf6
  8894. boolean | `true` | True | 0xf5
  8895. boolean | `false` | False | 0xf4
  8896. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3b
  8897. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3a
  8898. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  8899. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  8900. number_integer | -24..-1 | Negative integer | 0x20..0x37
  8901. number_integer | 0..23 | Integer | 0x00..0x17
  8902. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  8903. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  8904. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a
  8905. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b
  8906. number_unsigned | 0..23 | Integer | 0x00..0x17
  8907. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  8908. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  8909. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a
  8910. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b
  8911. number_float | *any value* | Double-Precision Float | 0xfb
  8912. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  8913. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  8914. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  8915. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7a
  8916. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7b
  8917. array | *size*: 0..23 | array | 0x80..0x97
  8918. array | *size*: 23..255 | array (1 byte follow) | 0x98
  8919. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  8920. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9a
  8921. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9b
  8922. object | *size*: 0..23 | map | 0xa0..0xb7
  8923. object | *size*: 23..255 | map (1 byte follow) | 0xb8
  8924. object | *size*: 256..65535 | map (2 bytes follow) | 0xb9
  8925. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xba
  8926. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xbb
  8927. @note The mapping is **complete** in the sense that any JSON value type
  8928. can be converted to a CBOR value.
  8929. @note The following CBOR types are not used in the conversion:
  8930. - byte strings (0x40..0x5f)
  8931. - UTF-8 strings terminated by "break" (0x7f)
  8932. - arrays terminated by "break" (0x9f)
  8933. - maps terminated by "break" (0xbf)
  8934. - date/time (0xc0..0xc1)
  8935. - bignum (0xc2..0xc3)
  8936. - decimal fraction (0xc4)
  8937. - bigfloat (0xc5)
  8938. - tagged items (0xc6..0xd4, 0xd8..0xdb)
  8939. - expected conversions (0xd5..0xd7)
  8940. - simple values (0xe0..0xf3, 0xf8)
  8941. - undefined (0xf7)
  8942. - half and single-precision floats (0xf9-0xfa)
  8943. - break (0xff)
  8944. @param[in] j JSON value to serialize
  8945. @return MessagePack serialization as byte vector
  8946. @complexity Linear in the size of the JSON value @a j.
  8947. @liveexample{The example shows the serialization of a JSON value to a byte
  8948. vector in CBOR format.,to_cbor}
  8949. @sa http://cbor.io
  8950. @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
  8951. analogous deserialization
  8952. @sa @ref to_msgpack(const basic_json& for the related MessagePack format
  8953. @since version 2.0.9
  8954. */
  8955. static std::vector<uint8_t> to_cbor(const basic_json& j)
  8956. {
  8957. std::vector<uint8_t> result;
  8958. binary_writer bw(output_adapter<uint8_t>::create(result));
  8959. bw.write_cbor(j);
  8960. return result;
  8961. }
  8962. /*!
  8963. @brief create a MessagePack serialization of a given JSON value
  8964. Serializes a given JSON value @a j to a byte vector using the MessagePack
  8965. serialization format. MessagePack is a binary serialization format which
  8966. aims to be more compact than JSON itself, yet more efficient to parse.
  8967. The library uses the following mapping from JSON values types to
  8968. MessagePack types according to the MessagePack specification:
  8969. JSON value type | value/range | MessagePack type | first byte
  8970. --------------- | --------------------------------- | ---------------- | ----------
  8971. null | `null` | nil | 0xc0
  8972. boolean | `true` | true | 0xc3
  8973. boolean | `false` | false | 0xc2
  8974. number_integer | -9223372036854775808..-2147483649 | int64 | 0xd3
  8975. number_integer | -2147483648..-32769 | int32 | 0xd2
  8976. number_integer | -32768..-129 | int16 | 0xd1
  8977. number_integer | -128..-33 | int8 | 0xd0
  8978. number_integer | -32..-1 | negative fixint | 0xe0..0xff
  8979. number_integer | 0..127 | positive fixint | 0x00..0x7f
  8980. number_integer | 128..255 | uint 8 | 0xcc
  8981. number_integer | 256..65535 | uint 16 | 0xcd
  8982. number_integer | 65536..4294967295 | uint 32 | 0xce
  8983. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xcf
  8984. number_unsigned | 0..127 | positive fixint | 0x00..0x7f
  8985. number_unsigned | 128..255 | uint 8 | 0xcc
  8986. number_unsigned | 256..65535 | uint 16 | 0xcd
  8987. number_unsigned | 65536..4294967295 | uint 32 | 0xce
  8988. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xcf
  8989. number_float | *any value* | float 64 | 0xcb
  8990. string | *length*: 0..31 | fixstr | 0xa0..0xbf
  8991. string | *length*: 32..255 | str 8 | 0xd9
  8992. string | *length*: 256..65535 | str 16 | 0xda
  8993. string | *length*: 65536..4294967295 | str 32 | 0xdb
  8994. array | *size*: 0..15 | fixarray | 0x90..0x9f
  8995. array | *size*: 16..65535 | array 16 | 0xdc
  8996. array | *size*: 65536..4294967295 | array 32 | 0xdd
  8997. object | *size*: 0..15 | fix map | 0x80..0x8f
  8998. object | *size*: 16..65535 | map 16 | 0xde
  8999. object | *size*: 65536..4294967295 | map 32 | 0xdf
  9000. @note The mapping is **complete** in the sense that any JSON value type
  9001. can be converted to a MessagePack value.
  9002. @note The following values can **not** be converted to a MessagePack value:
  9003. - strings with more than 4294967295 bytes
  9004. - arrays with more than 4294967295 elements
  9005. - objects with more than 4294967295 elements
  9006. @note The following MessagePack types are not used in the conversion:
  9007. - bin 8 - bin 32 (0xc4..0xc6)
  9008. - ext 8 - ext 32 (0xc7..0xc9)
  9009. - float 32 (0xca)
  9010. - fixext 1 - fixext 16 (0xd4..0xd8)
  9011. @note Any MessagePack output created @ref to_msgpack can be successfully
  9012. parsed by @ref from_msgpack.
  9013. @param[in] j JSON value to serialize
  9014. @return MessagePack serialization as byte vector
  9015. @complexity Linear in the size of the JSON value @a j.
  9016. @liveexample{The example shows the serialization of a JSON value to a byte
  9017. vector in MessagePack format.,to_msgpack}
  9018. @sa http://msgpack.org
  9019. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  9020. analogous deserialization
  9021. @sa @ref to_cbor(const basic_json& for the related CBOR format
  9022. @since version 2.0.9
  9023. */
  9024. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  9025. {
  9026. std::vector<uint8_t> result;
  9027. binary_writer bw(output_adapter<uint8_t>::create(result));
  9028. bw.write_msgpack(j);
  9029. return result;
  9030. }
  9031. /*!
  9032. @brief create a JSON value from a byte vector in CBOR format
  9033. Deserializes a given byte vector @a v to a JSON value using the CBOR
  9034. (Concise Binary Object Representation) serialization format.
  9035. The library maps CBOR types to JSON value types as follows:
  9036. CBOR type | JSON value type | first byte
  9037. ---------------------- | --------------- | ----------
  9038. Integer | number_unsigned | 0x00..0x17
  9039. Unsigned integer | number_unsigned | 0x18
  9040. Unsigned integer | number_unsigned | 0x19
  9041. Unsigned integer | number_unsigned | 0x1a
  9042. Unsigned integer | number_unsigned | 0x1b
  9043. Negative integer | number_integer | 0x20..0x37
  9044. Negative integer | number_integer | 0x38
  9045. Negative integer | number_integer | 0x39
  9046. Negative integer | number_integer | 0x3a
  9047. Negative integer | number_integer | 0x3b
  9048. Negative integer | number_integer | 0x40..0x57
  9049. UTF-8 string | string | 0x60..0x77
  9050. UTF-8 string | string | 0x78
  9051. UTF-8 string | string | 0x79
  9052. UTF-8 string | string | 0x7a
  9053. UTF-8 string | string | 0x7b
  9054. UTF-8 string | string | 0x7f
  9055. array | array | 0x80..0x97
  9056. array | array | 0x98
  9057. array | array | 0x99
  9058. array | array | 0x9a
  9059. array | array | 0x9b
  9060. array | array | 0x9f
  9061. map | object | 0xa0..0xb7
  9062. map | object | 0xb8
  9063. map | object | 0xb9
  9064. map | object | 0xba
  9065. map | object | 0xbb
  9066. map | object | 0xbf
  9067. False | `false` | 0xf4
  9068. True | `true` | 0xf5
  9069. Nill | `null` | 0xf6
  9070. Half-Precision Float | number_float | 0xf9
  9071. Single-Precision Float | number_float | 0xfa
  9072. Double-Precision Float | number_float | 0xfb
  9073. @warning The mapping is **incomplete** in the sense that not all CBOR
  9074. types can be converted to a JSON value. The following CBOR types
  9075. are not supported and will yield parse errors (parse_error.112):
  9076. - byte strings (0x40..0x5f)
  9077. - date/time (0xc0..0xc1)
  9078. - bignum (0xc2..0xc3)
  9079. - decimal fraction (0xc4)
  9080. - bigfloat (0xc5)
  9081. - tagged items (0xc6..0xd4, 0xd8..0xdb)
  9082. - expected conversions (0xd5..0xd7)
  9083. - simple values (0xe0..0xf3, 0xf8)
  9084. - undefined (0xf7)
  9085. @warning CBOR allows map keys of any type, whereas JSON only allows
  9086. strings as keys in object values. Therefore, CBOR maps with keys
  9087. other than UTF-8 strings are rejected (parse_error.113).
  9088. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  9089. @ref from_cbor.
  9090. @param[in] v a byte vector in CBOR format
  9091. @param[in] start_index the index to start reading from @a v (0 by default)
  9092. @return deserialized JSON value
  9093. @throw parse_error.110 if the given vector ends prematurely
  9094. @throw parse_error.112 if unsupported features from CBOR were
  9095. used in the given vector @a v or if the input is not valid CBOR
  9096. @throw parse_error.113 if a string was expected as map key, but not found
  9097. @complexity Linear in the size of the byte vector @a v.
  9098. @liveexample{The example shows the deserialization of a byte vector in CBOR
  9099. format to a JSON value.,from_cbor}
  9100. @sa http://cbor.io
  9101. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  9102. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  9103. related MessagePack format
  9104. @since version 2.0.9, parameter @a start_index since 2.1.1
  9105. */
  9106. static basic_json from_cbor(const std::vector<uint8_t>& v,
  9107. const size_t start_index = 0)
  9108. {
  9109. binary_reader br(input_adapter::create(v.begin() + static_cast<difference_type>(start_index), v.end()));
  9110. return br.parse_cbor();
  9111. }
  9112. /*!
  9113. @brief create a JSON value from a byte vector in MessagePack format
  9114. Deserializes a given byte vector @a v to a JSON value using the MessagePack
  9115. serialization format.
  9116. The library maps MessagePack types to JSON value types as follows:
  9117. MessagePack type | JSON value type | first byte
  9118. ---------------- | --------------- | ----------
  9119. positive fixint | number_unsigned | 0x00..0x7f
  9120. fixmap | object | 0x80..0x8f
  9121. fixarray | array | 0x90..0x9f
  9122. fixstr | string | 0xa0..0xbf
  9123. nil | `null` | 0xc0
  9124. false | `false` | 0xc2
  9125. true | `true` | 0xc3
  9126. float 32 | number_float | 0xca
  9127. float 64 | number_float | 0xcb
  9128. uint 8 | number_unsigned | 0xcc
  9129. uint 16 | number_unsigned | 0xcd
  9130. uint 32 | number_unsigned | 0xce
  9131. uint 64 | number_unsigned | 0xcf
  9132. int 8 | number_integer | 0xd0
  9133. int 16 | number_integer | 0xd1
  9134. int 32 | number_integer | 0xd2
  9135. int 64 | number_integer | 0xd3
  9136. str 8 | string | 0xd9
  9137. str 16 | string | 0xda
  9138. str 32 | string | 0xdb
  9139. array 16 | array | 0xdc
  9140. array 32 | array | 0xdd
  9141. map 16 | object | 0xde
  9142. map 32 | object | 0xdf
  9143. negative fixint | number_integer | 0xe0-0xff
  9144. @warning The mapping is **incomplete** in the sense that not all
  9145. MessagePack types can be converted to a JSON value. The following
  9146. MessagePack types are not supported and will yield parse errors:
  9147. - bin 8 - bin 32 (0xc4..0xc6)
  9148. - ext 8 - ext 32 (0xc7..0xc9)
  9149. - fixext 1 - fixext 16 (0xd4..0xd8)
  9150. @note Any MessagePack output created @ref to_msgpack can be successfully
  9151. parsed by @ref from_msgpack.
  9152. @param[in] v a byte vector in MessagePack format
  9153. @param[in] start_index the index to start reading from @a v (0 by default)
  9154. @return deserialized JSON value
  9155. @throw parse_error.110 if the given vector ends prematurely
  9156. @throw parse_error.112 if unsupported features from MessagePack were
  9157. used in the given vector @a v or if the input is not valid MessagePack
  9158. @throw parse_error.113 if a string was expected as map key, but not found
  9159. @complexity Linear in the size of the byte vector @a v.
  9160. @liveexample{The example shows the deserialization of a byte vector in
  9161. MessagePack format to a JSON value.,from_msgpack}
  9162. @sa http://msgpack.org
  9163. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  9164. @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
  9165. related CBOR format
  9166. @since version 2.0.9, parameter @a start_index since 2.1.1
  9167. */
  9168. static basic_json from_msgpack(const std::vector<uint8_t>& v,
  9169. const size_t start_index = 0)
  9170. {
  9171. binary_reader br(input_adapter::create(v.begin() + static_cast<difference_type>(start_index), v.end()));
  9172. return br.parse_msgpack();
  9173. }
  9174. /// @}
  9175. //////////////////////
  9176. // lexer and parser //
  9177. //////////////////////
  9178. private:
  9179. /*!
  9180. @brief lexical analysis
  9181. This class organizes the lexical analysis during JSON deserialization.
  9182. */
  9183. class lexer
  9184. {
  9185. public:
  9186. /// token types for the parser
  9187. enum class token_type
  9188. {
  9189. uninitialized, ///< indicating the scanner is uninitialized
  9190. literal_true, ///< the `true` literal
  9191. literal_false, ///< the `false` literal
  9192. literal_null, ///< the `null` literal
  9193. value_string, ///< a string -- use get_string() for actual value
  9194. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  9195. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  9196. value_float, ///< an floating point number -- use get_number_float() for actual value
  9197. begin_array, ///< the character for array begin `[`
  9198. begin_object, ///< the character for object begin `{`
  9199. end_array, ///< the character for array end `]`
  9200. end_object, ///< the character for object end `}`
  9201. name_separator, ///< the name separator `:`
  9202. value_separator, ///< the value separator `,`
  9203. parse_error, ///< indicating a parse error
  9204. end_of_input, ///< indicating the end of the input buffer
  9205. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  9206. };
  9207. /// return name of values of type token_type (only used for errors)
  9208. static const char* token_type_name(const token_type t) noexcept
  9209. {
  9210. switch (t)
  9211. {
  9212. case token_type::uninitialized:
  9213. return "<uninitialized>";
  9214. case token_type::literal_true:
  9215. return "true literal";
  9216. case token_type::literal_false:
  9217. return "false literal";
  9218. case token_type::literal_null:
  9219. return "null literal";
  9220. case token_type::value_string:
  9221. return "string literal";
  9222. case lexer::token_type::value_unsigned:
  9223. case lexer::token_type::value_integer:
  9224. case lexer::token_type::value_float:
  9225. return "number literal";
  9226. case token_type::begin_array:
  9227. return "'['";
  9228. case token_type::begin_object:
  9229. return "'{'";
  9230. case token_type::end_array:
  9231. return "']'";
  9232. case token_type::end_object:
  9233. return "'}'";
  9234. case token_type::name_separator:
  9235. return "':'";
  9236. case token_type::value_separator:
  9237. return "','";
  9238. case token_type::parse_error:
  9239. return "<parse error>";
  9240. case token_type::end_of_input:
  9241. return "end of input";
  9242. case token_type::literal_or_value:
  9243. return "'[', '{', or a literal";
  9244. default:
  9245. {
  9246. // catch non-enum values
  9247. return "unknown token"; // LCOV_EXCL_LINE
  9248. }
  9249. }
  9250. }
  9251. explicit lexer(input_adapter_t adapter)
  9252. : ia(adapter), decimal_point_char(get_decimal_point())
  9253. {}
  9254. // delete because of pointer members
  9255. lexer(const lexer&) = delete;
  9256. lexer& operator=(lexer&) = delete;
  9257. private:
  9258. /////////////////////
  9259. // locales
  9260. /////////////////////
  9261. /// return the locale-dependent decimal point
  9262. static char get_decimal_point() noexcept
  9263. {
  9264. const auto loc = localeconv();
  9265. assert(loc != nullptr);
  9266. return (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0];
  9267. }
  9268. /////////////////////
  9269. // scan functions
  9270. /////////////////////
  9271. /*!
  9272. @brief get codepoint from 4 hex characters following `\u`
  9273. @return codepoint or -1 in case of an error (e.g. EOF or non-hex
  9274. character)
  9275. */
  9276. int get_codepoint()
  9277. {
  9278. // this function only makes sense after reading `\u`
  9279. assert(current == 'u');
  9280. int codepoint = 0;
  9281. // byte 1: \uXxxx
  9282. switch (get())
  9283. {
  9284. case '0':
  9285. break;
  9286. case '1':
  9287. codepoint += 0x1000;
  9288. break;
  9289. case '2':
  9290. codepoint += 0x2000;
  9291. break;
  9292. case '3':
  9293. codepoint += 0x3000;
  9294. break;
  9295. case '4':
  9296. codepoint += 0x4000;
  9297. break;
  9298. case '5':
  9299. codepoint += 0x5000;
  9300. break;
  9301. case '6':
  9302. codepoint += 0x6000;
  9303. break;
  9304. case '7':
  9305. codepoint += 0x7000;
  9306. break;
  9307. case '8':
  9308. codepoint += 0x8000;
  9309. break;
  9310. case '9':
  9311. codepoint += 0x9000;
  9312. break;
  9313. case 'A':
  9314. case 'a':
  9315. codepoint += 0xa000;
  9316. break;
  9317. case 'B':
  9318. case 'b':
  9319. codepoint += 0xb000;
  9320. break;
  9321. case 'C':
  9322. case 'c':
  9323. codepoint += 0xc000;
  9324. break;
  9325. case 'D':
  9326. case 'd':
  9327. codepoint += 0xd000;
  9328. break;
  9329. case 'E':
  9330. case 'e':
  9331. codepoint += 0xe000;
  9332. break;
  9333. case 'F':
  9334. case 'f':
  9335. codepoint += 0xf000;
  9336. break;
  9337. default:
  9338. return -1;
  9339. }
  9340. // byte 2: \uxXxx
  9341. switch (get())
  9342. {
  9343. case '0':
  9344. break;
  9345. case '1':
  9346. codepoint += 0x0100;
  9347. break;
  9348. case '2':
  9349. codepoint += 0x0200;
  9350. break;
  9351. case '3':
  9352. codepoint += 0x0300;
  9353. break;
  9354. case '4':
  9355. codepoint += 0x0400;
  9356. break;
  9357. case '5':
  9358. codepoint += 0x0500;
  9359. break;
  9360. case '6':
  9361. codepoint += 0x0600;
  9362. break;
  9363. case '7':
  9364. codepoint += 0x0700;
  9365. break;
  9366. case '8':
  9367. codepoint += 0x0800;
  9368. break;
  9369. case '9':
  9370. codepoint += 0x0900;
  9371. break;
  9372. case 'A':
  9373. case 'a':
  9374. codepoint += 0x0a00;
  9375. break;
  9376. case 'B':
  9377. case 'b':
  9378. codepoint += 0x0b00;
  9379. break;
  9380. case 'C':
  9381. case 'c':
  9382. codepoint += 0x0c00;
  9383. break;
  9384. case 'D':
  9385. case 'd':
  9386. codepoint += 0x0d00;
  9387. break;
  9388. case 'E':
  9389. case 'e':
  9390. codepoint += 0x0e00;
  9391. break;
  9392. case 'F':
  9393. case 'f':
  9394. codepoint += 0x0f00;
  9395. break;
  9396. default:
  9397. return -1;
  9398. }
  9399. // byte 3: \uxxXx
  9400. switch (get())
  9401. {
  9402. case '0':
  9403. break;
  9404. case '1':
  9405. codepoint += 0x0010;
  9406. break;
  9407. case '2':
  9408. codepoint += 0x0020;
  9409. break;
  9410. case '3':
  9411. codepoint += 0x0030;
  9412. break;
  9413. case '4':
  9414. codepoint += 0x0040;
  9415. break;
  9416. case '5':
  9417. codepoint += 0x0050;
  9418. break;
  9419. case '6':
  9420. codepoint += 0x0060;
  9421. break;
  9422. case '7':
  9423. codepoint += 0x0070;
  9424. break;
  9425. case '8':
  9426. codepoint += 0x0080;
  9427. break;
  9428. case '9':
  9429. codepoint += 0x0090;
  9430. break;
  9431. case 'A':
  9432. case 'a':
  9433. codepoint += 0x00a0;
  9434. break;
  9435. case 'B':
  9436. case 'b':
  9437. codepoint += 0x00b0;
  9438. break;
  9439. case 'C':
  9440. case 'c':
  9441. codepoint += 0x00c0;
  9442. break;
  9443. case 'D':
  9444. case 'd':
  9445. codepoint += 0x00d0;
  9446. break;
  9447. case 'E':
  9448. case 'e':
  9449. codepoint += 0x00e0;
  9450. break;
  9451. case 'F':
  9452. case 'f':
  9453. codepoint += 0x00f0;
  9454. break;
  9455. default:
  9456. return -1;
  9457. }
  9458. // byte 4: \uxxxX
  9459. switch (get())
  9460. {
  9461. case '0':
  9462. break;
  9463. case '1':
  9464. codepoint += 0x0001;
  9465. break;
  9466. case '2':
  9467. codepoint += 0x0002;
  9468. break;
  9469. case '3':
  9470. codepoint += 0x0003;
  9471. break;
  9472. case '4':
  9473. codepoint += 0x0004;
  9474. break;
  9475. case '5':
  9476. codepoint += 0x0005;
  9477. break;
  9478. case '6':
  9479. codepoint += 0x0006;
  9480. break;
  9481. case '7':
  9482. codepoint += 0x0007;
  9483. break;
  9484. case '8':
  9485. codepoint += 0x0008;
  9486. break;
  9487. case '9':
  9488. codepoint += 0x0009;
  9489. break;
  9490. case 'A':
  9491. case 'a':
  9492. codepoint += 0x000a;
  9493. break;
  9494. case 'B':
  9495. case 'b':
  9496. codepoint += 0x000b;
  9497. break;
  9498. case 'C':
  9499. case 'c':
  9500. codepoint += 0x000c;
  9501. break;
  9502. case 'D':
  9503. case 'd':
  9504. codepoint += 0x000d;
  9505. break;
  9506. case 'E':
  9507. case 'e':
  9508. codepoint += 0x000e;
  9509. break;
  9510. case 'F':
  9511. case 'f':
  9512. codepoint += 0x000f;
  9513. break;
  9514. default:
  9515. return -1;
  9516. }
  9517. return codepoint;
  9518. }
  9519. /*!
  9520. @brief scan a string literal
  9521. This function scans a string according to Sect. 7 of RFC 7159. While
  9522. scanning, bytes are escaped and copied into buffer yytext. Then the
  9523. function returns successfully, yytext is null-terminated and yylen
  9524. contains the number of bytes in the string.
  9525. @return token_type::value_string if string could be successfully
  9526. scanned, token_type::parse_error otherwise
  9527. @note In case of errors, variable error_message contains a textual
  9528. description.
  9529. */
  9530. token_type scan_string()
  9531. {
  9532. // reset yytext (ignore opening quote)
  9533. reset();
  9534. // we entered the function by reading an open quote
  9535. assert(current == '\"');
  9536. while (true)
  9537. {
  9538. // get next character
  9539. switch (get())
  9540. {
  9541. // end of file while parsing string
  9542. case std::char_traits<char>::eof():
  9543. {
  9544. error_message = "invalid string: missing closing quote";
  9545. return token_type::parse_error;
  9546. }
  9547. // closing quote
  9548. case '\"':
  9549. {
  9550. // terminate yytext
  9551. add('\0');
  9552. --yylen;
  9553. return token_type::value_string;
  9554. }
  9555. // escapes
  9556. case '\\':
  9557. {
  9558. switch (get())
  9559. {
  9560. // quotation mark
  9561. case '\"':
  9562. add('\"');
  9563. break;
  9564. // reverse solidus
  9565. case '\\':
  9566. add('\\');
  9567. break;
  9568. // solidus
  9569. case '/':
  9570. add('/');
  9571. break;
  9572. // backspace
  9573. case 'b':
  9574. add('\b');
  9575. break;
  9576. // form feed
  9577. case 'f':
  9578. add('\f');
  9579. break;
  9580. // line feed
  9581. case 'n':
  9582. add('\n');
  9583. break;
  9584. // carriage return
  9585. case 'r':
  9586. add('\r');
  9587. break;
  9588. // tab
  9589. case 't':
  9590. add('\t');
  9591. break;
  9592. // unicode escapes
  9593. case 'u':
  9594. {
  9595. int codepoint;
  9596. int codepoint1 = get_codepoint();
  9597. if (JSON_UNLIKELY(codepoint1 == -1))
  9598. {
  9599. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  9600. return token_type::parse_error;
  9601. }
  9602. // check if code point is a high surrogate
  9603. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  9604. {
  9605. // expect next \uxxxx entry
  9606. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  9607. {
  9608. const int codepoint2 = get_codepoint();
  9609. if (JSON_UNLIKELY(codepoint2 == -1))
  9610. {
  9611. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  9612. return token_type::parse_error;
  9613. }
  9614. // check if codepoint2 is a low surrogate
  9615. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  9616. {
  9617. codepoint =
  9618. // high surrogate occupies the most significant 22 bits
  9619. (codepoint1 << 10)
  9620. // low surrogate occupies the least significant 15 bits
  9621. + codepoint2
  9622. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  9623. // in the result so we have to subtract with:
  9624. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  9625. - 0x35FDC00;
  9626. }
  9627. else
  9628. {
  9629. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  9630. return token_type::parse_error;
  9631. }
  9632. }
  9633. else
  9634. {
  9635. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  9636. return token_type::parse_error;
  9637. }
  9638. }
  9639. else
  9640. {
  9641. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  9642. {
  9643. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  9644. return token_type::parse_error;
  9645. }
  9646. // only work with first code point
  9647. codepoint = codepoint1;
  9648. }
  9649. // result of the above calculation yields a proper codepoint
  9650. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  9651. // translate code point to bytes
  9652. if (codepoint < 0x80)
  9653. {
  9654. // 1-byte characters: 0xxxxxxx (ASCII)
  9655. add(codepoint);
  9656. }
  9657. else if (codepoint <= 0x7ff)
  9658. {
  9659. // 2-byte characters: 110xxxxx 10xxxxxx
  9660. add(0xC0 | (codepoint >> 6));
  9661. add(0x80 | (codepoint & 0x3F));
  9662. }
  9663. else if (codepoint <= 0xffff)
  9664. {
  9665. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  9666. add(0xE0 | (codepoint >> 12));
  9667. add(0x80 | ((codepoint >> 6) & 0x3F));
  9668. add(0x80 | (codepoint & 0x3F));
  9669. }
  9670. else
  9671. {
  9672. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  9673. add(0xF0 | (codepoint >> 18));
  9674. add(0x80 | ((codepoint >> 12) & 0x3F));
  9675. add(0x80 | ((codepoint >> 6) & 0x3F));
  9676. add(0x80 | (codepoint & 0x3F));
  9677. }
  9678. break;
  9679. }
  9680. // other characters after escape
  9681. default:
  9682. error_message = "invalid string: forbidden character after backslash";
  9683. return token_type::parse_error;
  9684. }
  9685. break;
  9686. }
  9687. // invalid control characters
  9688. case 0x00:
  9689. case 0x01:
  9690. case 0x02:
  9691. case 0x03:
  9692. case 0x04:
  9693. case 0x05:
  9694. case 0x06:
  9695. case 0x07:
  9696. case 0x08:
  9697. case 0x09:
  9698. case 0x0a:
  9699. case 0x0b:
  9700. case 0x0c:
  9701. case 0x0d:
  9702. case 0x0e:
  9703. case 0x0f:
  9704. case 0x10:
  9705. case 0x11:
  9706. case 0x12:
  9707. case 0x13:
  9708. case 0x14:
  9709. case 0x15:
  9710. case 0x16:
  9711. case 0x17:
  9712. case 0x18:
  9713. case 0x19:
  9714. case 0x1a:
  9715. case 0x1b:
  9716. case 0x1c:
  9717. case 0x1d:
  9718. case 0x1e:
  9719. case 0x1f:
  9720. {
  9721. error_message = "invalid string: control character must be escaped";
  9722. return token_type::parse_error;
  9723. }
  9724. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  9725. case 0x20:
  9726. case 0x21:
  9727. case 0x23:
  9728. case 0x24:
  9729. case 0x25:
  9730. case 0x26:
  9731. case 0x27:
  9732. case 0x28:
  9733. case 0x29:
  9734. case 0x2a:
  9735. case 0x2b:
  9736. case 0x2c:
  9737. case 0x2d:
  9738. case 0x2e:
  9739. case 0x2f:
  9740. case 0x30:
  9741. case 0x31:
  9742. case 0x32:
  9743. case 0x33:
  9744. case 0x34:
  9745. case 0x35:
  9746. case 0x36:
  9747. case 0x37:
  9748. case 0x38:
  9749. case 0x39:
  9750. case 0x3a:
  9751. case 0x3b:
  9752. case 0x3c:
  9753. case 0x3d:
  9754. case 0x3e:
  9755. case 0x3f:
  9756. case 0x40:
  9757. case 0x41:
  9758. case 0x42:
  9759. case 0x43:
  9760. case 0x44:
  9761. case 0x45:
  9762. case 0x46:
  9763. case 0x47:
  9764. case 0x48:
  9765. case 0x49:
  9766. case 0x4a:
  9767. case 0x4b:
  9768. case 0x4c:
  9769. case 0x4d:
  9770. case 0x4e:
  9771. case 0x4f:
  9772. case 0x50:
  9773. case 0x51:
  9774. case 0x52:
  9775. case 0x53:
  9776. case 0x54:
  9777. case 0x55:
  9778. case 0x56:
  9779. case 0x57:
  9780. case 0x58:
  9781. case 0x59:
  9782. case 0x5a:
  9783. case 0x5b:
  9784. case 0x5d:
  9785. case 0x5e:
  9786. case 0x5f:
  9787. case 0x60:
  9788. case 0x61:
  9789. case 0x62:
  9790. case 0x63:
  9791. case 0x64:
  9792. case 0x65:
  9793. case 0x66:
  9794. case 0x67:
  9795. case 0x68:
  9796. case 0x69:
  9797. case 0x6a:
  9798. case 0x6b:
  9799. case 0x6c:
  9800. case 0x6d:
  9801. case 0x6e:
  9802. case 0x6f:
  9803. case 0x70:
  9804. case 0x71:
  9805. case 0x72:
  9806. case 0x73:
  9807. case 0x74:
  9808. case 0x75:
  9809. case 0x76:
  9810. case 0x77:
  9811. case 0x78:
  9812. case 0x79:
  9813. case 0x7a:
  9814. case 0x7b:
  9815. case 0x7c:
  9816. case 0x7d:
  9817. case 0x7e:
  9818. case 0x7f:
  9819. {
  9820. add(current);
  9821. break;
  9822. }
  9823. // U+0080..U+07FF: bytes C2..DF 80..BF
  9824. case 0xc2:
  9825. case 0xc3:
  9826. case 0xc4:
  9827. case 0xc5:
  9828. case 0xc6:
  9829. case 0xc7:
  9830. case 0xc8:
  9831. case 0xc9:
  9832. case 0xca:
  9833. case 0xcb:
  9834. case 0xcc:
  9835. case 0xcd:
  9836. case 0xce:
  9837. case 0xcf:
  9838. case 0xd0:
  9839. case 0xd1:
  9840. case 0xd2:
  9841. case 0xd3:
  9842. case 0xd4:
  9843. case 0xd5:
  9844. case 0xd6:
  9845. case 0xd7:
  9846. case 0xd8:
  9847. case 0xd9:
  9848. case 0xda:
  9849. case 0xdb:
  9850. case 0xdc:
  9851. case 0xdd:
  9852. case 0xde:
  9853. case 0xdf:
  9854. {
  9855. add(current);
  9856. get();
  9857. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9858. {
  9859. add(current);
  9860. continue;
  9861. }
  9862. error_message = "invalid string: ill-formed UTF-8 byte";
  9863. return token_type::parse_error;
  9864. }
  9865. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  9866. case 0xe0:
  9867. {
  9868. add(current);
  9869. get();
  9870. if (JSON_LIKELY(0xa0 <= current and current <= 0xbf))
  9871. {
  9872. add(current);
  9873. get();
  9874. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9875. {
  9876. add(current);
  9877. continue;
  9878. }
  9879. }
  9880. error_message = "invalid string: ill-formed UTF-8 byte";
  9881. return token_type::parse_error;
  9882. }
  9883. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  9884. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  9885. case 0xe1:
  9886. case 0xe2:
  9887. case 0xe3:
  9888. case 0xe4:
  9889. case 0xe5:
  9890. case 0xe6:
  9891. case 0xe7:
  9892. case 0xe8:
  9893. case 0xe9:
  9894. case 0xea:
  9895. case 0xeb:
  9896. case 0xec:
  9897. case 0xee:
  9898. case 0xef:
  9899. {
  9900. add(current);
  9901. get();
  9902. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9903. {
  9904. add(current);
  9905. get();
  9906. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9907. {
  9908. add(current);
  9909. continue;
  9910. }
  9911. }
  9912. error_message = "invalid string: ill-formed UTF-8 byte";
  9913. return token_type::parse_error;
  9914. }
  9915. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  9916. case 0xed:
  9917. {
  9918. add(current);
  9919. get();
  9920. if (JSON_LIKELY(0x80 <= current and current <= 0x9f))
  9921. {
  9922. add(current);
  9923. get();
  9924. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9925. {
  9926. add(current);
  9927. continue;
  9928. }
  9929. }
  9930. error_message = "invalid string: ill-formed UTF-8 byte";
  9931. return token_type::parse_error;
  9932. }
  9933. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  9934. case 0xf0:
  9935. {
  9936. add(current);
  9937. get();
  9938. if (JSON_LIKELY(0x90 <= current and current <= 0xbf))
  9939. {
  9940. add(current);
  9941. get();
  9942. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9943. {
  9944. add(current);
  9945. get();
  9946. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9947. {
  9948. add(current);
  9949. continue;
  9950. }
  9951. }
  9952. }
  9953. error_message = "invalid string: ill-formed UTF-8 byte";
  9954. return token_type::parse_error;
  9955. }
  9956. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  9957. case 0xf1:
  9958. case 0xf2:
  9959. case 0xf3:
  9960. {
  9961. add(current);
  9962. get();
  9963. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9964. {
  9965. add(current);
  9966. get();
  9967. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9968. {
  9969. add(current);
  9970. get();
  9971. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9972. {
  9973. add(current);
  9974. continue;
  9975. }
  9976. }
  9977. }
  9978. error_message = "invalid string: ill-formed UTF-8 byte";
  9979. return token_type::parse_error;
  9980. }
  9981. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  9982. case 0xf4:
  9983. {
  9984. add(current);
  9985. get();
  9986. if (JSON_LIKELY(0x80 <= current and current <= 0x8f))
  9987. {
  9988. add(current);
  9989. get();
  9990. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9991. {
  9992. add(current);
  9993. get();
  9994. if (JSON_LIKELY(0x80 <= current and current <= 0xbf))
  9995. {
  9996. add(current);
  9997. continue;
  9998. }
  9999. }
  10000. }
  10001. error_message = "invalid string: ill-formed UTF-8 byte";
  10002. return token_type::parse_error;
  10003. }
  10004. // remaining bytes (80..C1 and F5..FF) are ill-formed
  10005. default:
  10006. {
  10007. error_message = "invalid string: ill-formed UTF-8 byte";
  10008. return token_type::parse_error;
  10009. }
  10010. }
  10011. }
  10012. }
  10013. static void strtof(float& f, const char* str, char** endptr) noexcept
  10014. {
  10015. f = std::strtof(str, endptr);
  10016. }
  10017. static void strtof(double& f, const char* str, char** endptr) noexcept
  10018. {
  10019. f = std::strtod(str, endptr);
  10020. }
  10021. static void strtof(long double& f, const char* str, char** endptr) noexcept
  10022. {
  10023. f = std::strtold(str, endptr);
  10024. }
  10025. /*!
  10026. @brief scan a number literal
  10027. This function scans a string according to Sect. 6 of RFC 7159.
  10028. The function is realized with a deterministic finite state machine
  10029. derived from the grammar described in RFC 7159. Starting in state
  10030. "init", the input is read and used to determined the next state. Only
  10031. state "done" accepts the number. State "error" is a trap state to model
  10032. errors. In the table below, "anything" means any character but the ones
  10033. listed before.
  10034. state | 0 | 1-9 | e E | + | - | . | anything
  10035. ---------|----------|----------|----------|---------|---------|----------|-----------
  10036. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  10037. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  10038. zero | done | done | exponent | done | done | decimal1 | done
  10039. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  10040. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  10041. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  10042. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  10043. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  10044. any2 | any2 | any2 | done | done | done | done | done
  10045. The state machine is realized with one label per state (prefixed with
  10046. "scan_number_") and `goto` statements between them. The state machine
  10047. contains cycles, but any cycle can be left when EOF is read. Therefore,
  10048. the function is guaranteed to terminate.
  10049. During scanning, the read bytes are stored in yytext. This string is
  10050. then converted to a signed integer, an unsigned integer, or a
  10051. floating-point number.
  10052. @return token_type::value_unsigned, token_type::value_integer, or
  10053. token_type::value_float if number could be successfully scanned,
  10054. token_type::parse_error otherwise
  10055. @note The scanner is independent of the current locale. Internally, the
  10056. locale's decimal point is used instead of `.` to work with the
  10057. locale-dependent converters.
  10058. */
  10059. token_type scan_number()
  10060. {
  10061. // reset yytext to store the number's bytes
  10062. reset();
  10063. // the type of the parsed number; initially set to unsigned; will be
  10064. // changed if minus sign, decimal point or exponent is read
  10065. token_type number_type = token_type::value_unsigned;
  10066. // state (init): we just found out we need to scan a number
  10067. switch (current)
  10068. {
  10069. case '-':
  10070. {
  10071. add(current);
  10072. goto scan_number_minus;
  10073. }
  10074. case '0':
  10075. {
  10076. add(current);
  10077. goto scan_number_zero;
  10078. }
  10079. case '1':
  10080. case '2':
  10081. case '3':
  10082. case '4':
  10083. case '5':
  10084. case '6':
  10085. case '7':
  10086. case '8':
  10087. case '9':
  10088. {
  10089. add(current);
  10090. goto scan_number_any1;
  10091. }
  10092. default:
  10093. {
  10094. // all other characters are rejected outside scan_number()
  10095. assert(false); // LCOV_EXCL_LINE
  10096. }
  10097. }
  10098. scan_number_minus:
  10099. // state: we just parsed a leading minus sign
  10100. number_type = token_type::value_integer;
  10101. switch (get())
  10102. {
  10103. case '0':
  10104. {
  10105. add(current);
  10106. goto scan_number_zero;
  10107. }
  10108. case '1':
  10109. case '2':
  10110. case '3':
  10111. case '4':
  10112. case '5':
  10113. case '6':
  10114. case '7':
  10115. case '8':
  10116. case '9':
  10117. {
  10118. add(current);
  10119. goto scan_number_any1;
  10120. }
  10121. default:
  10122. {
  10123. error_message = "invalid number; expected digit after '-'";
  10124. return token_type::parse_error;
  10125. }
  10126. }
  10127. scan_number_zero:
  10128. // state: we just parse a zero (maybe with a leading minus sign)
  10129. switch (get())
  10130. {
  10131. case '.':
  10132. {
  10133. add(decimal_point_char);
  10134. goto scan_number_decimal1;
  10135. }
  10136. case 'e':
  10137. case 'E':
  10138. {
  10139. add(current);
  10140. goto scan_number_exponent;
  10141. }
  10142. default:
  10143. {
  10144. goto scan_number_done;
  10145. }
  10146. }
  10147. scan_number_any1:
  10148. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  10149. switch (get())
  10150. {
  10151. case '0':
  10152. case '1':
  10153. case '2':
  10154. case '3':
  10155. case '4':
  10156. case '5':
  10157. case '6':
  10158. case '7':
  10159. case '8':
  10160. case '9':
  10161. {
  10162. add(current);
  10163. goto scan_number_any1;
  10164. }
  10165. case '.':
  10166. {
  10167. add(decimal_point_char);
  10168. goto scan_number_decimal1;
  10169. }
  10170. case 'e':
  10171. case 'E':
  10172. {
  10173. add(current);
  10174. goto scan_number_exponent;
  10175. }
  10176. default:
  10177. {
  10178. goto scan_number_done;
  10179. }
  10180. }
  10181. scan_number_decimal1:
  10182. // state: we just parsed a decimal point
  10183. number_type = token_type::value_float;
  10184. switch (get())
  10185. {
  10186. case '0':
  10187. case '1':
  10188. case '2':
  10189. case '3':
  10190. case '4':
  10191. case '5':
  10192. case '6':
  10193. case '7':
  10194. case '8':
  10195. case '9':
  10196. {
  10197. add(current);
  10198. goto scan_number_decimal2;
  10199. }
  10200. default:
  10201. {
  10202. error_message = "invalid number; expected digit after '.'";
  10203. return token_type::parse_error;
  10204. }
  10205. }
  10206. scan_number_decimal2:
  10207. // we just parsed at least one number after a decimal point
  10208. switch (get())
  10209. {
  10210. case '0':
  10211. case '1':
  10212. case '2':
  10213. case '3':
  10214. case '4':
  10215. case '5':
  10216. case '6':
  10217. case '7':
  10218. case '8':
  10219. case '9':
  10220. {
  10221. add(current);
  10222. goto scan_number_decimal2;
  10223. }
  10224. case 'e':
  10225. case 'E':
  10226. {
  10227. add(current);
  10228. goto scan_number_exponent;
  10229. }
  10230. default:
  10231. {
  10232. goto scan_number_done;
  10233. }
  10234. }
  10235. scan_number_exponent:
  10236. // we just parsed an exponent
  10237. number_type = token_type::value_float;
  10238. switch (get())
  10239. {
  10240. case '+':
  10241. case '-':
  10242. {
  10243. add(current);
  10244. goto scan_number_sign;
  10245. }
  10246. case '0':
  10247. case '1':
  10248. case '2':
  10249. case '3':
  10250. case '4':
  10251. case '5':
  10252. case '6':
  10253. case '7':
  10254. case '8':
  10255. case '9':
  10256. {
  10257. add(current);
  10258. goto scan_number_any2;
  10259. }
  10260. default:
  10261. {
  10262. error_message = "invalid number; expected '+', '-', or digit after exponent";
  10263. return token_type::parse_error;
  10264. }
  10265. }
  10266. scan_number_sign:
  10267. // we just parsed an exponent sign
  10268. switch (get())
  10269. {
  10270. case '0':
  10271. case '1':
  10272. case '2':
  10273. case '3':
  10274. case '4':
  10275. case '5':
  10276. case '6':
  10277. case '7':
  10278. case '8':
  10279. case '9':
  10280. {
  10281. add(current);
  10282. goto scan_number_any2;
  10283. }
  10284. default:
  10285. {
  10286. error_message = "invalid number; expected digit after exponent sign";
  10287. return token_type::parse_error;
  10288. }
  10289. }
  10290. scan_number_any2:
  10291. // we just parsed a number after the exponent or exponent sign
  10292. switch (get())
  10293. {
  10294. case '0':
  10295. case '1':
  10296. case '2':
  10297. case '3':
  10298. case '4':
  10299. case '5':
  10300. case '6':
  10301. case '7':
  10302. case '8':
  10303. case '9':
  10304. {
  10305. add(current);
  10306. goto scan_number_any2;
  10307. }
  10308. default:
  10309. {
  10310. goto scan_number_done;
  10311. }
  10312. }
  10313. scan_number_done:
  10314. // unget the character after the number (we only read it to know
  10315. // that we are done scanning a number)
  10316. --chars_read;
  10317. next_unget = true;
  10318. // terminate token
  10319. add('\0');
  10320. --yylen;
  10321. // try to parse integers first and fall back to floats
  10322. if (number_type == token_type::value_unsigned)
  10323. {
  10324. char* endptr = nullptr;
  10325. errno = 0;
  10326. const auto x = std::strtoull(yytext.data(), &endptr, 10);
  10327. // we checked the number format before
  10328. assert(endptr == yytext.data() + yylen);
  10329. if (errno == 0)
  10330. {
  10331. value_unsigned = static_cast<number_unsigned_t>(x);
  10332. if (value_unsigned == x)
  10333. {
  10334. return token_type::value_unsigned;
  10335. }
  10336. }
  10337. }
  10338. else if (number_type == token_type::value_integer)
  10339. {
  10340. char* endptr = nullptr;
  10341. errno = 0;
  10342. const auto x = std::strtoll(yytext.data(), &endptr, 10);
  10343. // we checked the number format before
  10344. assert(endptr == yytext.data() + yylen);
  10345. if (errno == 0)
  10346. {
  10347. value_integer = static_cast<number_integer_t>(x);
  10348. if (value_integer == x)
  10349. {
  10350. return token_type::value_integer;
  10351. }
  10352. }
  10353. }
  10354. // this code is reached if we parse a floating-point number or if
  10355. // an integer conversion above failed
  10356. strtof(value_float, yytext.data(), nullptr);
  10357. return token_type::value_float;
  10358. }
  10359. /*!
  10360. @param[in] literal_text the literal text to expect
  10361. @param[in] length the length of the passed literal text
  10362. @param[in] return_type the token type to return on success
  10363. */
  10364. token_type scan_literal(const char* literal_text, const size_t length,
  10365. token_type return_type)
  10366. {
  10367. assert(current == literal_text[0]);
  10368. for (size_t i = 1; i < length; ++i)
  10369. {
  10370. if (JSON_UNLIKELY(get() != literal_text[i]))
  10371. {
  10372. error_message = "invalid literal";
  10373. return token_type::parse_error;
  10374. }
  10375. }
  10376. return return_type;
  10377. }
  10378. /////////////////////
  10379. // input management
  10380. /////////////////////
  10381. /// reset yytext
  10382. void reset() noexcept
  10383. {
  10384. yylen = 0;
  10385. start_pos = chars_read - 1;
  10386. }
  10387. /// get a character from the input
  10388. int get()
  10389. {
  10390. ++chars_read;
  10391. return next_unget
  10392. ? (next_unget = false, current)
  10393. : (current = ia->get_character());
  10394. }
  10395. /// add a character to yytext
  10396. void add(int c)
  10397. {
  10398. // resize yytext if necessary; this condition is deemed unlikely,
  10399. // because we start with a 1024-byte buffer
  10400. if (JSON_UNLIKELY((yylen + 1 > yytext.capacity())))
  10401. {
  10402. yytext.resize(2 * yytext.capacity(), '\0');
  10403. }
  10404. assert(yylen < yytext.size());
  10405. yytext[yylen++] = static_cast<char>(c);
  10406. }
  10407. public:
  10408. /////////////////////
  10409. // value getters
  10410. /////////////////////
  10411. /// return integer value
  10412. constexpr number_integer_t get_number_integer() const noexcept
  10413. {
  10414. return value_integer;
  10415. }
  10416. /// return unsigned integer value
  10417. constexpr number_unsigned_t get_number_unsigned() const noexcept
  10418. {
  10419. return value_unsigned;
  10420. }
  10421. /// return floating-point value
  10422. constexpr number_float_t get_number_float() const noexcept
  10423. {
  10424. return value_float;
  10425. }
  10426. /// return string value
  10427. const std::string get_string()
  10428. {
  10429. // yytext cannot be returned as char*, because it may contain a
  10430. // null byte (parsed as "\u0000")
  10431. return std::string(yytext.data(), yylen);
  10432. }
  10433. /////////////////////
  10434. // diagnostics
  10435. /////////////////////
  10436. /// return position of last read token
  10437. constexpr size_t get_position() const noexcept
  10438. {
  10439. return chars_read;
  10440. }
  10441. /// return the last read token (for errors only)
  10442. std::string get_token_string() const
  10443. {
  10444. // get the raw byte sequence of the last token
  10445. std::string s = ia->read(start_pos, chars_read - start_pos);
  10446. // escape control characters
  10447. std::string result;
  10448. for (auto c : s)
  10449. {
  10450. if (c == '\0' or c == std::char_traits<char>::eof())
  10451. {
  10452. // ignore EOF
  10453. continue;
  10454. }
  10455. else if ('\x00' <= c and c <= '\x1f')
  10456. {
  10457. // escape control characters
  10458. std::stringstream ss;
  10459. ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(c) << ">";
  10460. result += ss.str();
  10461. }
  10462. else
  10463. {
  10464. // add character as is
  10465. result.append(1, c);
  10466. }
  10467. }
  10468. return result;
  10469. }
  10470. /// return syntax error message
  10471. constexpr const char* get_error_message() const noexcept
  10472. {
  10473. return error_message;
  10474. }
  10475. /////////////////////
  10476. // actual scanner
  10477. /////////////////////
  10478. token_type scan()
  10479. {
  10480. // read next character and ignore whitespace
  10481. do
  10482. {
  10483. get();
  10484. }
  10485. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  10486. switch (current)
  10487. {
  10488. // structural characters
  10489. case '[':
  10490. return token_type::begin_array;
  10491. case ']':
  10492. return token_type::end_array;
  10493. case '{':
  10494. return token_type::begin_object;
  10495. case '}':
  10496. return token_type::end_object;
  10497. case ':':
  10498. return token_type::name_separator;
  10499. case ',':
  10500. return token_type::value_separator;
  10501. // literals
  10502. case 't':
  10503. return scan_literal("true", 4, token_type::literal_true);
  10504. case 'f':
  10505. return scan_literal("false", 5, token_type::literal_false);
  10506. case 'n':
  10507. return scan_literal("null", 4, token_type::literal_null);
  10508. // string
  10509. case '\"':
  10510. return scan_string();
  10511. // number
  10512. case '-':
  10513. case '0':
  10514. case '1':
  10515. case '2':
  10516. case '3':
  10517. case '4':
  10518. case '5':
  10519. case '6':
  10520. case '7':
  10521. case '8':
  10522. case '9':
  10523. return scan_number();
  10524. // end of input (the null byte is needed when parsing from
  10525. // string literals)
  10526. case '\0':
  10527. case std::char_traits<char>::eof():
  10528. return token_type::end_of_input;
  10529. // error
  10530. default:
  10531. error_message = "invalid literal";
  10532. return token_type::parse_error;
  10533. }
  10534. }
  10535. private:
  10536. /// input adapter
  10537. input_adapter_t ia = nullptr;
  10538. /// the current character
  10539. int current = std::char_traits<char>::eof();
  10540. /// whether get() should return the last character again
  10541. bool next_unget = false;
  10542. /// the number of characters read
  10543. size_t chars_read = 0;
  10544. /// the start position of the current token
  10545. size_t start_pos = 0;
  10546. /// buffer for variable-length tokens (numbers, strings)
  10547. std::vector<char> yytext = std::vector<char>(1024, '\0');
  10548. /// current index in yytext
  10549. size_t yylen = 0;
  10550. /// a description of occurred lexer errors
  10551. const char* error_message = "";
  10552. // number values
  10553. number_integer_t value_integer = 0;
  10554. number_unsigned_t value_unsigned = 0;
  10555. number_float_t value_float = 0;
  10556. /// the decimal point
  10557. const char decimal_point_char = '.';
  10558. };
  10559. /*!
  10560. @brief syntax analysis
  10561. This class implements a recursive decent parser.
  10562. */
  10563. class parser
  10564. {
  10565. public:
  10566. /// a parser reading from an input adapter
  10567. explicit parser(input_adapter_t adapter,
  10568. const parser_callback_t cb = nullptr)
  10569. : callback(cb), m_lexer(adapter)
  10570. {}
  10571. /*!
  10572. @brief public parser interface
  10573. @param[in] strict whether to expect the last token to be EOF
  10574. @return parsed JSON value
  10575. @throw parse_error.101 in case of an unexpected token
  10576. @throw parse_error.102 if to_unicode fails or surrogate error
  10577. @throw parse_error.103 if to_unicode fails
  10578. */
  10579. basic_json parse(const bool strict = true)
  10580. {
  10581. // read first token
  10582. get_token();
  10583. basic_json result = parse_internal(true);
  10584. result.assert_invariant();
  10585. if (strict)
  10586. {
  10587. get_token();
  10588. expect(lexer::token_type::end_of_input);
  10589. }
  10590. // return parser result and replace it with null in case the
  10591. // top-level value was discarded by the callback function
  10592. return result.is_discarded() ? basic_json() : std::move(result);
  10593. }
  10594. /*!
  10595. @brief public accept interface
  10596. @param[in] strict whether to expect the last token to be EOF
  10597. @return whether the input is a proper JSON text
  10598. */
  10599. bool accept(const bool strict = true)
  10600. {
  10601. // read first token
  10602. get_token();
  10603. if (not accept_internal())
  10604. {
  10605. return false;
  10606. }
  10607. if (strict and get_token() != lexer::token_type::end_of_input)
  10608. {
  10609. return false;
  10610. }
  10611. return true;
  10612. }
  10613. private:
  10614. /*!
  10615. @brief the actual parser
  10616. @throw parse_error.101 in case of an unexpected token
  10617. @throw parse_error.102 if to_unicode fails or surrogate error
  10618. @throw parse_error.103 if to_unicode fails
  10619. */
  10620. basic_json parse_internal(bool keep)
  10621. {
  10622. auto result = basic_json(value_t::discarded);
  10623. switch (last_token)
  10624. {
  10625. case lexer::token_type::begin_object:
  10626. {
  10627. if (keep and (not callback
  10628. or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0)))
  10629. {
  10630. // explicitly set result to object to cope with {}
  10631. result.m_type = value_t::object;
  10632. result.m_value = value_t::object;
  10633. }
  10634. // read next token
  10635. get_token();
  10636. // closing } -> we are done
  10637. if (last_token == lexer::token_type::end_object)
  10638. {
  10639. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  10640. {
  10641. result = basic_json(value_t::discarded);
  10642. }
  10643. return result;
  10644. }
  10645. // parse values
  10646. while (true)
  10647. {
  10648. // store key
  10649. expect(lexer::token_type::value_string);
  10650. const auto key = m_lexer.get_string();
  10651. bool keep_tag = false;
  10652. if (keep)
  10653. {
  10654. if (callback)
  10655. {
  10656. basic_json k(key);
  10657. keep_tag = callback(depth, parse_event_t::key, k);
  10658. }
  10659. else
  10660. {
  10661. keep_tag = true;
  10662. }
  10663. }
  10664. // parse separator (:)
  10665. get_token();
  10666. expect(lexer::token_type::name_separator);
  10667. // parse and add value
  10668. get_token();
  10669. auto value = parse_internal(keep);
  10670. if (keep and keep_tag and not value.is_discarded())
  10671. {
  10672. result[key] = std::move(value);
  10673. }
  10674. // comma -> next value
  10675. get_token();
  10676. if (last_token == lexer::token_type::value_separator)
  10677. {
  10678. get_token();
  10679. continue;
  10680. }
  10681. // closing }
  10682. expect(lexer::token_type::end_object);
  10683. break;
  10684. }
  10685. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  10686. {
  10687. result = basic_json(value_t::discarded);
  10688. }
  10689. return result;
  10690. }
  10691. case lexer::token_type::begin_array:
  10692. {
  10693. if (keep and (not callback
  10694. or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0)))
  10695. {
  10696. // explicitly set result to object to cope with []
  10697. result.m_type = value_t::array;
  10698. result.m_value = value_t::array;
  10699. }
  10700. // read next token
  10701. get_token();
  10702. // closing ] -> we are done
  10703. if (last_token == lexer::token_type::end_array)
  10704. {
  10705. if (callback and not callback(--depth, parse_event_t::array_end, result))
  10706. {
  10707. result = basic_json(value_t::discarded);
  10708. }
  10709. return result;
  10710. }
  10711. // parse values
  10712. while (true)
  10713. {
  10714. // parse value
  10715. auto value = parse_internal(keep);
  10716. if (keep and not value.is_discarded())
  10717. {
  10718. result.push_back(std::move(value));
  10719. }
  10720. // comma -> next value
  10721. get_token();
  10722. if (last_token == lexer::token_type::value_separator)
  10723. {
  10724. get_token();
  10725. continue;
  10726. }
  10727. // closing ]
  10728. expect(lexer::token_type::end_array);
  10729. break;
  10730. }
  10731. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  10732. {
  10733. result = basic_json(value_t::discarded);
  10734. }
  10735. return result;
  10736. }
  10737. case lexer::token_type::literal_null:
  10738. {
  10739. result.m_type = value_t::null;
  10740. break;
  10741. }
  10742. case lexer::token_type::value_string:
  10743. {
  10744. result = basic_json(m_lexer.get_string());
  10745. break;
  10746. }
  10747. case lexer::token_type::literal_true:
  10748. {
  10749. result.m_type = value_t::boolean;
  10750. result.m_value = true;
  10751. break;
  10752. }
  10753. case lexer::token_type::literal_false:
  10754. {
  10755. result.m_type = value_t::boolean;
  10756. result.m_value = false;
  10757. break;
  10758. }
  10759. case lexer::token_type::value_unsigned:
  10760. {
  10761. result.m_type = value_t::number_unsigned;
  10762. result.m_value = m_lexer.get_number_unsigned();
  10763. break;
  10764. }
  10765. case lexer::token_type::value_integer:
  10766. {
  10767. result.m_type = value_t::number_integer;
  10768. result.m_value = m_lexer.get_number_integer();
  10769. break;
  10770. }
  10771. case lexer::token_type::value_float:
  10772. {
  10773. result.m_type = value_t::number_float;
  10774. result.m_value = m_lexer.get_number_float();
  10775. // throw in case of infinity or NAN
  10776. if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
  10777. {
  10778. JSON_THROW(out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  10779. }
  10780. break;
  10781. }
  10782. case lexer::token_type::parse_error:
  10783. {
  10784. // using "uninitialized" to avoid "expected" message
  10785. expect(lexer::token_type::uninitialized);
  10786. break; // LCOV_EXCL_LINE
  10787. }
  10788. default:
  10789. {
  10790. // the last token was unexpected; we expected a value
  10791. expect(lexer::token_type::literal_or_value);
  10792. break; // LCOV_EXCL_LINE
  10793. }
  10794. }
  10795. if (keep and callback and not callback(depth, parse_event_t::value, result))
  10796. {
  10797. result = basic_json(value_t::discarded);
  10798. }
  10799. return result;
  10800. }
  10801. /*!
  10802. @brief the acutal acceptor
  10803. @invariant 1. The last token is not yet processed. Therefore, the
  10804. caller of this function must make sure a token has
  10805. been read.
  10806. 2. When this function returns, the last token is processed.
  10807. That is, the last read character was already considered.
  10808. This invariant makes sure that no token needs to be "unput".
  10809. */
  10810. bool accept_internal()
  10811. {
  10812. switch (last_token)
  10813. {
  10814. case lexer::token_type::begin_object:
  10815. {
  10816. // read next token
  10817. get_token();
  10818. // closing } -> we are done
  10819. if (last_token == lexer::token_type::end_object)
  10820. {
  10821. return true;
  10822. }
  10823. // parse values
  10824. while (true)
  10825. {
  10826. // parse key
  10827. if (last_token != lexer::token_type::value_string)
  10828. {
  10829. return false;
  10830. }
  10831. // parse separator (:)
  10832. get_token();
  10833. if (last_token != lexer::token_type::name_separator)
  10834. {
  10835. return false;
  10836. }
  10837. // parse value
  10838. get_token();
  10839. if (not accept_internal())
  10840. {
  10841. return false;
  10842. }
  10843. // comma -> next value
  10844. get_token();
  10845. if (last_token == lexer::token_type::value_separator)
  10846. {
  10847. get_token();
  10848. continue;
  10849. }
  10850. // closing }
  10851. if (last_token != lexer::token_type::end_object)
  10852. {
  10853. return false;
  10854. }
  10855. return true;
  10856. }
  10857. }
  10858. case lexer::token_type::begin_array:
  10859. {
  10860. // read next token
  10861. get_token();
  10862. // closing ] -> we are done
  10863. if (last_token == lexer::token_type::end_array)
  10864. {
  10865. return true;
  10866. }
  10867. // parse values
  10868. while (true)
  10869. {
  10870. // parse value
  10871. if (not accept_internal())
  10872. {
  10873. return false;
  10874. }
  10875. // comma -> next value
  10876. get_token();
  10877. if (last_token == lexer::token_type::value_separator)
  10878. {
  10879. get_token();
  10880. continue;
  10881. }
  10882. // closing ]
  10883. if (last_token != lexer::token_type::end_array)
  10884. {
  10885. return false;
  10886. }
  10887. return true;
  10888. }
  10889. }
  10890. case lexer::token_type::literal_false:
  10891. case lexer::token_type::literal_null:
  10892. case lexer::token_type::literal_true:
  10893. case lexer::token_type::value_float:
  10894. case lexer::token_type::value_integer:
  10895. case lexer::token_type::value_string:
  10896. case lexer::token_type::value_unsigned:
  10897. {
  10898. return true;
  10899. }
  10900. default:
  10901. {
  10902. // the last token was unexpected
  10903. return false;
  10904. }
  10905. }
  10906. }
  10907. /// get next token from lexer
  10908. typename lexer::token_type get_token()
  10909. {
  10910. return (last_token = m_lexer.scan());
  10911. }
  10912. /*!
  10913. @throw parse_error.101 if expected token did not occur
  10914. */
  10915. void expect(typename lexer::token_type t)
  10916. {
  10917. if (JSON_UNLIKELY(t != last_token))
  10918. {
  10919. errored = true;
  10920. expected = t;
  10921. throw_exception();
  10922. }
  10923. }
  10924. [[noreturn]] void throw_exception() const
  10925. {
  10926. std::string error_msg = "syntax error - ";
  10927. if (last_token == lexer::token_type::parse_error)
  10928. {
  10929. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'";
  10930. }
  10931. else
  10932. {
  10933. error_msg += "unexpected " + std::string(lexer::token_type_name(last_token));
  10934. }
  10935. if (expected != lexer::token_type::uninitialized)
  10936. {
  10937. error_msg += "; expected " + std::string(lexer::token_type_name(expected));
  10938. }
  10939. JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
  10940. }
  10941. private:
  10942. /// current level of recursion
  10943. int depth = 0;
  10944. /// callback function
  10945. const parser_callback_t callback = nullptr;
  10946. /// the type of the last read token
  10947. typename lexer::token_type last_token = lexer::token_type::uninitialized;
  10948. /// the lexer
  10949. lexer m_lexer;
  10950. /// whether a syntax error occurred
  10951. bool errored = false;
  10952. /// possible reason for the syntax error
  10953. typename lexer::token_type expected = lexer::token_type::uninitialized;
  10954. };
  10955. public:
  10956. /*!
  10957. @brief JSON Pointer
  10958. A JSON pointer defines a string syntax for identifying a specific value
  10959. within a JSON document. It can be used with functions `at` and
  10960. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  10961. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  10962. @since version 2.0.0
  10963. */
  10964. class json_pointer
  10965. {
  10966. /// allow basic_json to access private members
  10967. friend class basic_json;
  10968. public:
  10969. /*!
  10970. @brief create JSON pointer
  10971. Create a JSON pointer according to the syntax described in
  10972. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10973. @param[in] s string representing the JSON pointer; if omitted, the
  10974. empty string is assumed which references the whole JSON
  10975. value
  10976. @throw parse_error.107 if the given JSON pointer @a s is nonempty and
  10977. does not begin with a slash (`/`); see example below
  10978. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s
  10979. is not followed by `0` (representing `~`) or `1` (representing `/`);
  10980. see example below
  10981. @liveexample{The example shows the construction several valid JSON
  10982. pointers as well as the exceptional behavior.,json_pointer}
  10983. @since version 2.0.0
  10984. */
  10985. explicit json_pointer(const std::string& s = "")
  10986. : reference_tokens(split(s))
  10987. {}
  10988. /*!
  10989. @brief return a string representation of the JSON pointer
  10990. @invariant For each JSON pointer `ptr`, it holds:
  10991. @code {.cpp}
  10992. ptr == json_pointer(ptr.to_string());
  10993. @endcode
  10994. @return a string representation of the JSON pointer
  10995. @liveexample{The example shows the result of `to_string`.,
  10996. json_pointer__to_string}
  10997. @since version 2.0.0
  10998. */
  10999. std::string to_string() const noexcept
  11000. {
  11001. return std::accumulate(reference_tokens.begin(),
  11002. reference_tokens.end(), std::string{},
  11003. [](const std::string & a, const std::string & b)
  11004. {
  11005. return a + "/" + escape(b);
  11006. });
  11007. }
  11008. /// @copydoc to_string()
  11009. operator std::string() const
  11010. {
  11011. return to_string();
  11012. }
  11013. private:
  11014. /*!
  11015. @brief remove and return last reference pointer
  11016. @throw out_of_range.405 if JSON pointer has no parent
  11017. */
  11018. std::string pop_back()
  11019. {
  11020. if (is_root())
  11021. {
  11022. JSON_THROW(out_of_range::create(405, "JSON pointer has no parent"));
  11023. }
  11024. auto last = reference_tokens.back();
  11025. reference_tokens.pop_back();
  11026. return last;
  11027. }
  11028. /// return whether pointer points to the root document
  11029. bool is_root() const
  11030. {
  11031. return reference_tokens.empty();
  11032. }
  11033. json_pointer top() const
  11034. {
  11035. if (is_root())
  11036. {
  11037. JSON_THROW(out_of_range::create(405, "JSON pointer has no parent"));
  11038. }
  11039. json_pointer result = *this;
  11040. result.reference_tokens = {reference_tokens[0]};
  11041. return result;
  11042. }
  11043. /*!
  11044. @brief create and return a reference to the pointed to value
  11045. @complexity Linear in the number of reference tokens.
  11046. @throw parse_error.109 if array index is not a number
  11047. @throw type_error.313 if value cannot be unflattened
  11048. */
  11049. reference get_and_create(reference j) const
  11050. {
  11051. pointer result = &j;
  11052. // in case no reference tokens exist, return a reference to the
  11053. // JSON value j which will be overwritten by a primitive value
  11054. for (const auto& reference_token : reference_tokens)
  11055. {
  11056. switch (result->m_type)
  11057. {
  11058. case value_t::null:
  11059. {
  11060. if (reference_token == "0")
  11061. {
  11062. // start a new array if reference token is 0
  11063. result = &result->operator[](0);
  11064. }
  11065. else
  11066. {
  11067. // start a new object otherwise
  11068. result = &result->operator[](reference_token);
  11069. }
  11070. break;
  11071. }
  11072. case value_t::object:
  11073. {
  11074. // create an entry in the object
  11075. result = &result->operator[](reference_token);
  11076. break;
  11077. }
  11078. case value_t::array:
  11079. {
  11080. // create an entry in the array
  11081. JSON_TRY
  11082. {
  11083. result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
  11084. }
  11085. JSON_CATCH (std::invalid_argument&)
  11086. {
  11087. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11088. }
  11089. break;
  11090. }
  11091. /*
  11092. The following code is only reached if there exists a
  11093. reference token _and_ the current value is primitive. In
  11094. this case, we have an error situation, because primitive
  11095. values may only occur as single value; that is, with an
  11096. empty list of reference tokens.
  11097. */
  11098. default:
  11099. {
  11100. JSON_THROW(type_error::create(313, "invalid value to unflatten"));
  11101. }
  11102. }
  11103. }
  11104. return *result;
  11105. }
  11106. /*!
  11107. @brief return a reference to the pointed to value
  11108. @note This version does not throw if a value is not present, but tries
  11109. to create nested values instead. For instance, calling this function
  11110. with pointer `"/this/that"` on a null value is equivalent to calling
  11111. `operator[]("this").operator[]("that")` on that value, effectively
  11112. changing the null value to an object.
  11113. @param[in] ptr a JSON value
  11114. @return reference to the JSON value pointed to by the JSON pointer
  11115. @complexity Linear in the length of the JSON pointer.
  11116. @throw parse_error.106 if an array index begins with '0'
  11117. @throw parse_error.109 if an array index was not a number
  11118. @throw out_of_range.404 if the JSON pointer can not be resolved
  11119. */
  11120. reference get_unchecked(pointer ptr) const
  11121. {
  11122. for (const auto& reference_token : reference_tokens)
  11123. {
  11124. // convert null values to arrays or objects before continuing
  11125. if (ptr->m_type == value_t::null)
  11126. {
  11127. // check if reference token is a number
  11128. const bool nums = std::all_of(reference_token.begin(),
  11129. reference_token.end(),
  11130. [](const char x)
  11131. {
  11132. return (x >= '0' and x <= '9');
  11133. });
  11134. // change value to array for numbers or "-" or to object
  11135. // otherwise
  11136. if (nums or reference_token == "-")
  11137. {
  11138. *ptr = value_t::array;
  11139. }
  11140. else
  11141. {
  11142. *ptr = value_t::object;
  11143. }
  11144. }
  11145. switch (ptr->m_type)
  11146. {
  11147. case value_t::object:
  11148. {
  11149. // use unchecked object access
  11150. ptr = &ptr->operator[](reference_token);
  11151. break;
  11152. }
  11153. case value_t::array:
  11154. {
  11155. // error condition (cf. RFC 6901, Sect. 4)
  11156. if (reference_token.size() > 1 and reference_token[0] == '0')
  11157. {
  11158. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  11159. }
  11160. if (reference_token == "-")
  11161. {
  11162. // explicitly treat "-" as index beyond the end
  11163. ptr = &ptr->operator[](ptr->m_value.array->size());
  11164. }
  11165. else
  11166. {
  11167. // convert array index to number; unchecked access
  11168. JSON_TRY
  11169. {
  11170. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  11171. }
  11172. JSON_CATCH (std::invalid_argument&)
  11173. {
  11174. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11175. }
  11176. }
  11177. break;
  11178. }
  11179. default:
  11180. {
  11181. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  11182. }
  11183. }
  11184. }
  11185. return *ptr;
  11186. }
  11187. /*!
  11188. @throw parse_error.106 if an array index begins with '0'
  11189. @throw parse_error.109 if an array index was not a number
  11190. @throw out_of_range.402 if the array index '-' is used
  11191. @throw out_of_range.404 if the JSON pointer can not be resolved
  11192. */
  11193. reference get_checked(pointer ptr) const
  11194. {
  11195. for (const auto& reference_token : reference_tokens)
  11196. {
  11197. switch (ptr->m_type)
  11198. {
  11199. case value_t::object:
  11200. {
  11201. // note: at performs range check
  11202. ptr = &ptr->at(reference_token);
  11203. break;
  11204. }
  11205. case value_t::array:
  11206. {
  11207. if (reference_token == "-")
  11208. {
  11209. // "-" always fails the range check
  11210. JSON_THROW(out_of_range::create(402, "array index '-' (" +
  11211. std::to_string(ptr->m_value.array->size()) +
  11212. ") is out of range"));
  11213. }
  11214. // error condition (cf. RFC 6901, Sect. 4)
  11215. if (reference_token.size() > 1 and reference_token[0] == '0')
  11216. {
  11217. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  11218. }
  11219. // note: at performs range check
  11220. JSON_TRY
  11221. {
  11222. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  11223. }
  11224. JSON_CATCH (std::invalid_argument&)
  11225. {
  11226. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11227. }
  11228. break;
  11229. }
  11230. default:
  11231. {
  11232. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  11233. }
  11234. }
  11235. }
  11236. return *ptr;
  11237. }
  11238. /*!
  11239. @brief return a const reference to the pointed to value
  11240. @param[in] ptr a JSON value
  11241. @return const reference to the JSON value pointed to by the JSON
  11242. pointer
  11243. @throw parse_error.106 if an array index begins with '0'
  11244. @throw parse_error.109 if an array index was not a number
  11245. @throw out_of_range.402 if the array index '-' is used
  11246. @throw out_of_range.404 if the JSON pointer can not be resolved
  11247. */
  11248. const_reference get_unchecked(const_pointer ptr) const
  11249. {
  11250. for (const auto& reference_token : reference_tokens)
  11251. {
  11252. switch (ptr->m_type)
  11253. {
  11254. case value_t::object:
  11255. {
  11256. // use unchecked object access
  11257. ptr = &ptr->operator[](reference_token);
  11258. break;
  11259. }
  11260. case value_t::array:
  11261. {
  11262. if (reference_token == "-")
  11263. {
  11264. // "-" cannot be used for const access
  11265. JSON_THROW(out_of_range::create(402, "array index '-' (" +
  11266. std::to_string(ptr->m_value.array->size()) +
  11267. ") is out of range"));
  11268. }
  11269. // error condition (cf. RFC 6901, Sect. 4)
  11270. if (reference_token.size() > 1 and reference_token[0] == '0')
  11271. {
  11272. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  11273. }
  11274. // use unchecked array access
  11275. JSON_TRY
  11276. {
  11277. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  11278. }
  11279. JSON_CATCH (std::invalid_argument&)
  11280. {
  11281. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11282. }
  11283. break;
  11284. }
  11285. default:
  11286. {
  11287. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  11288. }
  11289. }
  11290. }
  11291. return *ptr;
  11292. }
  11293. /*!
  11294. @throw parse_error.106 if an array index begins with '0'
  11295. @throw parse_error.109 if an array index was not a number
  11296. @throw out_of_range.402 if the array index '-' is used
  11297. @throw out_of_range.404 if the JSON pointer can not be resolved
  11298. */
  11299. const_reference get_checked(const_pointer ptr) const
  11300. {
  11301. for (const auto& reference_token : reference_tokens)
  11302. {
  11303. switch (ptr->m_type)
  11304. {
  11305. case value_t::object:
  11306. {
  11307. // note: at performs range check
  11308. ptr = &ptr->at(reference_token);
  11309. break;
  11310. }
  11311. case value_t::array:
  11312. {
  11313. if (reference_token == "-")
  11314. {
  11315. // "-" always fails the range check
  11316. JSON_THROW(out_of_range::create(402, "array index '-' (" +
  11317. std::to_string(ptr->m_value.array->size()) +
  11318. ") is out of range"));
  11319. }
  11320. // error condition (cf. RFC 6901, Sect. 4)
  11321. if (reference_token.size() > 1 and reference_token[0] == '0')
  11322. {
  11323. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  11324. }
  11325. // note: at performs range check
  11326. JSON_TRY
  11327. {
  11328. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  11329. }
  11330. JSON_CATCH (std::invalid_argument&)
  11331. {
  11332. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11333. }
  11334. break;
  11335. }
  11336. default:
  11337. {
  11338. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  11339. }
  11340. }
  11341. }
  11342. return *ptr;
  11343. }
  11344. /*!
  11345. @brief split the string input to reference tokens
  11346. @note This function is only called by the json_pointer constructor.
  11347. All exceptions below are documented there.
  11348. @throw parse_error.107 if the pointer is not empty or begins with '/'
  11349. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  11350. */
  11351. static std::vector<std::string> split(const std::string& reference_string)
  11352. {
  11353. std::vector<std::string> result;
  11354. // special case: empty reference string -> no reference tokens
  11355. if (reference_string.empty())
  11356. {
  11357. return result;
  11358. }
  11359. // check if nonempty reference string begins with slash
  11360. if (reference_string[0] != '/')
  11361. {
  11362. JSON_THROW(parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'"));
  11363. }
  11364. // extract the reference tokens:
  11365. // - slash: position of the last read slash (or end of string)
  11366. // - start: position after the previous slash
  11367. for (
  11368. // search for the first slash after the first character
  11369. size_t slash = reference_string.find_first_of('/', 1),
  11370. // set the beginning of the first reference token
  11371. start = 1;
  11372. // we can stop if start == string::npos+1 = 0
  11373. start != 0;
  11374. // set the beginning of the next reference token
  11375. // (will eventually be 0 if slash == std::string::npos)
  11376. start = slash + 1,
  11377. // find next slash
  11378. slash = reference_string.find_first_of('/', start))
  11379. {
  11380. // use the text between the beginning of the reference token
  11381. // (start) and the last slash (slash).
  11382. auto reference_token = reference_string.substr(start, slash - start);
  11383. // check reference tokens are properly escaped
  11384. for (size_t pos = reference_token.find_first_of('~');
  11385. pos != std::string::npos;
  11386. pos = reference_token.find_first_of('~', pos + 1))
  11387. {
  11388. assert(reference_token[pos] == '~');
  11389. // ~ must be followed by 0 or 1
  11390. if (pos == reference_token.size() - 1 or
  11391. (reference_token[pos + 1] != '0' and
  11392. reference_token[pos + 1] != '1'))
  11393. {
  11394. JSON_THROW(parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  11395. }
  11396. }
  11397. // finally, store the reference token
  11398. unescape(reference_token);
  11399. result.push_back(reference_token);
  11400. }
  11401. return result;
  11402. }
  11403. /*!
  11404. @brief replace all occurrences of a substring by another string
  11405. @param[in,out] s the string to manipulate; changed so that all
  11406. occurrences of @a f are replaced with @a t
  11407. @param[in] f the substring to replace with @a t
  11408. @param[in] t the string to replace @a f
  11409. @pre The search string @a f must not be empty. **This precondition is
  11410. enforced with an assertion.**
  11411. @since version 2.0.0
  11412. */
  11413. static void replace_substring(std::string& s,
  11414. const std::string& f,
  11415. const std::string& t)
  11416. {
  11417. assert(not f.empty());
  11418. for (
  11419. size_t pos = s.find(f); // find first occurrence of f
  11420. pos != std::string::npos; // make sure f was found
  11421. s.replace(pos, f.size(), t), // replace with t
  11422. pos = s.find(f, pos + t.size()) // find next occurrence of f
  11423. );
  11424. }
  11425. /// escape tilde and slash
  11426. static std::string escape(std::string s)
  11427. {
  11428. // escape "~"" to "~0" and "/" to "~1"
  11429. replace_substring(s, "~", "~0");
  11430. replace_substring(s, "/", "~1");
  11431. return s;
  11432. }
  11433. /// unescape tilde and slash
  11434. static void unescape(std::string& s)
  11435. {
  11436. // first transform any occurrence of the sequence '~1' to '/'
  11437. replace_substring(s, "~1", "/");
  11438. // then transform any occurrence of the sequence '~0' to '~'
  11439. replace_substring(s, "~0", "~");
  11440. }
  11441. /*!
  11442. @param[in] reference_string the reference string to the current value
  11443. @param[in] value the value to consider
  11444. @param[in,out] result the result object to insert values to
  11445. @note Empty objects or arrays are flattened to `null`.
  11446. */
  11447. static void flatten(const std::string& reference_string,
  11448. const basic_json& value,
  11449. basic_json& result)
  11450. {
  11451. switch (value.m_type)
  11452. {
  11453. case value_t::array:
  11454. {
  11455. if (value.m_value.array->empty())
  11456. {
  11457. // flatten empty array as null
  11458. result[reference_string] = nullptr;
  11459. }
  11460. else
  11461. {
  11462. // iterate array and use index as reference string
  11463. for (size_t i = 0; i < value.m_value.array->size(); ++i)
  11464. {
  11465. flatten(reference_string + "/" + std::to_string(i),
  11466. value.m_value.array->operator[](i), result);
  11467. }
  11468. }
  11469. break;
  11470. }
  11471. case value_t::object:
  11472. {
  11473. if (value.m_value.object->empty())
  11474. {
  11475. // flatten empty object as null
  11476. result[reference_string] = nullptr;
  11477. }
  11478. else
  11479. {
  11480. // iterate object and use keys as reference string
  11481. for (const auto& element : *value.m_value.object)
  11482. {
  11483. flatten(reference_string + "/" + escape(element.first),
  11484. element.second, result);
  11485. }
  11486. }
  11487. break;
  11488. }
  11489. default:
  11490. {
  11491. // add primitive value with its reference string
  11492. result[reference_string] = value;
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. /*!
  11498. @param[in] value flattened JSON
  11499. @return unflattened JSON
  11500. @throw parse_error.109 if array index is not a number
  11501. @throw type_error.314 if value is not an object
  11502. @throw type_error.315 if object values are not primitive
  11503. @throw type_error.313 if value cannot be unflattened
  11504. */
  11505. static basic_json unflatten(const basic_json& value)
  11506. {
  11507. if (not value.is_object())
  11508. {
  11509. JSON_THROW(type_error::create(314, "only objects can be unflattened"));
  11510. }
  11511. basic_json result;
  11512. // iterate the JSON object values
  11513. for (const auto& element : *value.m_value.object)
  11514. {
  11515. if (not element.second.is_primitive())
  11516. {
  11517. JSON_THROW(type_error::create(315, "values in object must be primitive"));
  11518. }
  11519. // assign value to reference pointed to by JSON pointer; Note
  11520. // that if the JSON pointer is "" (i.e., points to the whole
  11521. // value), function get_and_create returns a reference to
  11522. // result itself. An assignment will then create a primitive
  11523. // value.
  11524. json_pointer(element.first).get_and_create(result) = element.second;
  11525. }
  11526. return result;
  11527. }
  11528. friend bool operator==(json_pointer const& lhs,
  11529. json_pointer const& rhs) noexcept
  11530. {
  11531. return lhs.reference_tokens == rhs.reference_tokens;
  11532. }
  11533. friend bool operator!=(json_pointer const& lhs,
  11534. json_pointer const& rhs) noexcept
  11535. {
  11536. return !(lhs == rhs);
  11537. }
  11538. /// the reference tokens
  11539. std::vector<std::string> reference_tokens {};
  11540. };
  11541. //////////////////////////
  11542. // JSON Pointer support //
  11543. //////////////////////////
  11544. /// @name JSON Pointer functions
  11545. /// @{
  11546. /*!
  11547. @brief access specified element via JSON Pointer
  11548. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11549. No bound checking is performed. Similar to @ref operator[](const typename
  11550. object_t::key_type&), `null` values are created in arrays and objects if
  11551. necessary.
  11552. In particular:
  11553. - If the JSON pointer points to an object key that does not exist, it
  11554. is created an filled with a `null` value before a reference to it
  11555. is returned.
  11556. - If the JSON pointer points to an array index that does not exist, it
  11557. is created an filled with a `null` value before a reference to it
  11558. is returned. All indices between the current maximum and the given
  11559. index are also filled with `null`.
  11560. - The special value `-` is treated as a synonym for the index past the
  11561. end.
  11562. @param[in] ptr a JSON pointer
  11563. @return reference to the element pointed to by @a ptr
  11564. @complexity Constant.
  11565. @throw parse_error.106 if an array index begins with '0'
  11566. @throw parse_error.109 if an array index was not a number
  11567. @throw out_of_range.404 if the JSON pointer can not be resolved
  11568. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  11569. @since version 2.0.0
  11570. */
  11571. reference operator[](const json_pointer& ptr)
  11572. {
  11573. return ptr.get_unchecked(this);
  11574. }
  11575. /*!
  11576. @brief access specified element via JSON Pointer
  11577. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11578. No bound checking is performed. The function does not change the JSON
  11579. value; no `null` values are created. In particular, the the special value
  11580. `-` yields an exception.
  11581. @param[in] ptr JSON pointer to the desired element
  11582. @return const reference to the element pointed to by @a ptr
  11583. @complexity Constant.
  11584. @throw parse_error.106 if an array index begins with '0'
  11585. @throw parse_error.109 if an array index was not a number
  11586. @throw out_of_range.402 if the array index '-' is used
  11587. @throw out_of_range.404 if the JSON pointer can not be resolved
  11588. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  11589. @since version 2.0.0
  11590. */
  11591. const_reference operator[](const json_pointer& ptr) const
  11592. {
  11593. return ptr.get_unchecked(this);
  11594. }
  11595. /*!
  11596. @brief access specified element via JSON Pointer
  11597. Returns a reference to the element at with specified JSON pointer @a ptr,
  11598. with bounds checking.
  11599. @param[in] ptr JSON pointer to the desired element
  11600. @return reference to the element pointed to by @a ptr
  11601. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11602. begins with '0'. See example below.
  11603. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11604. is not a number. See example below.
  11605. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11606. is out of range. See example below.
  11607. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11608. pointer @a ptr. As `at` provides checked access (and no elements are
  11609. implicitly inserted), the index '-' is always invalid. See example below.
  11610. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11611. See example below.
  11612. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11613. changes in the JSON value.
  11614. @complexity Constant.
  11615. @since version 2.0.0
  11616. @liveexample{The behavior is shown in the example.,at_json_pointer}
  11617. */
  11618. reference at(const json_pointer& ptr)
  11619. {
  11620. return ptr.get_checked(this);
  11621. }
  11622. /*!
  11623. @brief access specified element via JSON Pointer
  11624. Returns a const reference to the element at with specified JSON pointer @a
  11625. ptr, with bounds checking.
  11626. @param[in] ptr JSON pointer to the desired element
  11627. @return reference to the element pointed to by @a ptr
  11628. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11629. begins with '0'. See example below.
  11630. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11631. is not a number. See example below.
  11632. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11633. is out of range. See example below.
  11634. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11635. pointer @a ptr. As `at` provides checked access (and no elements are
  11636. implicitly inserted), the index '-' is always invalid. See example below.
  11637. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11638. See example below.
  11639. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11640. changes in the JSON value.
  11641. @complexity Constant.
  11642. @since version 2.0.0
  11643. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  11644. */
  11645. const_reference at(const json_pointer& ptr) const
  11646. {
  11647. return ptr.get_checked(this);
  11648. }
  11649. /*!
  11650. @brief return flattened JSON value
  11651. The function creates a JSON object whose keys are JSON pointers (see [RFC
  11652. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  11653. primitive. The original JSON value can be restored using the @ref
  11654. unflatten() function.
  11655. @return an object that maps JSON pointers to primitive values
  11656. @note Empty objects and arrays are flattened to `null` and will not be
  11657. reconstructed correctly by the @ref unflatten() function.
  11658. @complexity Linear in the size the JSON value.
  11659. @liveexample{The following code shows how a JSON object is flattened to an
  11660. object whose keys consist of JSON pointers.,flatten}
  11661. @sa @ref unflatten() for the reverse function
  11662. @since version 2.0.0
  11663. */
  11664. basic_json flatten() const
  11665. {
  11666. basic_json result(value_t::object);
  11667. json_pointer::flatten("", *this, result);
  11668. return result;
  11669. }
  11670. /*!
  11671. @brief unflatten a previously flattened JSON value
  11672. The function restores the arbitrary nesting of a JSON value that has been
  11673. flattened before using the @ref flatten() function. The JSON value must
  11674. meet certain constraints:
  11675. 1. The value must be an object.
  11676. 2. The keys must be JSON pointers (see
  11677. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  11678. 3. The mapped values must be primitive JSON types.
  11679. @return the original JSON from a flattened version
  11680. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  11681. values and can not unflattened to their original type. Apart from
  11682. this example, for a JSON value `j`, the following is always true:
  11683. `j == j.flatten().unflatten()`.
  11684. @complexity Linear in the size the JSON value.
  11685. @throw type_error.314 if value is not an object
  11686. @throw type_error.315 if object values are not primitive
  11687. @liveexample{The following code shows how a flattened JSON object is
  11688. unflattened into the original nested JSON object.,unflatten}
  11689. @sa @ref flatten() for the reverse function
  11690. @since version 2.0.0
  11691. */
  11692. basic_json unflatten() const
  11693. {
  11694. return json_pointer::unflatten(*this);
  11695. }
  11696. /// @}
  11697. //////////////////////////
  11698. // JSON Patch functions //
  11699. //////////////////////////
  11700. /// @name JSON Patch functions
  11701. /// @{
  11702. /*!
  11703. @brief applies a JSON patch
  11704. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  11705. expressing a sequence of operations to apply to a JSON) document. With
  11706. this function, a JSON Patch is applied to the current JSON value by
  11707. executing all operations from the patch.
  11708. @param[in] json_patch JSON patch document
  11709. @return patched document
  11710. @note The application of a patch is atomic: Either all operations succeed
  11711. and the patched document is returned or an exception is thrown. In
  11712. any case, the original value is not changed: the patch is applied
  11713. to a copy of the value.
  11714. @throw parse_error.104 if the JSON patch does not consist of an array of
  11715. objects
  11716. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  11717. attributes are missing); example: `"operation add must have member path"`
  11718. @throw out_of_range.401 if an array index is out of range.
  11719. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  11720. resolved successfully in the current JSON value; example: `"key baz not
  11721. found"`
  11722. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  11723. "move")
  11724. @throw other_error.501 if "test" operation was unsuccessful
  11725. @complexity Linear in the size of the JSON value and the length of the
  11726. JSON patch. As usually only a fraction of the JSON value is affected by
  11727. the patch, the complexity can usually be neglected.
  11728. @liveexample{The following code shows how a JSON patch is applied to a
  11729. value.,patch}
  11730. @sa @ref diff -- create a JSON patch by comparing two JSON values
  11731. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11732. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  11733. @since version 2.0.0
  11734. */
  11735. basic_json patch(const basic_json& json_patch) const
  11736. {
  11737. // make a working copy to apply the patch to
  11738. basic_json result = *this;
  11739. // the valid JSON Patch operations
  11740. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  11741. const auto get_op = [](const std::string & op)
  11742. {
  11743. if (op == "add")
  11744. {
  11745. return patch_operations::add;
  11746. }
  11747. if (op == "remove")
  11748. {
  11749. return patch_operations::remove;
  11750. }
  11751. if (op == "replace")
  11752. {
  11753. return patch_operations::replace;
  11754. }
  11755. if (op == "move")
  11756. {
  11757. return patch_operations::move;
  11758. }
  11759. if (op == "copy")
  11760. {
  11761. return patch_operations::copy;
  11762. }
  11763. if (op == "test")
  11764. {
  11765. return patch_operations::test;
  11766. }
  11767. return patch_operations::invalid;
  11768. };
  11769. // wrapper for "add" operation; add value at ptr
  11770. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  11771. {
  11772. // adding to the root of the target document means replacing it
  11773. if (ptr.is_root())
  11774. {
  11775. result = val;
  11776. }
  11777. else
  11778. {
  11779. // make sure the top element of the pointer exists
  11780. json_pointer top_pointer = ptr.top();
  11781. if (top_pointer != ptr)
  11782. {
  11783. result.at(top_pointer);
  11784. }
  11785. // get reference to parent of JSON pointer ptr
  11786. const auto last_path = ptr.pop_back();
  11787. basic_json& parent = result[ptr];
  11788. switch (parent.m_type)
  11789. {
  11790. case value_t::null:
  11791. case value_t::object:
  11792. {
  11793. // use operator[] to add value
  11794. parent[last_path] = val;
  11795. break;
  11796. }
  11797. case value_t::array:
  11798. {
  11799. if (last_path == "-")
  11800. {
  11801. // special case: append to back
  11802. parent.push_back(val);
  11803. }
  11804. else
  11805. {
  11806. const auto idx = std::stoi(last_path);
  11807. if (static_cast<size_type>(idx) > parent.size())
  11808. {
  11809. // avoid undefined behavior
  11810. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11811. }
  11812. else
  11813. {
  11814. // default case: insert add offset
  11815. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  11816. }
  11817. }
  11818. break;
  11819. }
  11820. default:
  11821. {
  11822. // if there exists a parent it cannot be primitive
  11823. assert(false); // LCOV_EXCL_LINE
  11824. }
  11825. }
  11826. }
  11827. };
  11828. // wrapper for "remove" operation; remove value at ptr
  11829. const auto operation_remove = [&result](json_pointer & ptr)
  11830. {
  11831. // get reference to parent of JSON pointer ptr
  11832. const auto last_path = ptr.pop_back();
  11833. basic_json& parent = result.at(ptr);
  11834. // remove child
  11835. if (parent.is_object())
  11836. {
  11837. // perform range check
  11838. auto it = parent.find(last_path);
  11839. if (it != parent.end())
  11840. {
  11841. parent.erase(it);
  11842. }
  11843. else
  11844. {
  11845. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  11846. }
  11847. }
  11848. else if (parent.is_array())
  11849. {
  11850. // note erase performs range check
  11851. parent.erase(static_cast<size_type>(std::stoi(last_path)));
  11852. }
  11853. };
  11854. // type check: top level value must be an array
  11855. if (not json_patch.is_array())
  11856. {
  11857. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11858. }
  11859. // iterate and apply the operations
  11860. for (const auto& val : json_patch)
  11861. {
  11862. // wrapper to get a value for an operation
  11863. const auto get_value = [&val](const std::string & op,
  11864. const std::string & member,
  11865. bool string_type) -> basic_json&
  11866. {
  11867. // find value
  11868. auto it = val.m_value.object->find(member);
  11869. // context-sensitive error message
  11870. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  11871. // check if desired value is present
  11872. if (it == val.m_value.object->end())
  11873. {
  11874. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  11875. }
  11876. // check if result is of type string
  11877. if (string_type and not it->second.is_string())
  11878. {
  11879. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  11880. }
  11881. // no error: return value
  11882. return it->second;
  11883. };
  11884. // type check: every element of the array must be an object
  11885. if (not val.is_object())
  11886. {
  11887. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11888. }
  11889. // collect mandatory members
  11890. const std::string op = get_value("op", "op", true);
  11891. const std::string path = get_value(op, "path", true);
  11892. json_pointer ptr(path);
  11893. switch (get_op(op))
  11894. {
  11895. case patch_operations::add:
  11896. {
  11897. operation_add(ptr, get_value("add", "value", false));
  11898. break;
  11899. }
  11900. case patch_operations::remove:
  11901. {
  11902. operation_remove(ptr);
  11903. break;
  11904. }
  11905. case patch_operations::replace:
  11906. {
  11907. // the "path" location must exist - use at()
  11908. result.at(ptr) = get_value("replace", "value", false);
  11909. break;
  11910. }
  11911. case patch_operations::move:
  11912. {
  11913. const std::string from_path = get_value("move", "from", true);
  11914. json_pointer from_ptr(from_path);
  11915. // the "from" location must exist - use at()
  11916. basic_json v = result.at(from_ptr);
  11917. // The move operation is functionally identical to a
  11918. // "remove" operation on the "from" location, followed
  11919. // immediately by an "add" operation at the target
  11920. // location with the value that was just removed.
  11921. operation_remove(from_ptr);
  11922. operation_add(ptr, v);
  11923. break;
  11924. }
  11925. case patch_operations::copy:
  11926. {
  11927. const std::string from_path = get_value("copy", "from", true);
  11928. const json_pointer from_ptr(from_path);
  11929. // the "from" location must exist - use at()
  11930. result[ptr] = result.at(from_ptr);
  11931. break;
  11932. }
  11933. case patch_operations::test:
  11934. {
  11935. bool success = false;
  11936. JSON_TRY
  11937. {
  11938. // check if "value" matches the one at "path"
  11939. // the "path" location must exist - use at()
  11940. success = (result.at(ptr) == get_value("test", "value", false));
  11941. }
  11942. JSON_CATCH (out_of_range&)
  11943. {
  11944. // ignore out of range errors: success remains false
  11945. }
  11946. // throw an exception if test fails
  11947. if (not success)
  11948. {
  11949. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  11950. }
  11951. break;
  11952. }
  11953. case patch_operations::invalid:
  11954. {
  11955. // op must be "add", "remove", "replace", "move", "copy", or
  11956. // "test"
  11957. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  11958. }
  11959. }
  11960. }
  11961. return result;
  11962. }
  11963. /*!
  11964. @brief creates a diff as a JSON patch
  11965. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  11966. be changed into the value @a target by calling @ref patch function.
  11967. @invariant For two JSON values @a source and @a target, the following code
  11968. yields always `true`:
  11969. @code {.cpp}
  11970. source.patch(diff(source, target)) == target;
  11971. @endcode
  11972. @note Currently, only `remove`, `add`, and `replace` operations are
  11973. generated.
  11974. @param[in] source JSON value to compare from
  11975. @param[in] target JSON value to compare against
  11976. @param[in] path helper value to create JSON pointers
  11977. @return a JSON patch to convert the @a source to @a target
  11978. @complexity Linear in the lengths of @a source and @a target.
  11979. @liveexample{The following code shows how a JSON patch is created as a
  11980. diff for two JSON values.,diff}
  11981. @sa @ref patch -- apply a JSON patch
  11982. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11983. @since version 2.0.0
  11984. */
  11985. static basic_json diff(const basic_json& source,
  11986. const basic_json& target,
  11987. const std::string& path = "")
  11988. {
  11989. // the patch
  11990. basic_json result(value_t::array);
  11991. // if the values are the same, return empty patch
  11992. if (source == target)
  11993. {
  11994. return result;
  11995. }
  11996. if (source.type() != target.type())
  11997. {
  11998. // different types: replace value
  11999. result.push_back(
  12000. {
  12001. {"op", "replace"},
  12002. {"path", path},
  12003. {"value", target}
  12004. });
  12005. }
  12006. else
  12007. {
  12008. switch (source.type())
  12009. {
  12010. case value_t::array:
  12011. {
  12012. // first pass: traverse common elements
  12013. size_t i = 0;
  12014. while (i < source.size() and i < target.size())
  12015. {
  12016. // recursive call to compare array values at index i
  12017. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  12018. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  12019. ++i;
  12020. }
  12021. // i now reached the end of at least one array
  12022. // in a second pass, traverse the remaining elements
  12023. // remove my remaining elements
  12024. const auto end_index = static_cast<difference_type>(result.size());
  12025. while (i < source.size())
  12026. {
  12027. // add operations in reverse order to avoid invalid
  12028. // indices
  12029. result.insert(result.begin() + end_index, object(
  12030. {
  12031. {"op", "remove"},
  12032. {"path", path + "/" + std::to_string(i)}
  12033. }));
  12034. ++i;
  12035. }
  12036. // add other remaining elements
  12037. while (i < target.size())
  12038. {
  12039. result.push_back(
  12040. {
  12041. {"op", "add"},
  12042. {"path", path + "/" + std::to_string(i)},
  12043. {"value", target[i]}
  12044. });
  12045. ++i;
  12046. }
  12047. break;
  12048. }
  12049. case value_t::object:
  12050. {
  12051. // first pass: traverse this object's elements
  12052. for (auto it = source.begin(); it != source.end(); ++it)
  12053. {
  12054. // escape the key name to be used in a JSON patch
  12055. const auto key = json_pointer::escape(it.key());
  12056. if (target.find(it.key()) != target.end())
  12057. {
  12058. // recursive call to compare object values at key it
  12059. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  12060. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  12061. }
  12062. else
  12063. {
  12064. // found a key that is not in o -> remove it
  12065. result.push_back(object(
  12066. {
  12067. {"op", "remove"},
  12068. {"path", path + "/" + key}
  12069. }));
  12070. }
  12071. }
  12072. // second pass: traverse other object's elements
  12073. for (auto it = target.begin(); it != target.end(); ++it)
  12074. {
  12075. if (source.find(it.key()) == source.end())
  12076. {
  12077. // found a key that is not in this -> add it
  12078. const auto key = json_pointer::escape(it.key());
  12079. result.push_back(
  12080. {
  12081. {"op", "add"},
  12082. {"path", path + "/" + key},
  12083. {"value", it.value()}
  12084. });
  12085. }
  12086. }
  12087. break;
  12088. }
  12089. default:
  12090. {
  12091. // both primitive type: replace value
  12092. result.push_back(
  12093. {
  12094. {"op", "replace"},
  12095. {"path", path},
  12096. {"value", target}
  12097. });
  12098. break;
  12099. }
  12100. }
  12101. }
  12102. return result;
  12103. }
  12104. /// @}
  12105. };
  12106. /////////////
  12107. // presets //
  12108. /////////////
  12109. /*!
  12110. @brief default JSON class
  12111. This type is the default specialization of the @ref basic_json class which
  12112. uses the standard template types.
  12113. @since version 1.0.0
  12114. */
  12115. using json = basic_json<>;
  12116. } // namespace nlohmann
  12117. ///////////////////////
  12118. // nonmember support //
  12119. ///////////////////////
  12120. // specialization of std::swap, and std::hash
  12121. namespace std
  12122. {
  12123. /*!
  12124. @brief exchanges the values of two JSON objects
  12125. @since version 1.0.0
  12126. */
  12127. template<>
  12128. inline void swap(nlohmann::json& j1,
  12129. nlohmann::json& j2) noexcept(
  12130. is_nothrow_move_constructible<nlohmann::json>::value and
  12131. is_nothrow_move_assignable<nlohmann::json>::value
  12132. )
  12133. {
  12134. j1.swap(j2);
  12135. }
  12136. /// hash value for JSON objects
  12137. template<>
  12138. struct hash<nlohmann::json>
  12139. {
  12140. /*!
  12141. @brief return a hash value for a JSON object
  12142. @since version 1.0.0
  12143. */
  12144. std::size_t operator()(const nlohmann::json& j) const
  12145. {
  12146. // a naive hashing via the string representation
  12147. const auto& h = hash<nlohmann::json::string_t>();
  12148. return h(j.dump());
  12149. }
  12150. };
  12151. /// specialization for std::less<value_t>
  12152. template <>
  12153. struct less<::nlohmann::detail::value_t>
  12154. {
  12155. /*!
  12156. @brief compare two value_t enum values
  12157. @since version 3.0.0
  12158. */
  12159. bool operator()(nlohmann::detail::value_t lhs,
  12160. nlohmann::detail::value_t rhs) const noexcept
  12161. {
  12162. return nlohmann::detail::operator<(lhs, rhs);
  12163. }
  12164. };
  12165. } // namespace std
  12166. /*!
  12167. @brief user-defined string literal for JSON values
  12168. This operator implements a user-defined string literal for JSON objects. It
  12169. can be used by adding `"_json"` to a string literal and returns a JSON object
  12170. if no parse error occurred.
  12171. @param[in] s a string representation of a JSON object
  12172. @param[in] n the length of string @a s
  12173. @return a JSON object
  12174. @since version 1.0.0
  12175. */
  12176. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  12177. {
  12178. return nlohmann::json::parse(s, s + n);
  12179. }
  12180. /*!
  12181. @brief user-defined string literal for JSON pointer
  12182. This operator implements a user-defined string literal for JSON Pointers. It
  12183. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  12184. object if no parse error occurred.
  12185. @param[in] s a string representation of a JSON Pointer
  12186. @param[in] n the length of string @a s
  12187. @return a JSON pointer object
  12188. @since version 2.0.0
  12189. */
  12190. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  12191. {
  12192. return nlohmann::json::json_pointer(std::string(s, n));
  12193. }
  12194. // restore GCC/clang diagnostic settings
  12195. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  12196. #pragma GCC diagnostic pop
  12197. #endif
  12198. #if defined(__clang__)
  12199. #pragma GCC diagnostic pop
  12200. #endif
  12201. // clean up
  12202. #undef JSON_CATCH
  12203. #undef JSON_THROW
  12204. #undef JSON_TRY
  12205. #undef JSON_LIKELY
  12206. #undef JSON_UNLIKELY
  12207. #undef JSON_DEPRECATED
  12208. #endif