json.hpp 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 2.0.10
  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, for_each, transform
  27. #include <array> // array
  28. #include <cassert> // assert
  29. #include <cctype> // isdigit
  30. #include <ciso646> // and, not, or
  31. #include <cmath> // isfinite, ldexp, signbit
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <cstdint> // int64_t, uint64_t
  34. #include <cstdlib> // strtod, strtof, strtold, strtoul
  35. #include <cstring> // strlen
  36. #include <functional> // function, hash, less
  37. #include <initializer_list> // initializer_list
  38. #include <iomanip> // setw
  39. #include <iostream> // istream, ostream
  40. #include <iterator> // advance, begin, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
  41. #include <limits> // numeric_limits
  42. #include <locale> // locale
  43. #include <map> // map
  44. #include <memory> // addressof, allocator, allocator_traits, unique_ptr
  45. #include <numeric> // accumulate
  46. #include <sstream> // stringstream
  47. #include <stdexcept> // domain_error, invalid_argument, out_of_range
  48. #include <string> // getline, stoi, string, to_string
  49. #include <type_traits> // add_pointer, enable_if, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_floating_point, is_integral, is_nothrow_move_assignable, std::is_nothrow_move_constructible, std::is_pointer, std::is_reference, std::is_same, remove_const, remove_pointer, remove_reference
  50. #include <utility> // declval, forward, make_pair, move, pair, swap
  51. #include <vector> // vector
  52. // exclude unsupported compilers
  53. #if defined(__clang__)
  54. #define CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
  55. #if CLANG_VERSION < 30400
  56. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  57. #endif
  58. #elif defined(__GNUC__)
  59. #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  60. #if GCC_VERSION < 40900
  61. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  62. #endif
  63. #endif
  64. // disable float-equal warnings on GCC/clang
  65. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  66. #pragma GCC diagnostic push
  67. #pragma GCC diagnostic ignored "-Wfloat-equal"
  68. #endif
  69. // disable documentation warnings on clang
  70. #if defined(__clang__)
  71. #pragma GCC diagnostic push
  72. #pragma GCC diagnostic ignored "-Wdocumentation"
  73. #endif
  74. // allow for portable deprecation warnings
  75. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  76. #define JSON_DEPRECATED __attribute__((deprecated))
  77. #elif defined(_MSC_VER)
  78. #define JSON_DEPRECATED __declspec(deprecated)
  79. #else
  80. #define JSON_DEPRECATED
  81. #endif
  82. /*!
  83. @brief namespace for Niels Lohmann
  84. @see https://github.com/nlohmann
  85. @since version 1.0.0
  86. */
  87. namespace nlohmann
  88. {
  89. /*!
  90. @brief unnamed namespace with internal helper functions
  91. @since version 1.0.0
  92. */
  93. namespace
  94. {
  95. /*!
  96. @brief Helper to determine whether there's a key_type for T.
  97. Thus helper is used to tell associative containers apart from other containers
  98. such as sequence containers. For instance, `std::map` passes the test as it
  99. contains a `mapped_type`, whereas `std::vector` fails the test.
  100. @sa http://stackoverflow.com/a/7728728/266378
  101. @since version 1.0.0, overworked in version 2.0.6
  102. */
  103. template<typename T>
  104. struct has_mapped_type
  105. {
  106. private:
  107. template <typename U, typename = typename U::mapped_type>
  108. static int detect(U&&);
  109. static void detect(...);
  110. public:
  111. static constexpr bool value =
  112. std::is_integral<decltype(detect(std::declval<T>()))>::value;
  113. };
  114. }
  115. /*!
  116. @brief a class to store JSON values
  117. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  118. in @ref object_t)
  119. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  120. in @ref array_t)
  121. @tparam StringType type for JSON strings and object keys (`std::string` by
  122. default; will be used in @ref string_t)
  123. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  124. in @ref boolean_t)
  125. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  126. default; will be used in @ref number_integer_t)
  127. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  128. `uint64_t` by default; will be used in @ref number_unsigned_t)
  129. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  130. default; will be used in @ref number_float_t)
  131. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  132. default)
  133. @requirement The class satisfies the following concept requirements:
  134. - Basic
  135. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  136. JSON values can be default constructed. The result will be a JSON null value.
  137. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  138. A JSON value can be constructed from an rvalue argument.
  139. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  140. A JSON value can be copy-constructed from an lvalue expression.
  141. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  142. A JSON value van be assigned from an rvalue argument.
  143. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  144. A JSON value can be copy-assigned from an lvalue expression.
  145. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  146. JSON values can be destructed.
  147. - Layout
  148. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  149. JSON values have
  150. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  151. All non-static data members are private and standard layout types, the class
  152. has no virtual functions or (virtual) base classes.
  153. - Library-wide
  154. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  155. JSON values can be compared with `==`, see @ref
  156. operator==(const_reference,const_reference).
  157. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  158. JSON values can be compared with `<`, see @ref
  159. operator<(const_reference,const_reference).
  160. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  161. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  162. other compatible types, using unqualified function call @ref swap().
  163. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  164. JSON values can be compared against `std::nullptr_t` objects which are used
  165. to model the `null` value.
  166. - Container
  167. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  168. JSON values can be used like STL containers and provide iterator access.
  169. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  170. JSON values can be used like STL containers and provide reverse iterator
  171. access.
  172. @invariant The member variables @a m_value and @a m_type have the following
  173. relationship:
  174. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  175. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  176. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  177. The invariants are checked by member function assert_invariant().
  178. @internal
  179. @note ObjectType trick from http://stackoverflow.com/a/9860911
  180. @endinternal
  181. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  182. Format](http://rfc7159.net/rfc7159)
  183. @since version 1.0.0
  184. @nosubgrouping
  185. */
  186. template <
  187. template<typename U, typename V, typename... Args> class ObjectType = std::map,
  188. template<typename U, typename... Args> class ArrayType = std::vector,
  189. class StringType = std::string,
  190. class BooleanType = bool,
  191. class NumberIntegerType = std::int64_t,
  192. class NumberUnsignedType = std::uint64_t,
  193. class NumberFloatType = double,
  194. template<typename U> class AllocatorType = std::allocator
  195. >
  196. class basic_json
  197. {
  198. private:
  199. /// workaround type for MSVC
  200. using basic_json_t = basic_json<ObjectType, ArrayType, StringType,
  201. BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType,
  202. AllocatorType>;
  203. public:
  204. // forward declarations
  205. template<typename U> class iter_impl;
  206. template<typename Base> class json_reverse_iterator;
  207. class json_pointer;
  208. /////////////////////
  209. // container types //
  210. /////////////////////
  211. /// @name container types
  212. /// The canonic container types to use @ref basic_json like any other STL
  213. /// container.
  214. /// @{
  215. /// the type of elements in a basic_json container
  216. using value_type = basic_json;
  217. /// the type of an element reference
  218. using reference = value_type&;
  219. /// the type of an element const reference
  220. using const_reference = const value_type&;
  221. /// a type to represent differences between iterators
  222. using difference_type = std::ptrdiff_t;
  223. /// a type to represent container sizes
  224. using size_type = std::size_t;
  225. /// the allocator type
  226. using allocator_type = AllocatorType<basic_json>;
  227. /// the type of an element pointer
  228. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  229. /// the type of an element const pointer
  230. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  231. /// an iterator for a basic_json container
  232. using iterator = iter_impl<basic_json>;
  233. /// a const iterator for a basic_json container
  234. using const_iterator = iter_impl<const basic_json>;
  235. /// a reverse iterator for a basic_json container
  236. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  237. /// a const reverse iterator for a basic_json container
  238. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  239. /// @}
  240. /*!
  241. @brief returns the allocator associated with the container
  242. */
  243. static allocator_type get_allocator()
  244. {
  245. return allocator_type();
  246. }
  247. ///////////////////////////
  248. // JSON value data types //
  249. ///////////////////////////
  250. /// @name JSON value data types
  251. /// The data types to store a JSON value. These types are derived from
  252. /// the template arguments passed to class @ref basic_json.
  253. /// @{
  254. /*!
  255. @brief a type for an object
  256. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  257. > An object is an unordered collection of zero or more name/value pairs,
  258. > where a name is a string and a value is a string, number, boolean, null,
  259. > object, or array.
  260. To store objects in C++, a type is defined by the template parameters
  261. described below.
  262. @tparam ObjectType the container to store objects (e.g., `std::map` or
  263. `std::unordered_map`)
  264. @tparam StringType the type of the keys or names (e.g., `std::string`).
  265. The comparison function `std::less<StringType>` is used to order elements
  266. inside the container.
  267. @tparam AllocatorType the allocator to use for objects (e.g.,
  268. `std::allocator`)
  269. #### Default type
  270. With the default values for @a ObjectType (`std::map`), @a StringType
  271. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  272. value for @a object_t is:
  273. @code {.cpp}
  274. std::map<
  275. std::string, // key_type
  276. basic_json, // value_type
  277. std::less<std::string>, // key_compare
  278. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  279. >
  280. @endcode
  281. #### Behavior
  282. The choice of @a object_t influences the behavior of the JSON class. With
  283. the default type, objects have the following behavior:
  284. - When all names are unique, objects will be interoperable in the sense
  285. that all software implementations receiving that object will agree on
  286. the name-value mappings.
  287. - When the names within an object are not unique, later stored name/value
  288. pairs overwrite previously stored name/value pairs, leaving the used
  289. names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
  290. be treated as equal and both stored as `{"key": 1}`.
  291. - Internally, name/value pairs are stored in lexicographical order of the
  292. names. Objects will also be serialized (see @ref dump) in this order.
  293. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  294. and serialized as `{"a": 2, "b": 1}`.
  295. - When comparing objects, the order of the name/value pairs is irrelevant.
  296. This makes objects interoperable in the sense that they will not be
  297. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  298. `{"a": 2, "b": 1}` will be treated as equal.
  299. #### Limits
  300. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  301. > An implementation may set limits on the maximum depth of nesting.
  302. In this class, the object's limit of nesting is not constraint explicitly.
  303. However, a maximum depth of nesting may be introduced by the compiler or
  304. runtime environment. A theoretical limit can be queried by calling the
  305. @ref max_size function of a JSON object.
  306. #### Storage
  307. Objects are stored as pointers in a @ref basic_json type. That is, for any
  308. access to object values, a pointer of type `object_t*` must be
  309. dereferenced.
  310. @sa @ref array_t -- type for an array value
  311. @since version 1.0.0
  312. @note The order name/value pairs are added to the object is *not*
  313. preserved by the library. Therefore, iterating an object may return
  314. name/value pairs in a different order than they were originally stored. In
  315. fact, keys will be traversed in alphabetical order as `std::map` with
  316. `std::less` is used by default. Please note this behavior conforms to [RFC
  317. 7159](http://rfc7159.net/rfc7159), because any order implements the
  318. specified "unordered" nature of JSON objects.
  319. */
  320. using object_t = ObjectType<StringType,
  321. basic_json,
  322. std::less<StringType>,
  323. AllocatorType<std::pair<const StringType,
  324. basic_json>>>;
  325. /*!
  326. @brief a type for an array
  327. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  328. > An array is an ordered sequence of zero or more values.
  329. To store objects in C++, a type is defined by the template parameters
  330. explained below.
  331. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  332. `std::list`)
  333. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  334. #### Default type
  335. With the default values for @a ArrayType (`std::vector`) and @a
  336. AllocatorType (`std::allocator`), the default value for @a array_t is:
  337. @code {.cpp}
  338. std::vector<
  339. basic_json, // value_type
  340. std::allocator<basic_json> // allocator_type
  341. >
  342. @endcode
  343. #### Limits
  344. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  345. > An implementation may set limits on the maximum depth of nesting.
  346. In this class, the array's limit of nesting is not constraint explicitly.
  347. However, a maximum depth of nesting may be introduced by the compiler or
  348. runtime environment. A theoretical limit can be queried by calling the
  349. @ref max_size function of a JSON array.
  350. #### Storage
  351. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  352. access to array values, a pointer of type `array_t*` must be dereferenced.
  353. @sa @ref object_t -- type for an object value
  354. @since version 1.0.0
  355. */
  356. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  357. /*!
  358. @brief a type for a string
  359. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  360. > A string is a sequence of zero or more Unicode characters.
  361. To store objects in C++, a type is defined by the template parameter
  362. described below. Unicode values are split by the JSON class into
  363. byte-sized characters during deserialization.
  364. @tparam StringType the container to store strings (e.g., `std::string`).
  365. Note this container is used for keys/names in objects, see @ref object_t.
  366. #### Default type
  367. With the default values for @a StringType (`std::string`), the default
  368. value for @a string_t is:
  369. @code {.cpp}
  370. std::string
  371. @endcode
  372. #### String comparison
  373. [RFC 7159](http://rfc7159.net/rfc7159) states:
  374. > Software implementations are typically required to test names of object
  375. > members for equality. Implementations that transform the textual
  376. > representation into sequences of Unicode code units and then perform the
  377. > comparison numerically, code unit by code unit, are interoperable in the
  378. > sense that implementations will agree in all cases on equality or
  379. > inequality of two strings. For example, implementations that compare
  380. > strings with escaped characters unconverted may incorrectly find that
  381. > `"a\\b"` and `"a\u005Cb"` are not equal.
  382. This implementation is interoperable as it does compare strings code unit
  383. by code unit.
  384. #### Storage
  385. String values are stored as pointers in a @ref basic_json type. That is,
  386. for any access to string values, a pointer of type `string_t*` must be
  387. dereferenced.
  388. @since version 1.0.0
  389. */
  390. using string_t = StringType;
  391. /*!
  392. @brief a type for a boolean
  393. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  394. type which differentiates the two literals `true` and `false`.
  395. To store objects in C++, a type is defined by the template parameter @a
  396. BooleanType which chooses the type to use.
  397. #### Default type
  398. With the default values for @a BooleanType (`bool`), the default value for
  399. @a boolean_t is:
  400. @code {.cpp}
  401. bool
  402. @endcode
  403. #### Storage
  404. Boolean values are stored directly inside a @ref basic_json type.
  405. @since version 1.0.0
  406. */
  407. using boolean_t = BooleanType;
  408. /*!
  409. @brief a type for a number (integer)
  410. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  411. > The representation of numbers is similar to that used in most
  412. > programming languages. A number is represented in base 10 using decimal
  413. > digits. It contains an integer component that may be prefixed with an
  414. > optional minus sign, which may be followed by a fraction part and/or an
  415. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  416. > cannot be represented in the grammar below (such as Infinity and NaN)
  417. > are not permitted.
  418. This description includes both integer and floating-point numbers.
  419. However, C++ allows more precise storage if it is known whether the number
  420. is a signed integer, an unsigned integer or a floating-point number.
  421. Therefore, three different types, @ref number_integer_t, @ref
  422. number_unsigned_t and @ref number_float_t are used.
  423. To store integer numbers in C++, a type is defined by the template
  424. parameter @a NumberIntegerType which chooses the type to use.
  425. #### Default type
  426. With the default values for @a NumberIntegerType (`int64_t`), the default
  427. value for @a number_integer_t is:
  428. @code {.cpp}
  429. int64_t
  430. @endcode
  431. #### Default behavior
  432. - The restrictions about leading zeros is not enforced in C++. Instead,
  433. leading zeros in integer literals lead to an interpretation as octal
  434. number. Internally, the value will be stored as decimal number. For
  435. instance, the C++ integer literal `010` will be serialized to `8`.
  436. During deserialization, leading zeros yield an error.
  437. - Not-a-number (NaN) values will be serialized to `null`.
  438. #### Limits
  439. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  440. > An implementation may set limits on the range and precision of numbers.
  441. When the default type is used, the maximal integer number that can be
  442. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  443. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  444. that are out of range will yield over/underflow when used in a
  445. constructor. During deserialization, too large or small integer numbers
  446. will be automatically be stored as @ref number_unsigned_t or @ref
  447. number_float_t.
  448. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  449. > Note that when such software is used, numbers that are integers and are
  450. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  451. > that implementations will agree exactly on their numeric values.
  452. As this range is a subrange of the exactly supported range [INT64_MIN,
  453. INT64_MAX], this class's integer type is interoperable.
  454. #### Storage
  455. Integer number values are stored directly inside a @ref basic_json type.
  456. @sa @ref number_float_t -- type for number values (floating-point)
  457. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  458. @since version 1.0.0
  459. */
  460. using number_integer_t = NumberIntegerType;
  461. /*!
  462. @brief a type for a number (unsigned)
  463. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  464. > The representation of numbers is similar to that used in most
  465. > programming languages. A number is represented in base 10 using decimal
  466. > digits. It contains an integer component that may be prefixed with an
  467. > optional minus sign, which may be followed by a fraction part and/or an
  468. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  469. > cannot be represented in the grammar below (such as Infinity and NaN)
  470. > are not permitted.
  471. This description includes both integer and floating-point numbers.
  472. However, C++ allows more precise storage if it is known whether the number
  473. is a signed integer, an unsigned integer or a floating-point number.
  474. Therefore, three different types, @ref number_integer_t, @ref
  475. number_unsigned_t and @ref number_float_t are used.
  476. To store unsigned integer numbers in C++, a type is defined by the
  477. template parameter @a NumberUnsignedType which chooses the type to use.
  478. #### Default type
  479. With the default values for @a NumberUnsignedType (`uint64_t`), the
  480. default value for @a number_unsigned_t is:
  481. @code {.cpp}
  482. uint64_t
  483. @endcode
  484. #### Default behavior
  485. - The restrictions about leading zeros is not enforced in C++. Instead,
  486. leading zeros in integer literals lead to an interpretation as octal
  487. number. Internally, the value will be stored as decimal number. For
  488. instance, the C++ integer literal `010` will be serialized to `8`.
  489. During deserialization, leading zeros yield an error.
  490. - Not-a-number (NaN) values will be serialized to `null`.
  491. #### Limits
  492. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  493. > An implementation may set limits on the range and precision of numbers.
  494. When the default type is used, the maximal integer number that can be
  495. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  496. number that can be stored is `0`. Integer numbers that are out of range
  497. will yield over/underflow when used in a constructor. During
  498. deserialization, too large or small integer numbers will be automatically
  499. be stored as @ref number_integer_t or @ref number_float_t.
  500. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  501. > Note that when such software is used, numbers that are integers and are
  502. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  503. > that implementations will agree exactly on their numeric values.
  504. As this range is a subrange (when considered in conjunction with the
  505. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  506. this class's integer type is interoperable.
  507. #### Storage
  508. Integer number values are stored directly inside a @ref basic_json type.
  509. @sa @ref number_float_t -- type for number values (floating-point)
  510. @sa @ref number_integer_t -- type for number values (integer)
  511. @since version 2.0.0
  512. */
  513. using number_unsigned_t = NumberUnsignedType;
  514. /*!
  515. @brief a type for a number (floating-point)
  516. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  517. > The representation of numbers is similar to that used in most
  518. > programming languages. A number is represented in base 10 using decimal
  519. > digits. It contains an integer component that may be prefixed with an
  520. > optional minus sign, which may be followed by a fraction part and/or an
  521. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  522. > cannot be represented in the grammar below (such as Infinity and NaN)
  523. > are not permitted.
  524. This description includes both integer and floating-point numbers.
  525. However, C++ allows more precise storage if it is known whether the number
  526. is a signed integer, an unsigned integer or a floating-point number.
  527. Therefore, three different types, @ref number_integer_t, @ref
  528. number_unsigned_t and @ref number_float_t are used.
  529. To store floating-point numbers in C++, a type is defined by the template
  530. parameter @a NumberFloatType which chooses the type to use.
  531. #### Default type
  532. With the default values for @a NumberFloatType (`double`), the default
  533. value for @a number_float_t is:
  534. @code {.cpp}
  535. double
  536. @endcode
  537. #### Default behavior
  538. - The restrictions about leading zeros is not enforced in C++. Instead,
  539. leading zeros in floating-point literals will be ignored. Internally,
  540. the value will be stored as decimal number. For instance, the C++
  541. floating-point literal `01.2` will be serialized to `1.2`. During
  542. deserialization, leading zeros yield an error.
  543. - Not-a-number (NaN) values will be serialized to `null`.
  544. #### Limits
  545. [RFC 7159](http://rfc7159.net/rfc7159) states:
  546. > This specification allows implementations to set limits on the range and
  547. > precision of numbers accepted. Since software that implements IEEE
  548. > 754-2008 binary64 (double precision) numbers is generally available and
  549. > widely used, good interoperability can be achieved by implementations
  550. > that expect no more precision or range than these provide, in the sense
  551. > that implementations will approximate JSON numbers within the expected
  552. > precision.
  553. This implementation does exactly follow this approach, as it uses double
  554. precision floating-point numbers. Note values smaller than
  555. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  556. will be stored as NaN internally and be serialized to `null`.
  557. #### Storage
  558. Floating-point number values are stored directly inside a @ref basic_json
  559. type.
  560. @sa @ref number_integer_t -- type for number values (integer)
  561. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  562. @since version 1.0.0
  563. */
  564. using number_float_t = NumberFloatType;
  565. /// @}
  566. ///////////////////////////
  567. // JSON type enumeration //
  568. ///////////////////////////
  569. /*!
  570. @brief the JSON type enumeration
  571. This enumeration collects the different JSON types. It is internally used
  572. to distinguish the stored values, and the functions @ref is_null(), @ref
  573. is_object(), @ref is_array(), @ref is_string(), @ref is_boolean(), @ref
  574. is_number() (with @ref is_number_integer(), @ref is_number_unsigned(), and
  575. @ref is_number_float()), @ref is_discarded(), @ref is_primitive(), and
  576. @ref is_structured() rely on it.
  577. @note There are three enumeration entries (number_integer,
  578. number_unsigned, and number_float), because the library distinguishes
  579. these three types for numbers: @ref number_unsigned_t is used for unsigned
  580. integers, @ref number_integer_t is used for signed integers, and @ref
  581. number_float_t is used for floating-point numbers or to approximate
  582. integers which do not fit in the limits of their respective type.
  583. @sa @ref basic_json(const value_t value_type) -- create a JSON value with
  584. the default value for a given type
  585. @since version 1.0.0
  586. */
  587. enum class value_t : uint8_t
  588. {
  589. null, ///< null value
  590. object, ///< object (unordered set of name/value pairs)
  591. array, ///< array (ordered collection of values)
  592. string, ///< string value
  593. boolean, ///< boolean value
  594. number_integer, ///< number value (signed integer)
  595. number_unsigned, ///< number value (unsigned integer)
  596. number_float, ///< number value (floating-point)
  597. discarded ///< discarded by the the parser callback function
  598. };
  599. private:
  600. /// helper for exception-safe object creation
  601. template<typename T, typename... Args>
  602. static T* create(Args&& ... args)
  603. {
  604. AllocatorType<T> alloc;
  605. auto deleter = [&](T * object)
  606. {
  607. alloc.deallocate(object, 1);
  608. };
  609. std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
  610. alloc.construct(object.get(), std::forward<Args>(args)...);
  611. assert(object.get() != nullptr);
  612. return object.release();
  613. }
  614. ////////////////////////
  615. // JSON value storage //
  616. ////////////////////////
  617. /*!
  618. @brief a JSON value
  619. The actual storage for a JSON value of the @ref basic_json class. This
  620. union combines the different storage types for the JSON value types
  621. defined in @ref value_t.
  622. JSON type | value_t type | used type
  623. --------- | --------------- | ------------------------
  624. object | object | pointer to @ref object_t
  625. array | array | pointer to @ref array_t
  626. string | string | pointer to @ref string_t
  627. boolean | boolean | @ref boolean_t
  628. number | number_integer | @ref number_integer_t
  629. number | number_unsigned | @ref number_unsigned_t
  630. number | number_float | @ref number_float_t
  631. null | null | *no value is stored*
  632. @note Variable-length types (objects, arrays, and strings) are stored as
  633. pointers. The size of the union should not exceed 64 bits if the default
  634. value types are used.
  635. @since version 1.0.0
  636. */
  637. union json_value
  638. {
  639. /// object (stored with pointer to save storage)
  640. object_t* object;
  641. /// array (stored with pointer to save storage)
  642. array_t* array;
  643. /// string (stored with pointer to save storage)
  644. string_t* string;
  645. /// boolean
  646. boolean_t boolean;
  647. /// number (integer)
  648. number_integer_t number_integer;
  649. /// number (unsigned integer)
  650. number_unsigned_t number_unsigned;
  651. /// number (floating-point)
  652. number_float_t number_float;
  653. /// default constructor (for null values)
  654. json_value() = default;
  655. /// constructor for booleans
  656. json_value(boolean_t v) noexcept : boolean(v) {}
  657. /// constructor for numbers (integer)
  658. json_value(number_integer_t v) noexcept : number_integer(v) {}
  659. /// constructor for numbers (unsigned)
  660. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  661. /// constructor for numbers (floating-point)
  662. json_value(number_float_t v) noexcept : number_float(v) {}
  663. /// constructor for empty values of a given type
  664. json_value(value_t t)
  665. {
  666. switch (t)
  667. {
  668. case value_t::object:
  669. {
  670. object = create<object_t>();
  671. break;
  672. }
  673. case value_t::array:
  674. {
  675. array = create<array_t>();
  676. break;
  677. }
  678. case value_t::string:
  679. {
  680. string = create<string_t>("");
  681. break;
  682. }
  683. case value_t::boolean:
  684. {
  685. boolean = boolean_t(false);
  686. break;
  687. }
  688. case value_t::number_integer:
  689. {
  690. number_integer = number_integer_t(0);
  691. break;
  692. }
  693. case value_t::number_unsigned:
  694. {
  695. number_unsigned = number_unsigned_t(0);
  696. break;
  697. }
  698. case value_t::number_float:
  699. {
  700. number_float = number_float_t(0.0);
  701. break;
  702. }
  703. case value_t::null:
  704. {
  705. break;
  706. }
  707. default:
  708. {
  709. if (t == value_t::null)
  710. {
  711. throw std::domain_error("961c151d2e87f2686a955a9be24d316f1362bf21 2.0.10"); // LCOV_EXCL_LINE
  712. }
  713. break;
  714. }
  715. }
  716. }
  717. /// constructor for strings
  718. json_value(const string_t& value)
  719. {
  720. string = create<string_t>(value);
  721. }
  722. /// constructor for objects
  723. json_value(const object_t& value)
  724. {
  725. object = create<object_t>(value);
  726. }
  727. /// constructor for arrays
  728. json_value(const array_t& value)
  729. {
  730. array = create<array_t>(value);
  731. }
  732. };
  733. /*!
  734. @brief checks the class invariants
  735. This function asserts the class invariants. It needs to be called at the
  736. end of every constructor to make sure that created objects respect the
  737. invariant. Furthermore, it has to be called each time the type of a JSON
  738. value is changed, because the invariant expresses a relationship between
  739. @a m_type and @a m_value.
  740. */
  741. void assert_invariant() const
  742. {
  743. assert(m_type != value_t::object or m_value.object != nullptr);
  744. assert(m_type != value_t::array or m_value.array != nullptr);
  745. assert(m_type != value_t::string or m_value.string != nullptr);
  746. }
  747. public:
  748. //////////////////////////
  749. // JSON parser callback //
  750. //////////////////////////
  751. /*!
  752. @brief JSON callback events
  753. This enumeration lists the parser events that can trigger calling a
  754. callback function of type @ref parser_callback_t during parsing.
  755. @image html callback_events.png "Example when certain parse events are triggered"
  756. @since version 1.0.0
  757. */
  758. enum class parse_event_t : uint8_t
  759. {
  760. /// the parser read `{` and started to process a JSON object
  761. object_start,
  762. /// the parser read `}` and finished processing a JSON object
  763. object_end,
  764. /// the parser read `[` and started to process a JSON array
  765. array_start,
  766. /// the parser read `]` and finished processing a JSON array
  767. array_end,
  768. /// the parser read a key of a value in an object
  769. key,
  770. /// the parser finished reading a JSON value
  771. value
  772. };
  773. /*!
  774. @brief per-element parser callback type
  775. With a parser callback function, the result of parsing a JSON text can be
  776. influenced. When passed to @ref parse(std::istream&, const
  777. parser_callback_t) or @ref parse(const CharT, const parser_callback_t),
  778. it is called on certain events (passed as @ref parse_event_t via parameter
  779. @a event) with a set recursion depth @a depth and context JSON value
  780. @a parsed. The return value of the callback function is a boolean
  781. indicating whether the element that emitted the callback shall be kept or
  782. not.
  783. We distinguish six scenarios (determined by the event type) in which the
  784. callback function can be called. The following table describes the values
  785. of the parameters @a depth, @a event, and @a parsed.
  786. parameter @a event | description | parameter @a depth | parameter @a parsed
  787. ------------------ | ----------- | ------------------ | -------------------
  788. 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
  789. 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
  790. 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
  791. 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
  792. 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
  793. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  794. @image html callback_events.png "Example when certain parse events are triggered"
  795. Discarding a value (i.e., returning `false`) has different effects
  796. depending on the context in which function was called:
  797. - Discarded values in structured types are skipped. That is, the parser
  798. will behave as if the discarded value was never read.
  799. - In case a value outside a structured type is skipped, it is replaced
  800. with `null`. This case happens if the top-level element is skipped.
  801. @param[in] depth the depth of the recursion during parsing
  802. @param[in] event an event of type parse_event_t indicating the context in
  803. the callback function has been called
  804. @param[in,out] parsed the current intermediate parse result; note that
  805. writing to this value has no effect for parse_event_t::key events
  806. @return Whether the JSON value which called the function during parsing
  807. should be kept (`true`) or not (`false`). In the latter case, it is either
  808. skipped completely or replaced by an empty discarded object.
  809. @sa @ref parse(std::istream&, parser_callback_t) or
  810. @ref parse(const CharT, const parser_callback_t) for examples
  811. @since version 1.0.0
  812. */
  813. using parser_callback_t = std::function<bool(int depth,
  814. parse_event_t event,
  815. basic_json& parsed)>;
  816. //////////////////
  817. // constructors //
  818. //////////////////
  819. /// @name constructors and destructors
  820. /// Constructors of class @ref basic_json, copy/move constructor, copy
  821. /// assignment, static functions creating objects, and the destructor.
  822. /// @{
  823. /*!
  824. @brief create an empty value with a given type
  825. Create an empty JSON value with a given type. The value will be default
  826. initialized with an empty value which depends on the type:
  827. Value type | initial value
  828. ----------- | -------------
  829. null | `null`
  830. boolean | `false`
  831. string | `""`
  832. number | `0`
  833. object | `{}`
  834. array | `[]`
  835. @param[in] value_type the type of the value to create
  836. @complexity Constant.
  837. @throw std::bad_alloc if allocation for object, array, or string value
  838. fails
  839. @liveexample{The following code shows the constructor for different @ref
  840. value_t values,basic_json__value_t}
  841. @sa @ref basic_json(std::nullptr_t) -- create a `null` value
  842. @sa @ref basic_json(boolean_t value) -- create a boolean value
  843. @sa @ref basic_json(const string_t&) -- create a string value
  844. @sa @ref basic_json(const object_t&) -- create a object value
  845. @sa @ref basic_json(const array_t&) -- create a array value
  846. @sa @ref basic_json(const number_float_t) -- create a number
  847. (floating-point) value
  848. @sa @ref basic_json(const number_integer_t) -- create a number (integer)
  849. value
  850. @sa @ref basic_json(const number_unsigned_t) -- create a number (unsigned)
  851. value
  852. @since version 1.0.0
  853. */
  854. basic_json(const value_t value_type)
  855. : m_type(value_type), m_value(value_type)
  856. {
  857. assert_invariant();
  858. }
  859. /*!
  860. @brief create a null object
  861. Create a `null` JSON value. It either takes a null pointer as parameter
  862. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  863. The passed null pointer itself is not read -- it is only used to choose
  864. the right constructor.
  865. @complexity Constant.
  866. @exceptionsafety No-throw guarantee: this constructor never throws
  867. exceptions.
  868. @liveexample{The following code shows the constructor with and without a
  869. null pointer parameter.,basic_json__nullptr_t}
  870. @since version 1.0.0
  871. */
  872. basic_json(std::nullptr_t = nullptr) noexcept
  873. : basic_json(value_t::null)
  874. {
  875. assert_invariant();
  876. }
  877. /*!
  878. @brief create an object (explicit)
  879. Create an object JSON value with a given content.
  880. @param[in] val a value for the object
  881. @complexity Linear in the size of the passed @a val.
  882. @throw std::bad_alloc if allocation for object value fails
  883. @liveexample{The following code shows the constructor with an @ref
  884. object_t parameter.,basic_json__object_t}
  885. @sa @ref basic_json(const CompatibleObjectType&) -- create an object value
  886. from a compatible STL container
  887. @since version 1.0.0
  888. */
  889. basic_json(const object_t& val)
  890. : m_type(value_t::object), m_value(val)
  891. {
  892. assert_invariant();
  893. }
  894. /*!
  895. @brief create an object (implicit)
  896. Create an object JSON value with a given content. This constructor allows
  897. any type @a CompatibleObjectType that can be used to construct values of
  898. type @ref object_t.
  899. @tparam CompatibleObjectType An object type whose `key_type` and
  900. `value_type` is compatible to @ref object_t. Examples include `std::map`,
  901. `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with
  902. a `key_type` of `std::string`, and a `value_type` from which a @ref
  903. basic_json value can be constructed.
  904. @param[in] val a value for the object
  905. @complexity Linear in the size of the passed @a val.
  906. @throw std::bad_alloc if allocation for object value fails
  907. @liveexample{The following code shows the constructor with several
  908. compatible object type parameters.,basic_json__CompatibleObjectType}
  909. @sa @ref basic_json(const object_t&) -- create an object value
  910. @since version 1.0.0
  911. */
  912. template<class CompatibleObjectType, typename std::enable_if<
  913. std::is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value and
  914. std::is_constructible<basic_json, typename CompatibleObjectType::mapped_type>::value, int>::type = 0>
  915. basic_json(const CompatibleObjectType& val)
  916. : m_type(value_t::object)
  917. {
  918. using std::begin;
  919. using std::end;
  920. m_value.object = create<object_t>(begin(val), end(val));
  921. assert_invariant();
  922. }
  923. /*!
  924. @brief create an array (explicit)
  925. Create an array JSON value with a given content.
  926. @param[in] val a value for the array
  927. @complexity Linear in the size of the passed @a val.
  928. @throw std::bad_alloc if allocation for array value fails
  929. @liveexample{The following code shows the constructor with an @ref array_t
  930. parameter.,basic_json__array_t}
  931. @sa @ref basic_json(const CompatibleArrayType&) -- create an array value
  932. from a compatible STL containers
  933. @since version 1.0.0
  934. */
  935. basic_json(const array_t& val)
  936. : m_type(value_t::array), m_value(val)
  937. {
  938. assert_invariant();
  939. }
  940. /*!
  941. @brief create an array (implicit)
  942. Create an array JSON value with a given content. This constructor allows
  943. any type @a CompatibleArrayType that can be used to construct values of
  944. type @ref array_t.
  945. @tparam CompatibleArrayType An object type whose `value_type` is
  946. compatible to @ref array_t. Examples include `std::vector`, `std::deque`,
  947. `std::list`, `std::forward_list`, `std::array`, `std::set`,
  948. `std::unordered_set`, `std::multiset`, and `unordered_multiset` with a
  949. `value_type` from which a @ref basic_json value can be constructed.
  950. @param[in] val a value for the array
  951. @complexity Linear in the size of the passed @a val.
  952. @throw std::bad_alloc if allocation for array value fails
  953. @liveexample{The following code shows the constructor with several
  954. compatible array type parameters.,basic_json__CompatibleArrayType}
  955. @sa @ref basic_json(const array_t&) -- create an array value
  956. @since version 1.0.0
  957. */
  958. template<class CompatibleArrayType, typename std::enable_if<
  959. not std::is_same<CompatibleArrayType, typename basic_json_t::iterator>::value and
  960. not std::is_same<CompatibleArrayType, typename basic_json_t::const_iterator>::value and
  961. not std::is_same<CompatibleArrayType, typename basic_json_t::reverse_iterator>::value and
  962. not std::is_same<CompatibleArrayType, typename basic_json_t::const_reverse_iterator>::value and
  963. not std::is_same<CompatibleArrayType, typename array_t::iterator>::value and
  964. not std::is_same<CompatibleArrayType, typename array_t::const_iterator>::value and
  965. std::is_constructible<basic_json, typename CompatibleArrayType::value_type>::value, int>::type = 0>
  966. basic_json(const CompatibleArrayType& val)
  967. : m_type(value_t::array)
  968. {
  969. using std::begin;
  970. using std::end;
  971. m_value.array = create<array_t>(begin(val), end(val));
  972. assert_invariant();
  973. }
  974. /*!
  975. @brief create a string (explicit)
  976. Create an string JSON value with a given content.
  977. @param[in] val a value for the string
  978. @complexity Linear in the size of the passed @a val.
  979. @throw std::bad_alloc if allocation for string value fails
  980. @liveexample{The following code shows the constructor with an @ref
  981. string_t parameter.,basic_json__string_t}
  982. @sa @ref basic_json(const typename string_t::value_type*) -- create a
  983. string value from a character pointer
  984. @sa @ref basic_json(const CompatibleStringType&) -- create a string value
  985. from a compatible string container
  986. @since version 1.0.0
  987. */
  988. basic_json(const string_t& val)
  989. : m_type(value_t::string), m_value(val)
  990. {
  991. assert_invariant();
  992. }
  993. /*!
  994. @brief create a string (explicit)
  995. Create a string JSON value with a given content.
  996. @param[in] val a literal value for the string
  997. @complexity Linear in the size of the passed @a val.
  998. @throw std::bad_alloc if allocation for string value fails
  999. @liveexample{The following code shows the constructor with string literal
  1000. parameter.,basic_json__string_t_value_type}
  1001. @sa @ref basic_json(const string_t&) -- create a string value
  1002. @sa @ref basic_json(const CompatibleStringType&) -- create a string value
  1003. from a compatible string container
  1004. @since version 1.0.0
  1005. */
  1006. basic_json(const typename string_t::value_type* val)
  1007. : basic_json(string_t(val))
  1008. {
  1009. assert_invariant();
  1010. }
  1011. /*!
  1012. @brief create a string (implicit)
  1013. Create a string JSON value with a given content.
  1014. @param[in] val a value for the string
  1015. @tparam CompatibleStringType an string type which is compatible to @ref
  1016. string_t, for instance `std::string`.
  1017. @complexity Linear in the size of the passed @a val.
  1018. @throw std::bad_alloc if allocation for string value fails
  1019. @liveexample{The following code shows the construction of a string value
  1020. from a compatible type.,basic_json__CompatibleStringType}
  1021. @sa @ref basic_json(const string_t&) -- create a string value
  1022. @sa @ref basic_json(const typename string_t::value_type*) -- create a
  1023. string value from a character pointer
  1024. @since version 1.0.0
  1025. */
  1026. template<class CompatibleStringType, typename std::enable_if<
  1027. std::is_constructible<string_t, CompatibleStringType>::value, int>::type = 0>
  1028. basic_json(const CompatibleStringType& val)
  1029. : basic_json(string_t(val))
  1030. {
  1031. assert_invariant();
  1032. }
  1033. /*!
  1034. @brief create a boolean (explicit)
  1035. Creates a JSON boolean type from a given value.
  1036. @param[in] val a boolean value to store
  1037. @complexity Constant.
  1038. @liveexample{The example below demonstrates boolean
  1039. values.,basic_json__boolean_t}
  1040. @since version 1.0.0
  1041. */
  1042. basic_json(boolean_t val) noexcept
  1043. : m_type(value_t::boolean), m_value(val)
  1044. {
  1045. assert_invariant();
  1046. }
  1047. /*!
  1048. @brief create an integer number (explicit)
  1049. Create an integer number JSON value with a given content.
  1050. @tparam T A helper type to remove this function via SFINAE in case @ref
  1051. number_integer_t is the same as `int`. In this case, this constructor
  1052. would have the same signature as @ref basic_json(const int value). Note
  1053. the helper type @a T is not visible in this constructor's interface.
  1054. @param[in] val an integer to create a JSON number from
  1055. @complexity Constant.
  1056. @liveexample{The example below shows the construction of an integer
  1057. number value.,basic_json__number_integer_t}
  1058. @sa @ref basic_json(const int) -- create a number value (integer)
  1059. @sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
  1060. value (integer) from a compatible number type
  1061. @since version 1.0.0
  1062. */
  1063. template<typename T, typename std::enable_if<
  1064. not (std::is_same<T, int>::value) and
  1065. std::is_same<T, number_integer_t>::value, int>::type = 0>
  1066. basic_json(const number_integer_t val) noexcept
  1067. : m_type(value_t::number_integer), m_value(val)
  1068. {
  1069. assert_invariant();
  1070. }
  1071. /*!
  1072. @brief create an integer number from an enum type (explicit)
  1073. Create an integer number JSON value with a given content.
  1074. @param[in] val an integer to create a JSON number from
  1075. @note This constructor allows to pass enums directly to a constructor. As
  1076. C++ has no way of specifying the type of an anonymous enum explicitly, we
  1077. can only rely on the fact that such values implicitly convert to int. As
  1078. int may already be the same type of number_integer_t, we may need to
  1079. switch off the constructor @ref basic_json(const number_integer_t).
  1080. @complexity Constant.
  1081. @liveexample{The example below shows the construction of an integer
  1082. number value from an anonymous enum.,basic_json__const_int}
  1083. @sa @ref basic_json(const number_integer_t) -- create a number value
  1084. (integer)
  1085. @sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
  1086. value (integer) from a compatible number type
  1087. @since version 1.0.0
  1088. */
  1089. basic_json(const int val) noexcept
  1090. : m_type(value_t::number_integer),
  1091. m_value(static_cast<number_integer_t>(val))
  1092. {
  1093. assert_invariant();
  1094. }
  1095. /*!
  1096. @brief create an integer number (implicit)
  1097. Create an integer number JSON value with a given content. This constructor
  1098. allows any type @a CompatibleNumberIntegerType that can be used to
  1099. construct values of type @ref number_integer_t.
  1100. @tparam CompatibleNumberIntegerType An integer type which is compatible to
  1101. @ref number_integer_t. Examples include the types `int`, `int32_t`,
  1102. `long`, and `short`.
  1103. @param[in] val an integer to create a JSON number from
  1104. @complexity Constant.
  1105. @liveexample{The example below shows the construction of several integer
  1106. number values from compatible
  1107. types.,basic_json__CompatibleIntegerNumberType}
  1108. @sa @ref basic_json(const number_integer_t) -- create a number value
  1109. (integer)
  1110. @sa @ref basic_json(const int) -- create a number value (integer)
  1111. @since version 1.0.0
  1112. */
  1113. template<typename CompatibleNumberIntegerType, typename std::enable_if<
  1114. std::is_constructible<number_integer_t, CompatibleNumberIntegerType>::value and
  1115. std::numeric_limits<CompatibleNumberIntegerType>::is_integer and
  1116. std::numeric_limits<CompatibleNumberIntegerType>::is_signed,
  1117. CompatibleNumberIntegerType>::type = 0>
  1118. basic_json(const CompatibleNumberIntegerType val) noexcept
  1119. : m_type(value_t::number_integer),
  1120. m_value(static_cast<number_integer_t>(val))
  1121. {
  1122. assert_invariant();
  1123. }
  1124. /*!
  1125. @brief create an unsigned integer number (explicit)
  1126. Create an unsigned integer number JSON value with a given content.
  1127. @tparam T helper type to compare number_unsigned_t and unsigned int (not
  1128. visible in) the interface.
  1129. @param[in] val an integer to create a JSON number from
  1130. @complexity Constant.
  1131. @sa @ref basic_json(const CompatibleNumberUnsignedType) -- create a number
  1132. value (unsigned integer) from a compatible number type
  1133. @since version 2.0.0
  1134. */
  1135. template<typename T, typename std::enable_if<
  1136. not (std::is_same<T, int>::value) and
  1137. std::is_same<T, number_unsigned_t>::value, int>::type = 0>
  1138. basic_json(const number_unsigned_t val) noexcept
  1139. : m_type(value_t::number_unsigned), m_value(val)
  1140. {
  1141. assert_invariant();
  1142. }
  1143. /*!
  1144. @brief create an unsigned number (implicit)
  1145. Create an unsigned number JSON value with a given content. This
  1146. constructor allows any type @a CompatibleNumberUnsignedType that can be
  1147. used to construct values of type @ref number_unsigned_t.
  1148. @tparam CompatibleNumberUnsignedType An integer type which is compatible
  1149. to @ref number_unsigned_t. Examples may include the types `unsigned int`,
  1150. `uint32_t`, or `unsigned short`.
  1151. @param[in] val an unsigned integer to create a JSON number from
  1152. @complexity Constant.
  1153. @sa @ref basic_json(const number_unsigned_t) -- create a number value
  1154. (unsigned)
  1155. @since version 2.0.0
  1156. */
  1157. template<typename CompatibleNumberUnsignedType, typename std::enable_if <
  1158. std::is_constructible<number_unsigned_t, CompatibleNumberUnsignedType>::value and
  1159. std::numeric_limits<CompatibleNumberUnsignedType>::is_integer and
  1160. not std::numeric_limits<CompatibleNumberUnsignedType>::is_signed,
  1161. CompatibleNumberUnsignedType>::type = 0>
  1162. basic_json(const CompatibleNumberUnsignedType val) noexcept
  1163. : m_type(value_t::number_unsigned),
  1164. m_value(static_cast<number_unsigned_t>(val))
  1165. {
  1166. assert_invariant();
  1167. }
  1168. /*!
  1169. @brief create a floating-point number (explicit)
  1170. Create a floating-point number JSON value with a given content.
  1171. @param[in] val a floating-point value to create a JSON number from
  1172. @note [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), section 6
  1173. disallows NaN values:
  1174. > Numeric values that cannot be represented in the grammar below (such as
  1175. > Infinity and NaN) are not permitted.
  1176. In case the parameter @a val is not a number, a JSON null value is created
  1177. instead.
  1178. @complexity Constant.
  1179. @liveexample{The following example creates several floating-point
  1180. values.,basic_json__number_float_t}
  1181. @sa @ref basic_json(const CompatibleNumberFloatType) -- create a number
  1182. value (floating-point) from a compatible number type
  1183. @since version 1.0.0
  1184. */
  1185. basic_json(const number_float_t val) noexcept
  1186. : m_type(value_t::number_float), m_value(val)
  1187. {
  1188. // replace infinity and NAN by null
  1189. if (not std::isfinite(val))
  1190. {
  1191. m_type = value_t::null;
  1192. m_value = json_value();
  1193. }
  1194. assert_invariant();
  1195. }
  1196. /*!
  1197. @brief create an floating-point number (implicit)
  1198. Create an floating-point number JSON value with a given content. This
  1199. constructor allows any type @a CompatibleNumberFloatType that can be used
  1200. to construct values of type @ref number_float_t.
  1201. @tparam CompatibleNumberFloatType A floating-point type which is
  1202. compatible to @ref number_float_t. Examples may include the types `float`
  1203. or `double`.
  1204. @param[in] val a floating-point to create a JSON number from
  1205. @note [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), section 6
  1206. disallows NaN values:
  1207. > Numeric values that cannot be represented in the grammar below (such as
  1208. > Infinity and NaN) are not permitted.
  1209. In case the parameter @a val is not a number, a JSON null value is
  1210. created instead.
  1211. @complexity Constant.
  1212. @liveexample{The example below shows the construction of several
  1213. floating-point number values from compatible
  1214. types.,basic_json__CompatibleNumberFloatType}
  1215. @sa @ref basic_json(const number_float_t) -- create a number value
  1216. (floating-point)
  1217. @since version 1.0.0
  1218. */
  1219. template<typename CompatibleNumberFloatType, typename = typename std::enable_if<
  1220. std::is_constructible<number_float_t, CompatibleNumberFloatType>::value and
  1221. std::is_floating_point<CompatibleNumberFloatType>::value>::type>
  1222. basic_json(const CompatibleNumberFloatType val) noexcept
  1223. : basic_json(number_float_t(val))
  1224. {
  1225. assert_invariant();
  1226. }
  1227. /*!
  1228. @brief create a container (array or object) from an initializer list
  1229. Creates a JSON value of type array or object from the passed initializer
  1230. list @a init. In case @a type_deduction is `true` (default), the type of
  1231. the JSON value to be created is deducted from the initializer list @a init
  1232. according to the following rules:
  1233. 1. If the list is empty, an empty JSON object value `{}` is created.
  1234. 2. If the list consists of pairs whose first element is a string, a JSON
  1235. object value is created where the first elements of the pairs are
  1236. treated as keys and the second elements are as values.
  1237. 3. In all other cases, an array is created.
  1238. The rules aim to create the best fit between a C++ initializer list and
  1239. JSON values. The rationale is as follows:
  1240. 1. The empty initializer list is written as `{}` which is exactly an empty
  1241. JSON object.
  1242. 2. C++ has now way of describing mapped types other than to list a list of
  1243. pairs. As JSON requires that keys must be of type string, rule 2 is the
  1244. weakest constraint one can pose on initializer lists to interpret them
  1245. as an object.
  1246. 3. In all other cases, the initializer list could not be interpreted as
  1247. JSON object type, so interpreting it as JSON array type is safe.
  1248. With the rules described above, the following JSON values cannot be
  1249. expressed by an initializer list:
  1250. - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
  1251. with an empty initializer list in this case
  1252. - arrays whose elements satisfy rule 2: use @ref
  1253. array(std::initializer_list<basic_json>) with the same initializer list
  1254. in this case
  1255. @note When used without parentheses around an empty initializer list, @ref
  1256. basic_json() is called instead of this function, yielding the JSON null
  1257. value.
  1258. @param[in] init initializer list with JSON values
  1259. @param[in] type_deduction internal parameter; when set to `true`, the type
  1260. of the JSON value is deducted from the initializer list @a init; when set
  1261. to `false`, the type provided via @a manual_type is forced. This mode is
  1262. used by the functions @ref array(std::initializer_list<basic_json>) and
  1263. @ref object(std::initializer_list<basic_json>).
  1264. @param[in] manual_type internal parameter; when @a type_deduction is set
  1265. to `false`, the created JSON value will use the provided type (only @ref
  1266. value_t::array and @ref value_t::object are valid); when @a type_deduction
  1267. is set to `true`, this parameter has no effect
  1268. @throw std::domain_error if @a type_deduction is `false`, @a manual_type
  1269. is `value_t::object`, but @a init contains an element which is not a pair
  1270. whose first element is a string; example: `"cannot create object from
  1271. initializer list"`
  1272. @complexity Linear in the size of the initializer list @a init.
  1273. @liveexample{The example below shows how JSON values are created from
  1274. initializer lists.,basic_json__list_init_t}
  1275. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  1276. value from an initializer list
  1277. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  1278. value from an initializer list
  1279. @since version 1.0.0
  1280. */
  1281. basic_json(std::initializer_list<basic_json> init,
  1282. bool type_deduction = true,
  1283. value_t manual_type = value_t::array)
  1284. {
  1285. // check if each element is an array with two elements whose first
  1286. // element is a string
  1287. bool is_an_object = std::all_of(init.begin(), init.end(),
  1288. [](const basic_json & element)
  1289. {
  1290. return element.is_array() and element.size() == 2 and element[0].is_string();
  1291. });
  1292. // adjust type if type deduction is not wanted
  1293. if (not type_deduction)
  1294. {
  1295. // if array is wanted, do not create an object though possible
  1296. if (manual_type == value_t::array)
  1297. {
  1298. is_an_object = false;
  1299. }
  1300. // if object is wanted but impossible, throw an exception
  1301. if (manual_type == value_t::object and not is_an_object)
  1302. {
  1303. throw std::domain_error("cannot create object from initializer list");
  1304. }
  1305. }
  1306. if (is_an_object)
  1307. {
  1308. // the initializer list is a list of pairs -> create object
  1309. m_type = value_t::object;
  1310. m_value = value_t::object;
  1311. std::for_each(init.begin(), init.end(), [this](const basic_json & element)
  1312. {
  1313. m_value.object->emplace(*(element[0].m_value.string), element[1]);
  1314. });
  1315. }
  1316. else
  1317. {
  1318. // the initializer list describes an array -> create array
  1319. m_type = value_t::array;
  1320. m_value.array = create<array_t>(init);
  1321. }
  1322. assert_invariant();
  1323. }
  1324. /*!
  1325. @brief explicitly create an array from an initializer list
  1326. Creates a JSON array value from a given initializer list. That is, given a
  1327. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  1328. initializer list is empty, the empty array `[]` is created.
  1329. @note This function is only needed to express two edge cases that cannot
  1330. be realized with the initializer list constructor (@ref
  1331. basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
  1332. are:
  1333. 1. creating an array whose elements are all pairs whose first element is a
  1334. string -- in this case, the initializer list constructor would create an
  1335. object, taking the first elements as keys
  1336. 2. creating an empty array -- passing the empty initializer list to the
  1337. initializer list constructor yields an empty object
  1338. @param[in] init initializer list with JSON values to create an array from
  1339. (optional)
  1340. @return JSON array value
  1341. @complexity Linear in the size of @a init.
  1342. @liveexample{The following code shows an example for the `array`
  1343. function.,array}
  1344. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  1345. create a JSON value from an initializer list
  1346. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  1347. value from an initializer list
  1348. @since version 1.0.0
  1349. */
  1350. static basic_json array(std::initializer_list<basic_json> init =
  1351. std::initializer_list<basic_json>())
  1352. {
  1353. return basic_json(init, false, value_t::array);
  1354. }
  1355. /*!
  1356. @brief explicitly create an object from an initializer list
  1357. Creates a JSON object value from a given initializer list. The initializer
  1358. lists elements must be pairs, and their first elements must be strings. If
  1359. the initializer list is empty, the empty object `{}` is created.
  1360. @note This function is only added for symmetry reasons. In contrast to the
  1361. related function @ref array(std::initializer_list<basic_json>), there are
  1362. no cases which can only be expressed by this function. That is, any
  1363. initializer list @a init can also be passed to the initializer list
  1364. constructor @ref basic_json(std::initializer_list<basic_json>, bool,
  1365. value_t).
  1366. @param[in] init initializer list to create an object from (optional)
  1367. @return JSON object value
  1368. @throw std::domain_error if @a init is not a pair whose first elements are
  1369. strings; thrown by
  1370. @ref basic_json(std::initializer_list<basic_json>, bool, value_t)
  1371. @complexity Linear in the size of @a init.
  1372. @liveexample{The following code shows an example for the `object`
  1373. function.,object}
  1374. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  1375. create a JSON value from an initializer list
  1376. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  1377. value from an initializer list
  1378. @since version 1.0.0
  1379. */
  1380. static basic_json object(std::initializer_list<basic_json> init =
  1381. std::initializer_list<basic_json>())
  1382. {
  1383. return basic_json(init, false, value_t::object);
  1384. }
  1385. /*!
  1386. @brief construct an array with count copies of given value
  1387. Constructs a JSON array value by creating @a cnt copies of a passed value.
  1388. In case @a cnt is `0`, an empty array is created. As postcondition,
  1389. `std::distance(begin(),end()) == cnt` holds.
  1390. @param[in] cnt the number of JSON copies of @a val to create
  1391. @param[in] val the JSON value to copy
  1392. @complexity Linear in @a cnt.
  1393. @liveexample{The following code shows examples for the @ref
  1394. basic_json(size_type\, const basic_json&)
  1395. constructor.,basic_json__size_type_basic_json}
  1396. @since version 1.0.0
  1397. */
  1398. basic_json(size_type cnt, const basic_json& val)
  1399. : m_type(value_t::array)
  1400. {
  1401. m_value.array = create<array_t>(cnt, val);
  1402. assert_invariant();
  1403. }
  1404. /*!
  1405. @brief construct a JSON container given an iterator range
  1406. Constructs the JSON value with the contents of the range `[first, last)`.
  1407. The semantics depends on the different types a JSON value can have:
  1408. - In case of primitive types (number, boolean, or string), @a first must
  1409. be `begin()` and @a last must be `end()`. In this case, the value is
  1410. copied. Otherwise, std::out_of_range is thrown.
  1411. - In case of structured types (array, object), the constructor behaves as
  1412. similar versions for `std::vector`.
  1413. - In case of a null type, std::domain_error is thrown.
  1414. @tparam InputIT an input iterator type (@ref iterator or @ref
  1415. const_iterator)
  1416. @param[in] first begin of the range to copy from (included)
  1417. @param[in] last end of the range to copy from (excluded)
  1418. @pre Iterators @a first and @a last must be initialized. **This
  1419. precondition is enforced with an assertion.**
  1420. @throw std::domain_error if iterators are not compatible; that is, do not
  1421. belong to the same JSON value; example: `"iterators are not compatible"`
  1422. @throw std::out_of_range if iterators are for a primitive type (number,
  1423. boolean, or string) where an out of range error can be detected easily;
  1424. example: `"iterators out of range"`
  1425. @throw std::bad_alloc if allocation for object, array, or string fails
  1426. @throw std::domain_error if called with a null value; example: `"cannot
  1427. use construct with iterators from null"`
  1428. @complexity Linear in distance between @a first and @a last.
  1429. @liveexample{The example below shows several ways to create JSON values by
  1430. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  1431. @since version 1.0.0
  1432. */
  1433. template<class InputIT, typename std::enable_if<
  1434. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  1435. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  1436. basic_json(InputIT first, InputIT last)
  1437. {
  1438. assert(first.m_object != nullptr);
  1439. assert(last.m_object != nullptr);
  1440. // make sure iterator fits the current value
  1441. if (first.m_object != last.m_object)
  1442. {
  1443. throw std::domain_error("iterators are not compatible");
  1444. }
  1445. // copy type from first iterator
  1446. m_type = first.m_object->m_type;
  1447. // check if iterator range is complete for primitive values
  1448. switch (m_type)
  1449. {
  1450. case value_t::boolean:
  1451. case value_t::number_float:
  1452. case value_t::number_integer:
  1453. case value_t::number_unsigned:
  1454. case value_t::string:
  1455. {
  1456. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  1457. {
  1458. throw std::out_of_range("iterators out of range");
  1459. }
  1460. break;
  1461. }
  1462. default:
  1463. {
  1464. break;
  1465. }
  1466. }
  1467. switch (m_type)
  1468. {
  1469. case value_t::number_integer:
  1470. {
  1471. m_value.number_integer = first.m_object->m_value.number_integer;
  1472. break;
  1473. }
  1474. case value_t::number_unsigned:
  1475. {
  1476. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  1477. break;
  1478. }
  1479. case value_t::number_float:
  1480. {
  1481. m_value.number_float = first.m_object->m_value.number_float;
  1482. break;
  1483. }
  1484. case value_t::boolean:
  1485. {
  1486. m_value.boolean = first.m_object->m_value.boolean;
  1487. break;
  1488. }
  1489. case value_t::string:
  1490. {
  1491. m_value = *first.m_object->m_value.string;
  1492. break;
  1493. }
  1494. case value_t::object:
  1495. {
  1496. m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator);
  1497. break;
  1498. }
  1499. case value_t::array:
  1500. {
  1501. m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator);
  1502. break;
  1503. }
  1504. default:
  1505. {
  1506. throw std::domain_error("cannot use construct with iterators from " + first.m_object->type_name());
  1507. }
  1508. }
  1509. assert_invariant();
  1510. }
  1511. /*!
  1512. @brief construct a JSON value given an input stream
  1513. @param[in,out] i stream to read a serialized JSON value from
  1514. @param[in] cb a parser callback function of type @ref parser_callback_t
  1515. which is used to control the deserialization by filtering unwanted values
  1516. (optional)
  1517. @complexity Linear in the length of the input. The parser is a predictive
  1518. LL(1) parser. The complexity can be higher if the parser callback function
  1519. @a cb has a super-linear complexity.
  1520. @note A UTF-8 byte order mark is silently ignored.
  1521. @deprecated This constructor is deprecated and will be removed in version
  1522. 3.0.0 to unify the interface of the library. Deserialization will be
  1523. done by stream operators or by calling one of the `parse` functions,
  1524. e.g. @ref parse(std::istream&, const parser_callback_t). That is, calls
  1525. like `json j(i);` for an input stream @a i need to be replaced by
  1526. `json j = json::parse(i);`. See the example below.
  1527. @liveexample{The example below demonstrates constructing a JSON value from
  1528. a `std::stringstream` with and without callback
  1529. function.,basic_json__istream}
  1530. @since version 2.0.0, deprecated in version 2.0.3, to be removed in
  1531. version 3.0.0
  1532. */
  1533. JSON_DEPRECATED
  1534. explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr)
  1535. {
  1536. *this = parser(i, cb).parse();
  1537. assert_invariant();
  1538. }
  1539. ///////////////////////////////////////
  1540. // other constructors and destructor //
  1541. ///////////////////////////////////////
  1542. /*!
  1543. @brief copy constructor
  1544. Creates a copy of a given JSON value.
  1545. @param[in] other the JSON value to copy
  1546. @complexity Linear in the size of @a other.
  1547. @requirement This function helps `basic_json` satisfying the
  1548. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  1549. requirements:
  1550. - The complexity is linear.
  1551. - As postcondition, it holds: `other == basic_json(other)`.
  1552. @throw std::bad_alloc if allocation for object, array, or string fails.
  1553. @liveexample{The following code shows an example for the copy
  1554. constructor.,basic_json__basic_json}
  1555. @since version 1.0.0
  1556. */
  1557. basic_json(const basic_json& other)
  1558. : m_type(other.m_type)
  1559. {
  1560. // check of passed value is valid
  1561. other.assert_invariant();
  1562. switch (m_type)
  1563. {
  1564. case value_t::object:
  1565. {
  1566. m_value = *other.m_value.object;
  1567. break;
  1568. }
  1569. case value_t::array:
  1570. {
  1571. m_value = *other.m_value.array;
  1572. break;
  1573. }
  1574. case value_t::string:
  1575. {
  1576. m_value = *other.m_value.string;
  1577. break;
  1578. }
  1579. case value_t::boolean:
  1580. {
  1581. m_value = other.m_value.boolean;
  1582. break;
  1583. }
  1584. case value_t::number_integer:
  1585. {
  1586. m_value = other.m_value.number_integer;
  1587. break;
  1588. }
  1589. case value_t::number_unsigned:
  1590. {
  1591. m_value = other.m_value.number_unsigned;
  1592. break;
  1593. }
  1594. case value_t::number_float:
  1595. {
  1596. m_value = other.m_value.number_float;
  1597. break;
  1598. }
  1599. default:
  1600. {
  1601. break;
  1602. }
  1603. }
  1604. assert_invariant();
  1605. }
  1606. /*!
  1607. @brief move constructor
  1608. Move constructor. Constructs a JSON value with the contents of the given
  1609. value @a other using move semantics. It "steals" the resources from @a
  1610. other and leaves it as JSON null value.
  1611. @param[in,out] other value to move to this object
  1612. @post @a other is a JSON null value
  1613. @complexity Constant.
  1614. @liveexample{The code below shows the move constructor explicitly called
  1615. via std::move.,basic_json__moveconstructor}
  1616. @since version 1.0.0
  1617. */
  1618. basic_json(basic_json&& other) noexcept
  1619. : m_type(std::move(other.m_type)),
  1620. m_value(std::move(other.m_value))
  1621. {
  1622. // check that passed value is valid
  1623. other.assert_invariant();
  1624. // invalidate payload
  1625. other.m_type = value_t::null;
  1626. other.m_value = {};
  1627. assert_invariant();
  1628. }
  1629. /*!
  1630. @brief copy assignment
  1631. Copy assignment operator. Copies a JSON value via the "copy and swap"
  1632. strategy: It is expressed in terms of the copy constructor, destructor,
  1633. and the swap() member function.
  1634. @param[in] other value to copy from
  1635. @complexity Linear.
  1636. @requirement This function helps `basic_json` satisfying the
  1637. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  1638. requirements:
  1639. - The complexity is linear.
  1640. @liveexample{The code below shows and example for the copy assignment. It
  1641. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  1642. copy of `a` (which is the null value after the swap) is
  1643. destroyed.,basic_json__copyassignment}
  1644. @since version 1.0.0
  1645. */
  1646. reference& operator=(basic_json other) noexcept (
  1647. std::is_nothrow_move_constructible<value_t>::value and
  1648. std::is_nothrow_move_assignable<value_t>::value and
  1649. std::is_nothrow_move_constructible<json_value>::value and
  1650. std::is_nothrow_move_assignable<json_value>::value
  1651. )
  1652. {
  1653. // check that passed value is valid
  1654. other.assert_invariant();
  1655. using std::swap;
  1656. swap(m_type, other.m_type);
  1657. swap(m_value, other.m_value);
  1658. assert_invariant();
  1659. return *this;
  1660. }
  1661. /*!
  1662. @brief destructor
  1663. Destroys the JSON value and frees all allocated memory.
  1664. @complexity Linear.
  1665. @requirement This function helps `basic_json` satisfying the
  1666. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  1667. requirements:
  1668. - The complexity is linear.
  1669. - All stored elements are destroyed and all memory is freed.
  1670. @since version 1.0.0
  1671. */
  1672. ~basic_json()
  1673. {
  1674. assert_invariant();
  1675. switch (m_type)
  1676. {
  1677. case value_t::object:
  1678. {
  1679. AllocatorType<object_t> alloc;
  1680. alloc.destroy(m_value.object);
  1681. alloc.deallocate(m_value.object, 1);
  1682. break;
  1683. }
  1684. case value_t::array:
  1685. {
  1686. AllocatorType<array_t> alloc;
  1687. alloc.destroy(m_value.array);
  1688. alloc.deallocate(m_value.array, 1);
  1689. break;
  1690. }
  1691. case value_t::string:
  1692. {
  1693. AllocatorType<string_t> alloc;
  1694. alloc.destroy(m_value.string);
  1695. alloc.deallocate(m_value.string, 1);
  1696. break;
  1697. }
  1698. default:
  1699. {
  1700. // all other types need no specific destructor
  1701. break;
  1702. }
  1703. }
  1704. }
  1705. /// @}
  1706. public:
  1707. ///////////////////////
  1708. // object inspection //
  1709. ///////////////////////
  1710. /// @name object inspection
  1711. /// Functions to inspect the type of a JSON value.
  1712. /// @{
  1713. /*!
  1714. @brief serialization
  1715. Serialization function for JSON values. The function tries to mimic
  1716. Python's `json.dumps()` function, and currently supports its @a indent
  1717. parameter.
  1718. @param[in] indent If indent is nonnegative, then array elements and object
  1719. members will be pretty-printed with that indent level. An indent level of
  1720. `0` will only insert newlines. `-1` (the default) selects the most compact
  1721. representation.
  1722. @return string containing the serialization of the JSON value
  1723. @complexity Linear.
  1724. @liveexample{The following example shows the effect of different @a indent
  1725. parameters to the result of the serialization.,dump}
  1726. @see https://docs.python.org/2/library/json.html#json.dump
  1727. @since version 1.0.0
  1728. */
  1729. string_t dump(const int indent = -1) const
  1730. {
  1731. std::stringstream ss;
  1732. // fix locale problems
  1733. ss.imbue(std::locale::classic());
  1734. // 6, 15 or 16 digits of precision allows round-trip IEEE 754
  1735. // string->float->string, string->double->string or string->long
  1736. // double->string; to be safe, we read this value from
  1737. // std::numeric_limits<number_float_t>::digits10
  1738. ss.precision(std::numeric_limits<double>::digits10);
  1739. if (indent >= 0)
  1740. {
  1741. dump(ss, true, static_cast<unsigned int>(indent));
  1742. }
  1743. else
  1744. {
  1745. dump(ss, false, 0);
  1746. }
  1747. return ss.str();
  1748. }
  1749. /*!
  1750. @brief return the type of the JSON value (explicit)
  1751. Return the type of the JSON value as a value from the @ref value_t
  1752. enumeration.
  1753. @return the type of the JSON value
  1754. @complexity Constant.
  1755. @exceptionsafety No-throw guarantee: this member function never throws
  1756. exceptions.
  1757. @liveexample{The following code exemplifies `type()` for all JSON
  1758. types.,type}
  1759. @since version 1.0.0
  1760. */
  1761. constexpr value_t type() const noexcept
  1762. {
  1763. return m_type;
  1764. }
  1765. /*!
  1766. @brief return whether type is primitive
  1767. This function returns true iff the JSON type is primitive (string, number,
  1768. boolean, or null).
  1769. @return `true` if type is primitive (string, number, boolean, or null),
  1770. `false` otherwise.
  1771. @complexity Constant.
  1772. @exceptionsafety No-throw guarantee: this member function never throws
  1773. exceptions.
  1774. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  1775. types.,is_primitive}
  1776. @sa @ref is_structured() -- returns whether JSON value is structured
  1777. @sa @ref is_null() -- returns whether JSON value is `null`
  1778. @sa @ref is_string() -- returns whether JSON value is a string
  1779. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  1780. @sa @ref is_number() -- returns whether JSON value is a number
  1781. @since version 1.0.0
  1782. */
  1783. constexpr bool is_primitive() const noexcept
  1784. {
  1785. return is_null() or is_string() or is_boolean() or is_number();
  1786. }
  1787. /*!
  1788. @brief return whether type is structured
  1789. This function returns true iff the JSON type is structured (array or
  1790. object).
  1791. @return `true` if type is structured (array or object), `false` otherwise.
  1792. @complexity Constant.
  1793. @exceptionsafety No-throw guarantee: this member function never throws
  1794. exceptions.
  1795. @liveexample{The following code exemplifies `is_structured()` for all JSON
  1796. types.,is_structured}
  1797. @sa @ref is_primitive() -- returns whether value is primitive
  1798. @sa @ref is_array() -- returns whether value is an array
  1799. @sa @ref is_object() -- returns whether value is an object
  1800. @since version 1.0.0
  1801. */
  1802. constexpr bool is_structured() const noexcept
  1803. {
  1804. return is_array() or is_object();
  1805. }
  1806. /*!
  1807. @brief return whether value is null
  1808. This function returns true iff the JSON value is null.
  1809. @return `true` if type is null, `false` otherwise.
  1810. @complexity Constant.
  1811. @exceptionsafety No-throw guarantee: this member function never throws
  1812. exceptions.
  1813. @liveexample{The following code exemplifies `is_null()` for all JSON
  1814. types.,is_null}
  1815. @since version 1.0.0
  1816. */
  1817. constexpr bool is_null() const noexcept
  1818. {
  1819. return m_type == value_t::null;
  1820. }
  1821. /*!
  1822. @brief return whether value is a boolean
  1823. This function returns true iff the JSON value is a boolean.
  1824. @return `true` if type is boolean, `false` otherwise.
  1825. @complexity Constant.
  1826. @exceptionsafety No-throw guarantee: this member function never throws
  1827. exceptions.
  1828. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  1829. types.,is_boolean}
  1830. @since version 1.0.0
  1831. */
  1832. constexpr bool is_boolean() const noexcept
  1833. {
  1834. return m_type == value_t::boolean;
  1835. }
  1836. /*!
  1837. @brief return whether value is a number
  1838. This function returns true iff the JSON value is a number. This includes
  1839. both integer and floating-point values.
  1840. @return `true` if type is number (regardless whether integer, unsigned
  1841. integer or floating-type), `false` otherwise.
  1842. @complexity Constant.
  1843. @exceptionsafety No-throw guarantee: this member function never throws
  1844. exceptions.
  1845. @liveexample{The following code exemplifies `is_number()` for all JSON
  1846. types.,is_number}
  1847. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  1848. integer number
  1849. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1850. number
  1851. @sa @ref is_number_float() -- check if value is a floating-point number
  1852. @since version 1.0.0
  1853. */
  1854. constexpr bool is_number() const noexcept
  1855. {
  1856. return is_number_integer() or is_number_float();
  1857. }
  1858. /*!
  1859. @brief return whether value is an integer number
  1860. This function returns true iff the JSON value is an integer or unsigned
  1861. integer number. This excludes floating-point values.
  1862. @return `true` if type is an integer or unsigned integer number, `false`
  1863. otherwise.
  1864. @complexity Constant.
  1865. @exceptionsafety No-throw guarantee: this member function never throws
  1866. exceptions.
  1867. @liveexample{The following code exemplifies `is_number_integer()` for all
  1868. JSON types.,is_number_integer}
  1869. @sa @ref is_number() -- check if value is a number
  1870. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1871. number
  1872. @sa @ref is_number_float() -- check if value is a floating-point number
  1873. @since version 1.0.0
  1874. */
  1875. constexpr bool is_number_integer() const noexcept
  1876. {
  1877. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  1878. }
  1879. /*!
  1880. @brief return whether value is an unsigned integer number
  1881. This function returns true iff the JSON value is an unsigned integer
  1882. number. This excludes floating-point and (signed) integer values.
  1883. @return `true` if type is an unsigned integer number, `false` otherwise.
  1884. @complexity Constant.
  1885. @exceptionsafety No-throw guarantee: this member function never throws
  1886. exceptions.
  1887. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  1888. JSON types.,is_number_unsigned}
  1889. @sa @ref is_number() -- check if value is a number
  1890. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  1891. integer number
  1892. @sa @ref is_number_float() -- check if value is a floating-point number
  1893. @since version 2.0.0
  1894. */
  1895. constexpr bool is_number_unsigned() const noexcept
  1896. {
  1897. return m_type == value_t::number_unsigned;
  1898. }
  1899. /*!
  1900. @brief return whether value is a floating-point number
  1901. This function returns true iff the JSON value is a floating-point number.
  1902. This excludes integer and unsigned integer values.
  1903. @return `true` if type is a floating-point number, `false` otherwise.
  1904. @complexity Constant.
  1905. @exceptionsafety No-throw guarantee: this member function never throws
  1906. exceptions.
  1907. @liveexample{The following code exemplifies `is_number_float()` for all
  1908. JSON types.,is_number_float}
  1909. @sa @ref is_number() -- check if value is number
  1910. @sa @ref is_number_integer() -- check if value is an integer number
  1911. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1912. number
  1913. @since version 1.0.0
  1914. */
  1915. constexpr bool is_number_float() const noexcept
  1916. {
  1917. return m_type == value_t::number_float;
  1918. }
  1919. /*!
  1920. @brief return whether value is an object
  1921. This function returns true iff the JSON value is an object.
  1922. @return `true` if type is object, `false` otherwise.
  1923. @complexity Constant.
  1924. @exceptionsafety No-throw guarantee: this member function never throws
  1925. exceptions.
  1926. @liveexample{The following code exemplifies `is_object()` for all JSON
  1927. types.,is_object}
  1928. @since version 1.0.0
  1929. */
  1930. constexpr bool is_object() const noexcept
  1931. {
  1932. return m_type == value_t::object;
  1933. }
  1934. /*!
  1935. @brief return whether value is an array
  1936. This function returns true iff the JSON value is an array.
  1937. @return `true` if type is array, `false` otherwise.
  1938. @complexity Constant.
  1939. @exceptionsafety No-throw guarantee: this member function never throws
  1940. exceptions.
  1941. @liveexample{The following code exemplifies `is_array()` for all JSON
  1942. types.,is_array}
  1943. @since version 1.0.0
  1944. */
  1945. constexpr bool is_array() const noexcept
  1946. {
  1947. return m_type == value_t::array;
  1948. }
  1949. /*!
  1950. @brief return whether value is a string
  1951. This function returns true iff the JSON value is a string.
  1952. @return `true` if type is string, `false` otherwise.
  1953. @complexity Constant.
  1954. @exceptionsafety No-throw guarantee: this member function never throws
  1955. exceptions.
  1956. @liveexample{The following code exemplifies `is_string()` for all JSON
  1957. types.,is_string}
  1958. @since version 1.0.0
  1959. */
  1960. constexpr bool is_string() const noexcept
  1961. {
  1962. return m_type == value_t::string;
  1963. }
  1964. /*!
  1965. @brief return whether value is discarded
  1966. This function returns true iff the JSON value was discarded during parsing
  1967. with a callback function (see @ref parser_callback_t).
  1968. @note This function will always be `false` for JSON values after parsing.
  1969. That is, discarded values can only occur during parsing, but will be
  1970. removed when inside a structured value or replaced by null in other cases.
  1971. @return `true` if type is discarded, `false` otherwise.
  1972. @complexity Constant.
  1973. @exceptionsafety No-throw guarantee: this member function never throws
  1974. exceptions.
  1975. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  1976. types.,is_discarded}
  1977. @since version 1.0.0
  1978. */
  1979. constexpr bool is_discarded() const noexcept
  1980. {
  1981. return m_type == value_t::discarded;
  1982. }
  1983. /*!
  1984. @brief return the type of the JSON value (implicit)
  1985. Implicitly return the type of the JSON value as a value from the @ref
  1986. value_t enumeration.
  1987. @return the type of the JSON value
  1988. @complexity Constant.
  1989. @exceptionsafety No-throw guarantee: this member function never throws
  1990. exceptions.
  1991. @liveexample{The following code exemplifies the @ref value_t operator for
  1992. all JSON types.,operator__value_t}
  1993. @since version 1.0.0
  1994. */
  1995. constexpr operator value_t() const noexcept
  1996. {
  1997. return m_type;
  1998. }
  1999. /// @}
  2000. private:
  2001. //////////////////
  2002. // value access //
  2003. //////////////////
  2004. /// get an object (explicit)
  2005. template<class T, typename std::enable_if<
  2006. std::is_convertible<typename object_t::key_type, typename T::key_type>::value and
  2007. std::is_convertible<basic_json_t, typename T::mapped_type>::value, int>::type = 0>
  2008. T get_impl(T*) const
  2009. {
  2010. if (is_object())
  2011. {
  2012. return T(m_value.object->begin(), m_value.object->end());
  2013. }
  2014. else
  2015. {
  2016. throw std::domain_error("type must be object, but is " + type_name());
  2017. }
  2018. }
  2019. /// get an object (explicit)
  2020. object_t get_impl(object_t*) const
  2021. {
  2022. if (is_object())
  2023. {
  2024. return *(m_value.object);
  2025. }
  2026. else
  2027. {
  2028. throw std::domain_error("type must be object, but is " + type_name());
  2029. }
  2030. }
  2031. /// get an array (explicit)
  2032. template<class T, typename std::enable_if<
  2033. std::is_convertible<basic_json_t, typename T::value_type>::value and
  2034. not std::is_same<basic_json_t, typename T::value_type>::value and
  2035. not std::is_arithmetic<T>::value and
  2036. not std::is_convertible<std::string, T>::value and
  2037. not has_mapped_type<T>::value, int>::type = 0>
  2038. T get_impl(T*) const
  2039. {
  2040. if (is_array())
  2041. {
  2042. T to_vector;
  2043. std::transform(m_value.array->begin(), m_value.array->end(),
  2044. std::inserter(to_vector, to_vector.end()), [](basic_json i)
  2045. {
  2046. return i.get<typename T::value_type>();
  2047. });
  2048. return to_vector;
  2049. }
  2050. else
  2051. {
  2052. throw std::domain_error("type must be array, but is " + type_name());
  2053. }
  2054. }
  2055. /// get an array (explicit)
  2056. template<class T, typename std::enable_if<
  2057. std::is_convertible<basic_json_t, T>::value and
  2058. not std::is_same<basic_json_t, T>::value, int>::type = 0>
  2059. std::vector<T> get_impl(std::vector<T>*) const
  2060. {
  2061. if (is_array())
  2062. {
  2063. std::vector<T> to_vector;
  2064. to_vector.reserve(m_value.array->size());
  2065. std::transform(m_value.array->begin(), m_value.array->end(),
  2066. std::inserter(to_vector, to_vector.end()), [](basic_json i)
  2067. {
  2068. return i.get<T>();
  2069. });
  2070. return to_vector;
  2071. }
  2072. else
  2073. {
  2074. throw std::domain_error("type must be array, but is " + type_name());
  2075. }
  2076. }
  2077. /// get an array (explicit)
  2078. template<class T, typename std::enable_if<
  2079. std::is_same<basic_json, typename T::value_type>::value and
  2080. not has_mapped_type<T>::value, int>::type = 0>
  2081. T get_impl(T*) const
  2082. {
  2083. if (is_array())
  2084. {
  2085. return T(m_value.array->begin(), m_value.array->end());
  2086. }
  2087. else
  2088. {
  2089. throw std::domain_error("type must be array, but is " + type_name());
  2090. }
  2091. }
  2092. /// get an array (explicit)
  2093. array_t get_impl(array_t*) const
  2094. {
  2095. if (is_array())
  2096. {
  2097. return *(m_value.array);
  2098. }
  2099. else
  2100. {
  2101. throw std::domain_error("type must be array, but is " + type_name());
  2102. }
  2103. }
  2104. /// get a string (explicit)
  2105. template<typename T, typename std::enable_if<
  2106. std::is_convertible<string_t, T>::value, int>::type = 0>
  2107. T get_impl(T*) const
  2108. {
  2109. if (is_string())
  2110. {
  2111. return *m_value.string;
  2112. }
  2113. else
  2114. {
  2115. throw std::domain_error("type must be string, but is " + type_name());
  2116. }
  2117. }
  2118. /// get a number (explicit)
  2119. template<typename T, typename std::enable_if<
  2120. std::is_arithmetic<T>::value, int>::type = 0>
  2121. T get_impl(T*) const
  2122. {
  2123. switch (m_type)
  2124. {
  2125. case value_t::number_integer:
  2126. {
  2127. return static_cast<T>(m_value.number_integer);
  2128. }
  2129. case value_t::number_unsigned:
  2130. {
  2131. return static_cast<T>(m_value.number_unsigned);
  2132. }
  2133. case value_t::number_float:
  2134. {
  2135. return static_cast<T>(m_value.number_float);
  2136. }
  2137. default:
  2138. {
  2139. throw std::domain_error("type must be number, but is " + type_name());
  2140. }
  2141. }
  2142. }
  2143. /// get a boolean (explicit)
  2144. constexpr boolean_t get_impl(boolean_t*) const
  2145. {
  2146. return is_boolean()
  2147. ? m_value.boolean
  2148. : throw std::domain_error("type must be boolean, but is " + type_name());
  2149. }
  2150. /// get a pointer to the value (object)
  2151. object_t* get_impl_ptr(object_t*) noexcept
  2152. {
  2153. return is_object() ? m_value.object : nullptr;
  2154. }
  2155. /// get a pointer to the value (object)
  2156. constexpr const object_t* get_impl_ptr(const object_t*) const noexcept
  2157. {
  2158. return is_object() ? m_value.object : nullptr;
  2159. }
  2160. /// get a pointer to the value (array)
  2161. array_t* get_impl_ptr(array_t*) noexcept
  2162. {
  2163. return is_array() ? m_value.array : nullptr;
  2164. }
  2165. /// get a pointer to the value (array)
  2166. constexpr const array_t* get_impl_ptr(const array_t*) const noexcept
  2167. {
  2168. return is_array() ? m_value.array : nullptr;
  2169. }
  2170. /// get a pointer to the value (string)
  2171. string_t* get_impl_ptr(string_t*) noexcept
  2172. {
  2173. return is_string() ? m_value.string : nullptr;
  2174. }
  2175. /// get a pointer to the value (string)
  2176. constexpr const string_t* get_impl_ptr(const string_t*) const noexcept
  2177. {
  2178. return is_string() ? m_value.string : nullptr;
  2179. }
  2180. /// get a pointer to the value (boolean)
  2181. boolean_t* get_impl_ptr(boolean_t*) noexcept
  2182. {
  2183. return is_boolean() ? &m_value.boolean : nullptr;
  2184. }
  2185. /// get a pointer to the value (boolean)
  2186. constexpr const boolean_t* get_impl_ptr(const boolean_t*) const noexcept
  2187. {
  2188. return is_boolean() ? &m_value.boolean : nullptr;
  2189. }
  2190. /// get a pointer to the value (integer number)
  2191. number_integer_t* get_impl_ptr(number_integer_t*) noexcept
  2192. {
  2193. return is_number_integer() ? &m_value.number_integer : nullptr;
  2194. }
  2195. /// get a pointer to the value (integer number)
  2196. constexpr const number_integer_t* get_impl_ptr(const number_integer_t*) const noexcept
  2197. {
  2198. return is_number_integer() ? &m_value.number_integer : nullptr;
  2199. }
  2200. /// get a pointer to the value (unsigned number)
  2201. number_unsigned_t* get_impl_ptr(number_unsigned_t*) noexcept
  2202. {
  2203. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2204. }
  2205. /// get a pointer to the value (unsigned number)
  2206. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t*) const noexcept
  2207. {
  2208. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2209. }
  2210. /// get a pointer to the value (floating-point number)
  2211. number_float_t* get_impl_ptr(number_float_t*) noexcept
  2212. {
  2213. return is_number_float() ? &m_value.number_float : nullptr;
  2214. }
  2215. /// get a pointer to the value (floating-point number)
  2216. constexpr const number_float_t* get_impl_ptr(const number_float_t*) const noexcept
  2217. {
  2218. return is_number_float() ? &m_value.number_float : nullptr;
  2219. }
  2220. /*!
  2221. @brief helper function to implement get_ref()
  2222. This funcion helps to implement get_ref() without code duplication for
  2223. const and non-const overloads
  2224. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  2225. @throw std::domain_error if ReferenceType does not match underlying value
  2226. type of the current JSON
  2227. */
  2228. template<typename ReferenceType, typename ThisType>
  2229. static ReferenceType get_ref_impl(ThisType& obj)
  2230. {
  2231. // helper type
  2232. using PointerType = typename std::add_pointer<ReferenceType>::type;
  2233. // delegate the call to get_ptr<>()
  2234. auto ptr = obj.template get_ptr<PointerType>();
  2235. if (ptr != nullptr)
  2236. {
  2237. return *ptr;
  2238. }
  2239. else
  2240. {
  2241. throw std::domain_error("incompatible ReferenceType for get_ref, actual type is " +
  2242. obj.type_name());
  2243. }
  2244. }
  2245. public:
  2246. /// @name value access
  2247. /// Direct access to the stored value of a JSON value.
  2248. /// @{
  2249. /*!
  2250. @brief get a value (explicit)
  2251. Explicit type conversion between the JSON value and a compatible value.
  2252. @tparam ValueType non-pointer type compatible to the JSON value, for
  2253. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  2254. `std::vector` types for JSON arrays
  2255. @return copy of the JSON value, converted to type @a ValueType
  2256. @throw std::domain_error in case passed type @a ValueType is incompatible
  2257. to JSON; example: `"type must be object, but is null"`
  2258. @complexity Linear in the size of the JSON value.
  2259. @liveexample{The example below shows several conversions from JSON values
  2260. to other types. There a few things to note: (1) Floating-point numbers can
  2261. be converted to integers\, (2) A JSON array can be converted to a standard
  2262. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2263. associative containers such as `std::unordered_map<std::string\,
  2264. json>`.,get__ValueType_const}
  2265. @internal
  2266. The idea of using a casted null pointer to choose the correct
  2267. implementation is from <http://stackoverflow.com/a/8315197/266378>.
  2268. @endinternal
  2269. @sa @ref operator ValueType() const for implicit conversion
  2270. @sa @ref get() for pointer-member access
  2271. @since version 1.0.0
  2272. */
  2273. template<typename ValueType, typename std::enable_if<
  2274. not std::is_pointer<ValueType>::value, int>::type = 0>
  2275. ValueType get() const
  2276. {
  2277. return get_impl(static_cast<ValueType*>(nullptr));
  2278. }
  2279. /*!
  2280. @brief get a pointer value (explicit)
  2281. Explicit pointer access to the internally stored JSON value. No copies are
  2282. made.
  2283. @warning The pointer becomes invalid if the underlying JSON object
  2284. changes.
  2285. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2286. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2287. @ref number_unsigned_t, or @ref number_float_t.
  2288. @return pointer to the internally stored JSON value if the requested
  2289. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2290. @complexity Constant.
  2291. @liveexample{The example below shows how pointers to internal values of a
  2292. JSON value can be requested. Note that no type conversions are made and a
  2293. `nullptr` is returned if the value and the requested pointer type does not
  2294. match.,get__PointerType}
  2295. @sa @ref get_ptr() for explicit pointer-member access
  2296. @since version 1.0.0
  2297. */
  2298. template<typename PointerType, typename std::enable_if<
  2299. std::is_pointer<PointerType>::value, int>::type = 0>
  2300. PointerType get() noexcept
  2301. {
  2302. // delegate the call to get_ptr
  2303. return get_ptr<PointerType>();
  2304. }
  2305. /*!
  2306. @brief get a pointer value (explicit)
  2307. @copydoc get()
  2308. */
  2309. template<typename PointerType, typename std::enable_if<
  2310. std::is_pointer<PointerType>::value, int>::type = 0>
  2311. constexpr const PointerType get() const noexcept
  2312. {
  2313. // delegate the call to get_ptr
  2314. return get_ptr<PointerType>();
  2315. }
  2316. /*!
  2317. @brief get a pointer value (implicit)
  2318. Implicit pointer access to the internally stored JSON value. No copies are
  2319. made.
  2320. @warning Writing data to the pointee of the result yields an undefined
  2321. state.
  2322. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2323. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2324. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  2325. assertion.
  2326. @return pointer to the internally stored JSON value if the requested
  2327. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2328. @complexity Constant.
  2329. @liveexample{The example below shows how pointers to internal values of a
  2330. JSON value can be requested. Note that no type conversions are made and a
  2331. `nullptr` is returned if the value and the requested pointer type does not
  2332. match.,get_ptr}
  2333. @since version 1.0.0
  2334. */
  2335. template<typename PointerType, typename std::enable_if<
  2336. std::is_pointer<PointerType>::value, int>::type = 0>
  2337. PointerType get_ptr() noexcept
  2338. {
  2339. // get the type of the PointerType (remove pointer and const)
  2340. using pointee_t = typename std::remove_const<typename
  2341. std::remove_pointer<typename
  2342. std::remove_const<PointerType>::type>::type>::type;
  2343. // make sure the type matches the allowed types
  2344. static_assert(
  2345. std::is_same<object_t, pointee_t>::value
  2346. or std::is_same<array_t, pointee_t>::value
  2347. or std::is_same<string_t, pointee_t>::value
  2348. or std::is_same<boolean_t, pointee_t>::value
  2349. or std::is_same<number_integer_t, pointee_t>::value
  2350. or std::is_same<number_unsigned_t, pointee_t>::value
  2351. or std::is_same<number_float_t, pointee_t>::value
  2352. , "incompatible pointer type");
  2353. // delegate the call to get_impl_ptr<>()
  2354. return get_impl_ptr(static_cast<PointerType>(nullptr));
  2355. }
  2356. /*!
  2357. @brief get a pointer value (implicit)
  2358. @copydoc get_ptr()
  2359. */
  2360. template<typename PointerType, typename std::enable_if<
  2361. std::is_pointer<PointerType>::value and
  2362. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  2363. constexpr const PointerType get_ptr() const noexcept
  2364. {
  2365. // get the type of the PointerType (remove pointer and const)
  2366. using pointee_t = typename std::remove_const<typename
  2367. std::remove_pointer<typename
  2368. std::remove_const<PointerType>::type>::type>::type;
  2369. // make sure the type matches the allowed types
  2370. static_assert(
  2371. std::is_same<object_t, pointee_t>::value
  2372. or std::is_same<array_t, pointee_t>::value
  2373. or std::is_same<string_t, pointee_t>::value
  2374. or std::is_same<boolean_t, pointee_t>::value
  2375. or std::is_same<number_integer_t, pointee_t>::value
  2376. or std::is_same<number_unsigned_t, pointee_t>::value
  2377. or std::is_same<number_float_t, pointee_t>::value
  2378. , "incompatible pointer type");
  2379. // delegate the call to get_impl_ptr<>() const
  2380. return get_impl_ptr(static_cast<const PointerType>(nullptr));
  2381. }
  2382. /*!
  2383. @brief get a reference value (implicit)
  2384. Implict reference access to the internally stored JSON value. No copies
  2385. are made.
  2386. @warning Writing data to the referee of the result yields an undefined
  2387. state.
  2388. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  2389. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  2390. @ref number_float_t. Enforced by static assertion.
  2391. @return reference to the internally stored JSON value if the requested
  2392. reference type @a ReferenceType fits to the JSON value; throws
  2393. std::domain_error otherwise
  2394. @throw std::domain_error in case passed type @a ReferenceType is
  2395. incompatible with the stored JSON value
  2396. @complexity Constant.
  2397. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  2398. @since version 1.1.0
  2399. */
  2400. template<typename ReferenceType, typename std::enable_if<
  2401. std::is_reference<ReferenceType>::value, int>::type = 0>
  2402. ReferenceType get_ref()
  2403. {
  2404. // delegate call to get_ref_impl
  2405. return get_ref_impl<ReferenceType>(*this);
  2406. }
  2407. /*!
  2408. @brief get a reference value (implicit)
  2409. @copydoc get_ref()
  2410. */
  2411. template<typename ReferenceType, typename std::enable_if<
  2412. std::is_reference<ReferenceType>::value and
  2413. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  2414. ReferenceType get_ref() const
  2415. {
  2416. // delegate call to get_ref_impl
  2417. return get_ref_impl<ReferenceType>(*this);
  2418. }
  2419. /*!
  2420. @brief get a value (implicit)
  2421. Implicit type conversion between the JSON value and a compatible value.
  2422. The call is realized by calling @ref get() const.
  2423. @tparam ValueType non-pointer type compatible to the JSON value, for
  2424. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  2425. `std::vector` types for JSON arrays. The character type of @ref string_t
  2426. as well as an initializer list of this type is excluded to avoid
  2427. ambiguities as these types implicitly convert to `std::string`.
  2428. @return copy of the JSON value, converted to type @a ValueType
  2429. @throw std::domain_error in case passed type @a ValueType is incompatible
  2430. to JSON, thrown by @ref get() const
  2431. @complexity Linear in the size of the JSON value.
  2432. @liveexample{The example below shows several conversions from JSON values
  2433. to other types. There a few things to note: (1) Floating-point numbers can
  2434. be converted to integers\, (2) A JSON array can be converted to a standard
  2435. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2436. associative containers such as `std::unordered_map<std::string\,
  2437. json>`.,operator__ValueType}
  2438. @since version 1.0.0
  2439. */
  2440. template < typename ValueType, typename std::enable_if <
  2441. not std::is_pointer<ValueType>::value and
  2442. not std::is_same<ValueType, typename string_t::value_type>::value
  2443. #ifndef _MSC_VER // Fix for issue #167 operator<< abiguity under VS2015
  2444. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  2445. #endif
  2446. , int >::type = 0 >
  2447. operator ValueType() const
  2448. {
  2449. // delegate the call to get<>() const
  2450. return get<ValueType>();
  2451. }
  2452. /// @}
  2453. ////////////////////
  2454. // element access //
  2455. ////////////////////
  2456. /// @name element access
  2457. /// Access to the JSON value.
  2458. /// @{
  2459. /*!
  2460. @brief access specified array element with bounds checking
  2461. Returns a reference to the element at specified location @a idx, with
  2462. bounds checking.
  2463. @param[in] idx index of the element to access
  2464. @return reference to the element at index @a idx
  2465. @throw std::domain_error if the JSON value is not an array; example:
  2466. `"cannot use at() with string"`
  2467. @throw std::out_of_range if the index @a idx is out of range of the array;
  2468. that is, `idx >= size()`; example: `"array index 7 is out of range"`
  2469. @complexity Constant.
  2470. @liveexample{The example below shows how array elements can be read and
  2471. written using `at()`.,at__size_type}
  2472. @since version 1.0.0
  2473. */
  2474. reference at(size_type idx)
  2475. {
  2476. // at only works for arrays
  2477. if (is_array())
  2478. {
  2479. try
  2480. {
  2481. return m_value.array->at(idx);
  2482. }
  2483. catch (std::out_of_range&)
  2484. {
  2485. // create better exception explanation
  2486. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  2487. }
  2488. }
  2489. else
  2490. {
  2491. throw std::domain_error("cannot use at() with " + type_name());
  2492. }
  2493. }
  2494. /*!
  2495. @brief access specified array element with bounds checking
  2496. Returns a const reference to the element at specified location @a idx,
  2497. with bounds checking.
  2498. @param[in] idx index of the element to access
  2499. @return const reference to the element at index @a idx
  2500. @throw std::domain_error if the JSON value is not an array; example:
  2501. `"cannot use at() with string"`
  2502. @throw std::out_of_range if the index @a idx is out of range of the array;
  2503. that is, `idx >= size()`; example: `"array index 7 is out of range"`
  2504. @complexity Constant.
  2505. @liveexample{The example below shows how array elements can be read using
  2506. `at()`.,at__size_type_const}
  2507. @since version 1.0.0
  2508. */
  2509. const_reference at(size_type idx) const
  2510. {
  2511. // at only works for arrays
  2512. if (is_array())
  2513. {
  2514. try
  2515. {
  2516. return m_value.array->at(idx);
  2517. }
  2518. catch (std::out_of_range&)
  2519. {
  2520. // create better exception explanation
  2521. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  2522. }
  2523. }
  2524. else
  2525. {
  2526. throw std::domain_error("cannot use at() with " + type_name());
  2527. }
  2528. }
  2529. /*!
  2530. @brief access specified object element with bounds checking
  2531. Returns a reference to the element at with specified key @a key, with
  2532. bounds checking.
  2533. @param[in] key key of the element to access
  2534. @return reference to the element at key @a key
  2535. @throw std::domain_error if the JSON value is not an object; example:
  2536. `"cannot use at() with boolean"`
  2537. @throw std::out_of_range if the key @a key is is not stored in the object;
  2538. that is, `find(key) == end()`; example: `"key "the fast" not found"`
  2539. @complexity Logarithmic in the size of the container.
  2540. @liveexample{The example below shows how object elements can be read and
  2541. written using `at()`.,at__object_t_key_type}
  2542. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2543. access by reference
  2544. @sa @ref value() for access by value with a default value
  2545. @since version 1.0.0
  2546. */
  2547. reference at(const typename object_t::key_type& key)
  2548. {
  2549. // at only works for objects
  2550. if (is_object())
  2551. {
  2552. try
  2553. {
  2554. return m_value.object->at(key);
  2555. }
  2556. catch (std::out_of_range&)
  2557. {
  2558. // create better exception explanation
  2559. throw std::out_of_range("key '" + key + "' not found");
  2560. }
  2561. }
  2562. else
  2563. {
  2564. throw std::domain_error("cannot use at() with " + type_name());
  2565. }
  2566. }
  2567. /*!
  2568. @brief access specified object element with bounds checking
  2569. Returns a const reference to the element at with specified key @a key,
  2570. with bounds checking.
  2571. @param[in] key key of the element to access
  2572. @return const reference to the element at key @a key
  2573. @throw std::domain_error if the JSON value is not an object; example:
  2574. `"cannot use at() with boolean"`
  2575. @throw std::out_of_range if the key @a key is is not stored in the object;
  2576. that is, `find(key) == end()`; example: `"key "the fast" not found"`
  2577. @complexity Logarithmic in the size of the container.
  2578. @liveexample{The example below shows how object elements can be read using
  2579. `at()`.,at__object_t_key_type_const}
  2580. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2581. access by reference
  2582. @sa @ref value() for access by value with a default value
  2583. @since version 1.0.0
  2584. */
  2585. const_reference at(const typename object_t::key_type& key) const
  2586. {
  2587. // at only works for objects
  2588. if (is_object())
  2589. {
  2590. try
  2591. {
  2592. return m_value.object->at(key);
  2593. }
  2594. catch (std::out_of_range&)
  2595. {
  2596. // create better exception explanation
  2597. throw std::out_of_range("key '" + key + "' not found");
  2598. }
  2599. }
  2600. else
  2601. {
  2602. throw std::domain_error("cannot use at() with " + type_name());
  2603. }
  2604. }
  2605. /*!
  2606. @brief access specified array element
  2607. Returns a reference to the element at specified location @a idx.
  2608. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  2609. then the array is silently filled up with `null` values to make `idx` a
  2610. valid reference to the last stored element.
  2611. @param[in] idx index of the element to access
  2612. @return reference to the element at index @a idx
  2613. @throw std::domain_error if JSON is not an array or null; example:
  2614. `"cannot use operator[] with string"`
  2615. @complexity Constant if @a idx is in the range of the array. Otherwise
  2616. linear in `idx - size()`.
  2617. @liveexample{The example below shows how array elements can be read and
  2618. written using `[]` operator. Note the addition of `null`
  2619. values.,operatorarray__size_type}
  2620. @since version 1.0.0
  2621. */
  2622. reference operator[](size_type idx)
  2623. {
  2624. // implicitly convert null value to an empty array
  2625. if (is_null())
  2626. {
  2627. m_type = value_t::array;
  2628. m_value.array = create<array_t>();
  2629. assert_invariant();
  2630. }
  2631. // operator[] only works for arrays
  2632. if (is_array())
  2633. {
  2634. // fill up array with null values if given idx is outside range
  2635. if (idx >= m_value.array->size())
  2636. {
  2637. m_value.array->insert(m_value.array->end(),
  2638. idx - m_value.array->size() + 1,
  2639. basic_json());
  2640. }
  2641. return m_value.array->operator[](idx);
  2642. }
  2643. else
  2644. {
  2645. throw std::domain_error("cannot use operator[] with " + type_name());
  2646. }
  2647. }
  2648. /*!
  2649. @brief access specified array element
  2650. Returns a const reference to the element at specified location @a idx.
  2651. @param[in] idx index of the element to access
  2652. @return const reference to the element at index @a idx
  2653. @throw std::domain_error if JSON is not an array; example: `"cannot use
  2654. operator[] with null"`
  2655. @complexity Constant.
  2656. @liveexample{The example below shows how array elements can be read using
  2657. the `[]` operator.,operatorarray__size_type_const}
  2658. @since version 1.0.0
  2659. */
  2660. const_reference operator[](size_type idx) const
  2661. {
  2662. // const operator[] only works for arrays
  2663. if (is_array())
  2664. {
  2665. return m_value.array->operator[](idx);
  2666. }
  2667. else
  2668. {
  2669. throw std::domain_error("cannot use operator[] with " + type_name());
  2670. }
  2671. }
  2672. /*!
  2673. @brief access specified object element
  2674. Returns a reference to the element at with specified key @a key.
  2675. @note If @a key is not found in the object, then it is silently added to
  2676. the object and filled with a `null` value to make `key` a valid reference.
  2677. In case the value was `null` before, it is converted to an object.
  2678. @param[in] key key of the element to access
  2679. @return reference to the element at key @a key
  2680. @throw std::domain_error if JSON is not an object or null; example:
  2681. `"cannot use operator[] with string"`
  2682. @complexity Logarithmic in the size of the container.
  2683. @liveexample{The example below shows how object elements can be read and
  2684. written using the `[]` operator.,operatorarray__key_type}
  2685. @sa @ref at(const typename object_t::key_type&) for access by reference
  2686. with range checking
  2687. @sa @ref value() for access by value with a default value
  2688. @since version 1.0.0
  2689. */
  2690. reference operator[](const typename object_t::key_type& key)
  2691. {
  2692. // implicitly convert null value to an empty object
  2693. if (is_null())
  2694. {
  2695. m_type = value_t::object;
  2696. m_value.object = create<object_t>();
  2697. assert_invariant();
  2698. }
  2699. // operator[] only works for objects
  2700. if (is_object())
  2701. {
  2702. return m_value.object->operator[](key);
  2703. }
  2704. else
  2705. {
  2706. throw std::domain_error("cannot use operator[] with " + type_name());
  2707. }
  2708. }
  2709. /*!
  2710. @brief read-only access specified object element
  2711. Returns a const reference to the element at with specified key @a key. No
  2712. bounds checking is performed.
  2713. @warning If the element with key @a key does not exist, the behavior is
  2714. undefined.
  2715. @param[in] key key of the element to access
  2716. @return const reference to the element at key @a key
  2717. @pre The element with key @a key must exist. **This precondition is
  2718. enforced with an assertion.**
  2719. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2720. operator[] with null"`
  2721. @complexity Logarithmic in the size of the container.
  2722. @liveexample{The example below shows how object elements can be read using
  2723. the `[]` operator.,operatorarray__key_type_const}
  2724. @sa @ref at(const typename object_t::key_type&) for access by reference
  2725. with range checking
  2726. @sa @ref value() for access by value with a default value
  2727. @since version 1.0.0
  2728. */
  2729. const_reference operator[](const typename object_t::key_type& key) const
  2730. {
  2731. // const operator[] only works for objects
  2732. if (is_object())
  2733. {
  2734. assert(m_value.object->find(key) != m_value.object->end());
  2735. return m_value.object->find(key)->second;
  2736. }
  2737. else
  2738. {
  2739. throw std::domain_error("cannot use operator[] with " + type_name());
  2740. }
  2741. }
  2742. /*!
  2743. @brief access specified object element
  2744. Returns a reference to the element at with specified key @a key.
  2745. @note If @a key is not found in the object, then it is silently added to
  2746. the object and filled with a `null` value to make `key` a valid reference.
  2747. In case the value was `null` before, it is converted to an object.
  2748. @param[in] key key of the element to access
  2749. @return reference to the element at key @a key
  2750. @throw std::domain_error if JSON is not an object or null; example:
  2751. `"cannot use operator[] with string"`
  2752. @complexity Logarithmic in the size of the container.
  2753. @liveexample{The example below shows how object elements can be read and
  2754. written using the `[]` operator.,operatorarray__key_type}
  2755. @sa @ref at(const typename object_t::key_type&) for access by reference
  2756. with range checking
  2757. @sa @ref value() for access by value with a default value
  2758. @since version 1.0.0
  2759. */
  2760. template<typename T, std::size_t n>
  2761. reference operator[](T * (&key)[n])
  2762. {
  2763. return operator[](static_cast<const T>(key));
  2764. }
  2765. /*!
  2766. @brief read-only access specified object element
  2767. Returns a const reference to the element at with specified key @a key. No
  2768. bounds checking is performed.
  2769. @warning If the element with key @a key does not exist, the behavior is
  2770. undefined.
  2771. @note This function is required for compatibility reasons with Clang.
  2772. @param[in] key key of the element to access
  2773. @return const reference to the element at key @a key
  2774. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2775. operator[] with null"`
  2776. @complexity Logarithmic in the size of the container.
  2777. @liveexample{The example below shows how object elements can be read using
  2778. the `[]` operator.,operatorarray__key_type_const}
  2779. @sa @ref at(const typename object_t::key_type&) for access by reference
  2780. with range checking
  2781. @sa @ref value() for access by value with a default value
  2782. @since version 1.0.0
  2783. */
  2784. template<typename T, std::size_t n>
  2785. const_reference operator[](T * (&key)[n]) const
  2786. {
  2787. return operator[](static_cast<const T>(key));
  2788. }
  2789. /*!
  2790. @brief access specified object element
  2791. Returns a reference to the element at with specified key @a key.
  2792. @note If @a key is not found in the object, then it is silently added to
  2793. the object and filled with a `null` value to make `key` a valid reference.
  2794. In case the value was `null` before, it is converted to an object.
  2795. @param[in] key key of the element to access
  2796. @return reference to the element at key @a key
  2797. @throw std::domain_error if JSON is not an object or null; example:
  2798. `"cannot use operator[] with string"`
  2799. @complexity Logarithmic in the size of the container.
  2800. @liveexample{The example below shows how object elements can be read and
  2801. written using the `[]` operator.,operatorarray__key_type}
  2802. @sa @ref at(const typename object_t::key_type&) for access by reference
  2803. with range checking
  2804. @sa @ref value() for access by value with a default value
  2805. @since version 1.1.0
  2806. */
  2807. template<typename T>
  2808. reference operator[](T* key)
  2809. {
  2810. // implicitly convert null to object
  2811. if (is_null())
  2812. {
  2813. m_type = value_t::object;
  2814. m_value = value_t::object;
  2815. assert_invariant();
  2816. }
  2817. // at only works for objects
  2818. if (is_object())
  2819. {
  2820. return m_value.object->operator[](key);
  2821. }
  2822. else
  2823. {
  2824. throw std::domain_error("cannot use operator[] with " + type_name());
  2825. }
  2826. }
  2827. /*!
  2828. @brief read-only access specified object element
  2829. Returns a const reference to the element at with specified key @a key. No
  2830. bounds checking is performed.
  2831. @warning If the element with key @a key does not exist, the behavior is
  2832. undefined.
  2833. @param[in] key key of the element to access
  2834. @return const reference to the element at key @a key
  2835. @pre The element with key @a key must exist. **This precondition is
  2836. enforced with an assertion.**
  2837. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2838. operator[] with null"`
  2839. @complexity Logarithmic in the size of the container.
  2840. @liveexample{The example below shows how object elements can be read using
  2841. the `[]` operator.,operatorarray__key_type_const}
  2842. @sa @ref at(const typename object_t::key_type&) for access by reference
  2843. with range checking
  2844. @sa @ref value() for access by value with a default value
  2845. @since version 1.1.0
  2846. */
  2847. template<typename T>
  2848. const_reference operator[](T* key) const
  2849. {
  2850. // at only works for objects
  2851. if (is_object())
  2852. {
  2853. assert(m_value.object->find(key) != m_value.object->end());
  2854. return m_value.object->find(key)->second;
  2855. }
  2856. else
  2857. {
  2858. throw std::domain_error("cannot use operator[] with " + type_name());
  2859. }
  2860. }
  2861. /*!
  2862. @brief access specified object element with default value
  2863. Returns either a copy of an object's element at the specified key @a key
  2864. or a given default value if no element with key @a key exists.
  2865. The function is basically equivalent to executing
  2866. @code {.cpp}
  2867. try {
  2868. return at(key);
  2869. } catch(std::out_of_range) {
  2870. return default_value;
  2871. }
  2872. @endcode
  2873. @note Unlike @ref at(const typename object_t::key_type&), this function
  2874. does not throw if the given key @a key was not found.
  2875. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  2876. function does not implicitly add an element to the position defined by @a
  2877. key. This function is furthermore also applicable to const objects.
  2878. @param[in] key key of the element to access
  2879. @param[in] default_value the value to return if @a key is not found
  2880. @tparam ValueType type compatible to JSON values, for instance `int` for
  2881. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  2882. JSON arrays. Note the type of the expected value at @a key and the default
  2883. value @a default_value must be compatible.
  2884. @return copy of the element at key @a key or @a default_value if @a key
  2885. is not found
  2886. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2887. value() with null"`
  2888. @complexity Logarithmic in the size of the container.
  2889. @liveexample{The example below shows how object elements can be queried
  2890. with a default value.,basic_json__value}
  2891. @sa @ref at(const typename object_t::key_type&) for access by reference
  2892. with range checking
  2893. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2894. access by reference
  2895. @since version 1.0.0
  2896. */
  2897. template<class ValueType, typename std::enable_if<
  2898. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  2899. ValueType value(const typename object_t::key_type& key, ValueType default_value) const
  2900. {
  2901. // at only works for objects
  2902. if (is_object())
  2903. {
  2904. // if key is found, return value and given default value otherwise
  2905. const auto it = find(key);
  2906. if (it != end())
  2907. {
  2908. return *it;
  2909. }
  2910. else
  2911. {
  2912. return default_value;
  2913. }
  2914. }
  2915. else
  2916. {
  2917. throw std::domain_error("cannot use value() with " + type_name());
  2918. }
  2919. }
  2920. /*!
  2921. @brief overload for a default value of type const char*
  2922. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  2923. */
  2924. string_t value(const typename object_t::key_type& key, const char* default_value) const
  2925. {
  2926. return value(key, string_t(default_value));
  2927. }
  2928. /*!
  2929. @brief access specified object element via JSON Pointer with default value
  2930. Returns either a copy of an object's element at the specified key @a key
  2931. or a given default value if no element with key @a key exists.
  2932. The function is basically equivalent to executing
  2933. @code {.cpp}
  2934. try {
  2935. return at(ptr);
  2936. } catch(std::out_of_range) {
  2937. return default_value;
  2938. }
  2939. @endcode
  2940. @note Unlike @ref at(const json_pointer&), this function does not throw
  2941. if the given key @a key was not found.
  2942. @param[in] ptr a JSON pointer to the element to access
  2943. @param[in] default_value the value to return if @a ptr found no value
  2944. @tparam ValueType type compatible to JSON values, for instance `int` for
  2945. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  2946. JSON arrays. Note the type of the expected value at @a key and the default
  2947. value @a default_value must be compatible.
  2948. @return copy of the element at key @a key or @a default_value if @a key
  2949. is not found
  2950. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2951. value() with null"`
  2952. @complexity Logarithmic in the size of the container.
  2953. @liveexample{The example below shows how object elements can be queried
  2954. with a default value.,basic_json__value_ptr}
  2955. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  2956. @since version 2.0.2
  2957. */
  2958. template<class ValueType, typename std::enable_if<
  2959. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  2960. ValueType value(const json_pointer& ptr, ValueType default_value) const
  2961. {
  2962. // at only works for objects
  2963. if (is_object())
  2964. {
  2965. // if pointer resolves a value, return it or use default value
  2966. try
  2967. {
  2968. return ptr.get_checked(this);
  2969. }
  2970. catch (std::out_of_range&)
  2971. {
  2972. return default_value;
  2973. }
  2974. }
  2975. else
  2976. {
  2977. throw std::domain_error("cannot use value() with " + type_name());
  2978. }
  2979. }
  2980. /*!
  2981. @brief overload for a default value of type const char*
  2982. @copydoc basic_json::value(const json_pointer&, ValueType) const
  2983. */
  2984. string_t value(const json_pointer& ptr, const char* default_value) const
  2985. {
  2986. return value(ptr, string_t(default_value));
  2987. }
  2988. /*!
  2989. @brief access the first element
  2990. Returns a reference to the first element in the container. For a JSON
  2991. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  2992. @return In case of a structured type (array or object), a reference to the
  2993. first element is returned. In case of number, string, or boolean values, a
  2994. reference to the value is returned.
  2995. @complexity Constant.
  2996. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  2997. or an empty array or object (undefined behavior, **guarded by
  2998. assertions**).
  2999. @post The JSON value remains unchanged.
  3000. @throw std::out_of_range when called on `null` value
  3001. @liveexample{The following code shows an example for `front()`.,front}
  3002. @sa @ref back() -- access the last element
  3003. @since version 1.0.0
  3004. */
  3005. reference front()
  3006. {
  3007. return *begin();
  3008. }
  3009. /*!
  3010. @copydoc basic_json::front()
  3011. */
  3012. const_reference front() const
  3013. {
  3014. return *cbegin();
  3015. }
  3016. /*!
  3017. @brief access the last element
  3018. Returns a reference to the last element in the container. For a JSON
  3019. container `c`, the expression `c.back()` is equivalent to
  3020. @code {.cpp}
  3021. auto tmp = c.end();
  3022. --tmp;
  3023. return *tmp;
  3024. @endcode
  3025. @return In case of a structured type (array or object), a reference to the
  3026. last element is returned. In case of number, string, or boolean values, a
  3027. reference to the value is returned.
  3028. @complexity Constant.
  3029. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3030. or an empty array or object (undefined behavior, **guarded by
  3031. assertions**).
  3032. @post The JSON value remains unchanged.
  3033. @throw std::out_of_range when called on `null` value.
  3034. @liveexample{The following code shows an example for `back()`.,back}
  3035. @sa @ref front() -- access the first element
  3036. @since version 1.0.0
  3037. */
  3038. reference back()
  3039. {
  3040. auto tmp = end();
  3041. --tmp;
  3042. return *tmp;
  3043. }
  3044. /*!
  3045. @copydoc basic_json::back()
  3046. */
  3047. const_reference back() const
  3048. {
  3049. auto tmp = cend();
  3050. --tmp;
  3051. return *tmp;
  3052. }
  3053. /*!
  3054. @brief remove element given an iterator
  3055. Removes the element specified by iterator @a pos. The iterator @a pos must
  3056. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  3057. but is not dereferenceable) cannot be used as a value for @a pos.
  3058. If called on a primitive type other than `null`, the resulting JSON value
  3059. will be `null`.
  3060. @param[in] pos iterator to the element to remove
  3061. @return Iterator following the last removed element. If the iterator @a
  3062. pos refers to the last element, the `end()` iterator is returned.
  3063. @tparam IteratorType an @ref iterator or @ref const_iterator
  3064. @post Invalidates iterators and references at or after the point of the
  3065. erase, including the `end()` iterator.
  3066. @throw std::domain_error if called on a `null` value; example: `"cannot
  3067. use erase() with null"`
  3068. @throw std::domain_error if called on an iterator which does not belong to
  3069. the current JSON value; example: `"iterator does not fit current value"`
  3070. @throw std::out_of_range if called on a primitive type with invalid
  3071. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  3072. out of range"`
  3073. @complexity The complexity depends on the type:
  3074. - objects: amortized constant
  3075. - arrays: linear in distance between pos and the end of the container
  3076. - strings: linear in the length of the string
  3077. - other types: constant
  3078. @liveexample{The example shows the result of `erase()` for different JSON
  3079. types.,erase__IteratorType}
  3080. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3081. the given range
  3082. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3083. from an object at the given key
  3084. @sa @ref erase(const size_type) -- removes the element from an array at
  3085. the given index
  3086. @since version 1.0.0
  3087. */
  3088. template<class IteratorType, typename std::enable_if<
  3089. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3090. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3091. = 0>
  3092. IteratorType erase(IteratorType pos)
  3093. {
  3094. // make sure iterator fits the current value
  3095. if (this != pos.m_object)
  3096. {
  3097. throw std::domain_error("iterator does not fit current value");
  3098. }
  3099. IteratorType result = end();
  3100. switch (m_type)
  3101. {
  3102. case value_t::boolean:
  3103. case value_t::number_float:
  3104. case value_t::number_integer:
  3105. case value_t::number_unsigned:
  3106. case value_t::string:
  3107. {
  3108. if (not pos.m_it.primitive_iterator.is_begin())
  3109. {
  3110. throw std::out_of_range("iterator out of range");
  3111. }
  3112. if (is_string())
  3113. {
  3114. AllocatorType<string_t> alloc;
  3115. alloc.destroy(m_value.string);
  3116. alloc.deallocate(m_value.string, 1);
  3117. m_value.string = nullptr;
  3118. }
  3119. m_type = value_t::null;
  3120. assert_invariant();
  3121. break;
  3122. }
  3123. case value_t::object:
  3124. {
  3125. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  3126. break;
  3127. }
  3128. case value_t::array:
  3129. {
  3130. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  3131. break;
  3132. }
  3133. default:
  3134. {
  3135. throw std::domain_error("cannot use erase() with " + type_name());
  3136. }
  3137. }
  3138. return result;
  3139. }
  3140. /*!
  3141. @brief remove elements given an iterator range
  3142. Removes the element specified by the range `[first; last)`. The iterator
  3143. @a first does not need to be dereferenceable if `first == last`: erasing
  3144. an empty range is a no-op.
  3145. If called on a primitive type other than `null`, the resulting JSON value
  3146. will be `null`.
  3147. @param[in] first iterator to the beginning of the range to remove
  3148. @param[in] last iterator past the end of the range to remove
  3149. @return Iterator following the last removed element. If the iterator @a
  3150. second refers to the last element, the `end()` iterator is returned.
  3151. @tparam IteratorType an @ref iterator or @ref const_iterator
  3152. @post Invalidates iterators and references at or after the point of the
  3153. erase, including the `end()` iterator.
  3154. @throw std::domain_error if called on a `null` value; example: `"cannot
  3155. use erase() with null"`
  3156. @throw std::domain_error if called on iterators which does not belong to
  3157. the current JSON value; example: `"iterators do not fit current value"`
  3158. @throw std::out_of_range if called on a primitive type with invalid
  3159. iterators (i.e., if `first != begin()` and `last != end()`); example:
  3160. `"iterators out of range"`
  3161. @complexity The complexity depends on the type:
  3162. - objects: `log(size()) + std::distance(first, last)`
  3163. - arrays: linear in the distance between @a first and @a last, plus linear
  3164. in the distance between @a last and end of the container
  3165. - strings: linear in the length of the string
  3166. - other types: constant
  3167. @liveexample{The example shows the result of `erase()` for different JSON
  3168. types.,erase__IteratorType_IteratorType}
  3169. @sa @ref erase(IteratorType) -- removes the element at a given position
  3170. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3171. from an object at the given key
  3172. @sa @ref erase(const size_type) -- removes the element from an array at
  3173. the given index
  3174. @since version 1.0.0
  3175. */
  3176. template<class IteratorType, typename std::enable_if<
  3177. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3178. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3179. = 0>
  3180. IteratorType erase(IteratorType first, IteratorType last)
  3181. {
  3182. // make sure iterator fits the current value
  3183. if (this != first.m_object or this != last.m_object)
  3184. {
  3185. throw std::domain_error("iterators do not fit current value");
  3186. }
  3187. IteratorType result = end();
  3188. switch (m_type)
  3189. {
  3190. case value_t::boolean:
  3191. case value_t::number_float:
  3192. case value_t::number_integer:
  3193. case value_t::number_unsigned:
  3194. case value_t::string:
  3195. {
  3196. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  3197. {
  3198. throw std::out_of_range("iterators out of range");
  3199. }
  3200. if (is_string())
  3201. {
  3202. AllocatorType<string_t> alloc;
  3203. alloc.destroy(m_value.string);
  3204. alloc.deallocate(m_value.string, 1);
  3205. m_value.string = nullptr;
  3206. }
  3207. m_type = value_t::null;
  3208. assert_invariant();
  3209. break;
  3210. }
  3211. case value_t::object:
  3212. {
  3213. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  3214. last.m_it.object_iterator);
  3215. break;
  3216. }
  3217. case value_t::array:
  3218. {
  3219. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  3220. last.m_it.array_iterator);
  3221. break;
  3222. }
  3223. default:
  3224. {
  3225. throw std::domain_error("cannot use erase() with " + type_name());
  3226. }
  3227. }
  3228. return result;
  3229. }
  3230. /*!
  3231. @brief remove element from a JSON object given a key
  3232. Removes elements from a JSON object with the key value @a key.
  3233. @param[in] key value of the elements to remove
  3234. @return Number of elements removed. If @a ObjectType is the default
  3235. `std::map` type, the return value will always be `0` (@a key was not
  3236. found) or `1` (@a key was found).
  3237. @post References and iterators to the erased elements are invalidated.
  3238. Other references and iterators are not affected.
  3239. @throw std::domain_error when called on a type other than JSON object;
  3240. example: `"cannot use erase() with null"`
  3241. @complexity `log(size()) + count(key)`
  3242. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  3243. @sa @ref erase(IteratorType) -- removes the element at a given position
  3244. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3245. the given range
  3246. @sa @ref erase(const size_type) -- removes the element from an array at
  3247. the given index
  3248. @since version 1.0.0
  3249. */
  3250. size_type erase(const typename object_t::key_type& key)
  3251. {
  3252. // this erase only works for objects
  3253. if (is_object())
  3254. {
  3255. return m_value.object->erase(key);
  3256. }
  3257. else
  3258. {
  3259. throw std::domain_error("cannot use erase() with " + type_name());
  3260. }
  3261. }
  3262. /*!
  3263. @brief remove element from a JSON array given an index
  3264. Removes element from a JSON array at the index @a idx.
  3265. @param[in] idx index of the element to remove
  3266. @throw std::domain_error when called on a type other than JSON array;
  3267. example: `"cannot use erase() with null"`
  3268. @throw std::out_of_range when `idx >= size()`; example: `"array index 17
  3269. is out of range"`
  3270. @complexity Linear in distance between @a idx and the end of the container.
  3271. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  3272. @sa @ref erase(IteratorType) -- removes the element at a given position
  3273. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3274. the given range
  3275. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3276. from an object at the given key
  3277. @since version 1.0.0
  3278. */
  3279. void erase(const size_type idx)
  3280. {
  3281. // this erase only works for arrays
  3282. if (is_array())
  3283. {
  3284. if (idx >= size())
  3285. {
  3286. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  3287. }
  3288. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  3289. }
  3290. else
  3291. {
  3292. throw std::domain_error("cannot use erase() with " + type_name());
  3293. }
  3294. }
  3295. /// @}
  3296. ////////////
  3297. // lookup //
  3298. ////////////
  3299. /// @name lookup
  3300. /// @{
  3301. /*!
  3302. @brief find an element in a JSON object
  3303. Finds an element in a JSON object with key equivalent to @a key. If the
  3304. element is not found or the JSON value is not an object, end() is
  3305. returned.
  3306. @note This method always returns @ref end() when executed on a JSON type
  3307. that is not an object.
  3308. @param[in] key key value of the element to search for
  3309. @return Iterator to an element with key equivalent to @a key. If no such
  3310. element is found or the JSON value is not an object, past-the-end (see
  3311. @ref end()) iterator is returned.
  3312. @complexity Logarithmic in the size of the JSON object.
  3313. @liveexample{The example shows how `find()` is used.,find__key_type}
  3314. @since version 1.0.0
  3315. */
  3316. iterator find(typename object_t::key_type key)
  3317. {
  3318. auto result = end();
  3319. if (is_object())
  3320. {
  3321. result.m_it.object_iterator = m_value.object->find(key);
  3322. }
  3323. return result;
  3324. }
  3325. /*!
  3326. @brief find an element in a JSON object
  3327. @copydoc find(typename object_t::key_type)
  3328. */
  3329. const_iterator find(typename object_t::key_type key) const
  3330. {
  3331. auto result = cend();
  3332. if (is_object())
  3333. {
  3334. result.m_it.object_iterator = m_value.object->find(key);
  3335. }
  3336. return result;
  3337. }
  3338. /*!
  3339. @brief returns the number of occurrences of a key in a JSON object
  3340. Returns the number of elements with key @a key. If ObjectType is the
  3341. default `std::map` type, the return value will always be `0` (@a key was
  3342. not found) or `1` (@a key was found).
  3343. @note This method always returns `0` when executed on a JSON type that is
  3344. not an object.
  3345. @param[in] key key value of the element to count
  3346. @return Number of elements with key @a key. If the JSON value is not an
  3347. object, the return value will be `0`.
  3348. @complexity Logarithmic in the size of the JSON object.
  3349. @liveexample{The example shows how `count()` is used.,count}
  3350. @since version 1.0.0
  3351. */
  3352. size_type count(typename object_t::key_type key) const
  3353. {
  3354. // return 0 for all nonobject types
  3355. return is_object() ? m_value.object->count(key) : 0;
  3356. }
  3357. /// @}
  3358. ///////////////
  3359. // iterators //
  3360. ///////////////
  3361. /// @name iterators
  3362. /// @{
  3363. /*!
  3364. @brief returns an iterator to the first element
  3365. Returns an iterator to the first element.
  3366. @image html range-begin-end.svg "Illustration from cppreference.com"
  3367. @return iterator to the first element
  3368. @complexity Constant.
  3369. @requirement This function helps `basic_json` satisfying the
  3370. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3371. requirements:
  3372. - The complexity is constant.
  3373. @liveexample{The following code shows an example for `begin()`.,begin}
  3374. @sa @ref cbegin() -- returns a const iterator to the beginning
  3375. @sa @ref end() -- returns an iterator to the end
  3376. @sa @ref cend() -- returns a const iterator to the end
  3377. @since version 1.0.0
  3378. */
  3379. iterator begin() noexcept
  3380. {
  3381. iterator result(this);
  3382. result.set_begin();
  3383. return result;
  3384. }
  3385. /*!
  3386. @copydoc basic_json::cbegin()
  3387. */
  3388. const_iterator begin() const noexcept
  3389. {
  3390. return cbegin();
  3391. }
  3392. /*!
  3393. @brief returns a const iterator to the first element
  3394. Returns a const iterator to the first element.
  3395. @image html range-begin-end.svg "Illustration from cppreference.com"
  3396. @return const iterator to the first element
  3397. @complexity Constant.
  3398. @requirement This function helps `basic_json` satisfying the
  3399. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3400. requirements:
  3401. - The complexity is constant.
  3402. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  3403. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  3404. @sa @ref begin() -- returns an iterator to the beginning
  3405. @sa @ref end() -- returns an iterator to the end
  3406. @sa @ref cend() -- returns a const iterator to the end
  3407. @since version 1.0.0
  3408. */
  3409. const_iterator cbegin() const noexcept
  3410. {
  3411. const_iterator result(this);
  3412. result.set_begin();
  3413. return result;
  3414. }
  3415. /*!
  3416. @brief returns an iterator to one past the last element
  3417. Returns an iterator to one past the last element.
  3418. @image html range-begin-end.svg "Illustration from cppreference.com"
  3419. @return iterator one past the last element
  3420. @complexity Constant.
  3421. @requirement This function helps `basic_json` satisfying the
  3422. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3423. requirements:
  3424. - The complexity is constant.
  3425. @liveexample{The following code shows an example for `end()`.,end}
  3426. @sa @ref cend() -- returns a const iterator to the end
  3427. @sa @ref begin() -- returns an iterator to the beginning
  3428. @sa @ref cbegin() -- returns a const iterator to the beginning
  3429. @since version 1.0.0
  3430. */
  3431. iterator end() noexcept
  3432. {
  3433. iterator result(this);
  3434. result.set_end();
  3435. return result;
  3436. }
  3437. /*!
  3438. @copydoc basic_json::cend()
  3439. */
  3440. const_iterator end() const noexcept
  3441. {
  3442. return cend();
  3443. }
  3444. /*!
  3445. @brief returns a const iterator to one past the last element
  3446. Returns a const iterator to one past the last element.
  3447. @image html range-begin-end.svg "Illustration from cppreference.com"
  3448. @return const iterator one past the last element
  3449. @complexity Constant.
  3450. @requirement This function helps `basic_json` satisfying the
  3451. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3452. requirements:
  3453. - The complexity is constant.
  3454. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  3455. @liveexample{The following code shows an example for `cend()`.,cend}
  3456. @sa @ref end() -- returns an iterator to the end
  3457. @sa @ref begin() -- returns an iterator to the beginning
  3458. @sa @ref cbegin() -- returns a const iterator to the beginning
  3459. @since version 1.0.0
  3460. */
  3461. const_iterator cend() const noexcept
  3462. {
  3463. const_iterator result(this);
  3464. result.set_end();
  3465. return result;
  3466. }
  3467. /*!
  3468. @brief returns an iterator to the reverse-beginning
  3469. Returns an iterator to the reverse-beginning; that is, the last element.
  3470. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3471. @complexity Constant.
  3472. @requirement This function helps `basic_json` satisfying the
  3473. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3474. requirements:
  3475. - The complexity is constant.
  3476. - Has the semantics of `reverse_iterator(end())`.
  3477. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  3478. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3479. @sa @ref rend() -- returns a reverse iterator to the end
  3480. @sa @ref crend() -- returns a const reverse iterator to the end
  3481. @since version 1.0.0
  3482. */
  3483. reverse_iterator rbegin() noexcept
  3484. {
  3485. return reverse_iterator(end());
  3486. }
  3487. /*!
  3488. @copydoc basic_json::crbegin()
  3489. */
  3490. const_reverse_iterator rbegin() const noexcept
  3491. {
  3492. return crbegin();
  3493. }
  3494. /*!
  3495. @brief returns an iterator to the reverse-end
  3496. Returns an iterator to the reverse-end; that is, one before the first
  3497. element.
  3498. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3499. @complexity Constant.
  3500. @requirement This function helps `basic_json` satisfying the
  3501. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3502. requirements:
  3503. - The complexity is constant.
  3504. - Has the semantics of `reverse_iterator(begin())`.
  3505. @liveexample{The following code shows an example for `rend()`.,rend}
  3506. @sa @ref crend() -- returns a const reverse iterator to the end
  3507. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3508. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3509. @since version 1.0.0
  3510. */
  3511. reverse_iterator rend() noexcept
  3512. {
  3513. return reverse_iterator(begin());
  3514. }
  3515. /*!
  3516. @copydoc basic_json::crend()
  3517. */
  3518. const_reverse_iterator rend() const noexcept
  3519. {
  3520. return crend();
  3521. }
  3522. /*!
  3523. @brief returns a const reverse iterator to the last element
  3524. Returns a const iterator to the reverse-beginning; that is, the last
  3525. element.
  3526. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3527. @complexity Constant.
  3528. @requirement This function helps `basic_json` satisfying the
  3529. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3530. requirements:
  3531. - The complexity is constant.
  3532. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  3533. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  3534. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3535. @sa @ref rend() -- returns a reverse iterator to the end
  3536. @sa @ref crend() -- returns a const reverse iterator to the end
  3537. @since version 1.0.0
  3538. */
  3539. const_reverse_iterator crbegin() const noexcept
  3540. {
  3541. return const_reverse_iterator(cend());
  3542. }
  3543. /*!
  3544. @brief returns a const reverse iterator to one before the first
  3545. Returns a const reverse iterator to the reverse-end; that is, one before
  3546. the first element.
  3547. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3548. @complexity Constant.
  3549. @requirement This function helps `basic_json` satisfying the
  3550. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3551. requirements:
  3552. - The complexity is constant.
  3553. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  3554. @liveexample{The following code shows an example for `crend()`.,crend}
  3555. @sa @ref rend() -- returns a reverse iterator to the end
  3556. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3557. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3558. @since version 1.0.0
  3559. */
  3560. const_reverse_iterator crend() const noexcept
  3561. {
  3562. return const_reverse_iterator(cbegin());
  3563. }
  3564. private:
  3565. // forward declaration
  3566. template<typename IteratorType> class iteration_proxy;
  3567. public:
  3568. /*!
  3569. @brief wrapper to access iterator member functions in range-based for
  3570. This function allows to access @ref iterator::key() and @ref
  3571. iterator::value() during range-based for loops. In these loops, a
  3572. reference to the JSON values is returned, so there is no access to the
  3573. underlying iterator.
  3574. @note The name of this function is not yet final and may change in the
  3575. future.
  3576. */
  3577. static iteration_proxy<iterator> iterator_wrapper(reference cont)
  3578. {
  3579. return iteration_proxy<iterator>(cont);
  3580. }
  3581. /*!
  3582. @copydoc iterator_wrapper(reference)
  3583. */
  3584. static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
  3585. {
  3586. return iteration_proxy<const_iterator>(cont);
  3587. }
  3588. /// @}
  3589. //////////////
  3590. // capacity //
  3591. //////////////
  3592. /// @name capacity
  3593. /// @{
  3594. /*!
  3595. @brief checks whether the container is empty
  3596. Checks if a JSON value has no elements.
  3597. @return The return value depends on the different types and is
  3598. defined as follows:
  3599. Value type | return value
  3600. ----------- | -------------
  3601. null | `true`
  3602. boolean | `false`
  3603. string | `false`
  3604. number | `false`
  3605. object | result of function `object_t::empty()`
  3606. array | result of function `array_t::empty()`
  3607. @note This function does not return whether a string stored as JSON value
  3608. is empty - it returns whether the JSON container itself is empty which is
  3609. false in the case of a string.
  3610. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3611. the Container concept; that is, their `empty()` functions have constant
  3612. complexity.
  3613. @requirement This function helps `basic_json` satisfying the
  3614. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3615. requirements:
  3616. - The complexity is constant.
  3617. - Has the semantics of `begin() == end()`.
  3618. @liveexample{The following code uses `empty()` to check if a JSON
  3619. object contains any elements.,empty}
  3620. @sa @ref size() -- returns the number of elements
  3621. @since version 1.0.0
  3622. */
  3623. bool empty() const noexcept
  3624. {
  3625. switch (m_type)
  3626. {
  3627. case value_t::null:
  3628. {
  3629. // null values are empty
  3630. return true;
  3631. }
  3632. case value_t::array:
  3633. {
  3634. // delegate call to array_t::empty()
  3635. return m_value.array->empty();
  3636. }
  3637. case value_t::object:
  3638. {
  3639. // delegate call to object_t::empty()
  3640. return m_value.object->empty();
  3641. }
  3642. default:
  3643. {
  3644. // all other types are nonempty
  3645. return false;
  3646. }
  3647. }
  3648. }
  3649. /*!
  3650. @brief returns the number of elements
  3651. Returns the number of elements in a JSON value.
  3652. @return The return value depends on the different types and is
  3653. defined as follows:
  3654. Value type | return value
  3655. ----------- | -------------
  3656. null | `0`
  3657. boolean | `1`
  3658. string | `1`
  3659. number | `1`
  3660. object | result of function object_t::size()
  3661. array | result of function array_t::size()
  3662. @note This function does not return the length of a string stored as JSON
  3663. value - it returns the number of elements in the JSON value which is 1 in
  3664. the case of a string.
  3665. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3666. the Container concept; that is, their size() functions have constant
  3667. complexity.
  3668. @requirement This function helps `basic_json` satisfying the
  3669. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3670. requirements:
  3671. - The complexity is constant.
  3672. - Has the semantics of `std::distance(begin(), end())`.
  3673. @liveexample{The following code calls `size()` on the different value
  3674. types.,size}
  3675. @sa @ref empty() -- checks whether the container is empty
  3676. @sa @ref max_size() -- returns the maximal number of elements
  3677. @since version 1.0.0
  3678. */
  3679. size_type size() const noexcept
  3680. {
  3681. switch (m_type)
  3682. {
  3683. case value_t::null:
  3684. {
  3685. // null values are empty
  3686. return 0;
  3687. }
  3688. case value_t::array:
  3689. {
  3690. // delegate call to array_t::size()
  3691. return m_value.array->size();
  3692. }
  3693. case value_t::object:
  3694. {
  3695. // delegate call to object_t::size()
  3696. return m_value.object->size();
  3697. }
  3698. default:
  3699. {
  3700. // all other types have size 1
  3701. return 1;
  3702. }
  3703. }
  3704. }
  3705. /*!
  3706. @brief returns the maximum possible number of elements
  3707. Returns the maximum number of elements a JSON value is able to hold due to
  3708. system or library implementation limitations, i.e. `std::distance(begin(),
  3709. end())` for the JSON value.
  3710. @return The return value depends on the different types and is
  3711. defined as follows:
  3712. Value type | return value
  3713. ----------- | -------------
  3714. null | `0` (same as `size()`)
  3715. boolean | `1` (same as `size()`)
  3716. string | `1` (same as `size()`)
  3717. number | `1` (same as `size()`)
  3718. object | result of function `object_t::max_size()`
  3719. array | result of function `array_t::max_size()`
  3720. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3721. the Container concept; that is, their `max_size()` functions have constant
  3722. complexity.
  3723. @requirement This function helps `basic_json` satisfying the
  3724. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3725. requirements:
  3726. - The complexity is constant.
  3727. - Has the semantics of returning `b.size()` where `b` is the largest
  3728. possible JSON value.
  3729. @liveexample{The following code calls `max_size()` on the different value
  3730. types. Note the output is implementation specific.,max_size}
  3731. @sa @ref size() -- returns the number of elements
  3732. @since version 1.0.0
  3733. */
  3734. size_type max_size() const noexcept
  3735. {
  3736. switch (m_type)
  3737. {
  3738. case value_t::array:
  3739. {
  3740. // delegate call to array_t::max_size()
  3741. return m_value.array->max_size();
  3742. }
  3743. case value_t::object:
  3744. {
  3745. // delegate call to object_t::max_size()
  3746. return m_value.object->max_size();
  3747. }
  3748. default:
  3749. {
  3750. // all other types have max_size() == size()
  3751. return size();
  3752. }
  3753. }
  3754. }
  3755. /// @}
  3756. ///////////////
  3757. // modifiers //
  3758. ///////////////
  3759. /// @name modifiers
  3760. /// @{
  3761. /*!
  3762. @brief clears the contents
  3763. Clears the content of a JSON value and resets it to the default value as
  3764. if @ref basic_json(value_t) would have been called:
  3765. Value type | initial value
  3766. ----------- | -------------
  3767. null | `null`
  3768. boolean | `false`
  3769. string | `""`
  3770. number | `0`
  3771. object | `{}`
  3772. array | `[]`
  3773. @complexity Linear in the size of the JSON value.
  3774. @liveexample{The example below shows the effect of `clear()` to different
  3775. JSON types.,clear}
  3776. @since version 1.0.0
  3777. */
  3778. void clear() noexcept
  3779. {
  3780. switch (m_type)
  3781. {
  3782. case value_t::number_integer:
  3783. {
  3784. m_value.number_integer = 0;
  3785. break;
  3786. }
  3787. case value_t::number_unsigned:
  3788. {
  3789. m_value.number_unsigned = 0;
  3790. break;
  3791. }
  3792. case value_t::number_float:
  3793. {
  3794. m_value.number_float = 0.0;
  3795. break;
  3796. }
  3797. case value_t::boolean:
  3798. {
  3799. m_value.boolean = false;
  3800. break;
  3801. }
  3802. case value_t::string:
  3803. {
  3804. m_value.string->clear();
  3805. break;
  3806. }
  3807. case value_t::array:
  3808. {
  3809. m_value.array->clear();
  3810. break;
  3811. }
  3812. case value_t::object:
  3813. {
  3814. m_value.object->clear();
  3815. break;
  3816. }
  3817. default:
  3818. {
  3819. break;
  3820. }
  3821. }
  3822. }
  3823. /*!
  3824. @brief add an object to an array
  3825. Appends the given element @a val to the end of the JSON value. If the
  3826. function is called on a JSON null value, an empty array is created before
  3827. appending @a val.
  3828. @param[in] val the value to add to the JSON array
  3829. @throw std::domain_error when called on a type other than JSON array or
  3830. null; example: `"cannot use push_back() with number"`
  3831. @complexity Amortized constant.
  3832. @liveexample{The example shows how `push_back()` and `+=` can be used to
  3833. add elements to a JSON array. Note how the `null` value was silently
  3834. converted to a JSON array.,push_back}
  3835. @since version 1.0.0
  3836. */
  3837. void push_back(basic_json&& val)
  3838. {
  3839. // push_back only works for null objects or arrays
  3840. if (not(is_null() or is_array()))
  3841. {
  3842. throw std::domain_error("cannot use push_back() with " + type_name());
  3843. }
  3844. // transform null object into an array
  3845. if (is_null())
  3846. {
  3847. m_type = value_t::array;
  3848. m_value = value_t::array;
  3849. assert_invariant();
  3850. }
  3851. // add element to array (move semantics)
  3852. m_value.array->push_back(std::move(val));
  3853. // invalidate object
  3854. val.m_type = value_t::null;
  3855. }
  3856. /*!
  3857. @brief add an object to an array
  3858. @copydoc push_back(basic_json&&)
  3859. */
  3860. reference operator+=(basic_json&& val)
  3861. {
  3862. push_back(std::move(val));
  3863. return *this;
  3864. }
  3865. /*!
  3866. @brief add an object to an array
  3867. @copydoc push_back(basic_json&&)
  3868. */
  3869. void push_back(const basic_json& val)
  3870. {
  3871. // push_back only works for null objects or arrays
  3872. if (not(is_null() or is_array()))
  3873. {
  3874. throw std::domain_error("cannot use push_back() with " + type_name());
  3875. }
  3876. // transform null object into an array
  3877. if (is_null())
  3878. {
  3879. m_type = value_t::array;
  3880. m_value = value_t::array;
  3881. assert_invariant();
  3882. }
  3883. // add element to array
  3884. m_value.array->push_back(val);
  3885. }
  3886. /*!
  3887. @brief add an object to an array
  3888. @copydoc push_back(basic_json&&)
  3889. */
  3890. reference operator+=(const basic_json& val)
  3891. {
  3892. push_back(val);
  3893. return *this;
  3894. }
  3895. /*!
  3896. @brief add an object to an object
  3897. Inserts the given element @a val to the JSON object. If the function is
  3898. called on a JSON null value, an empty object is created before inserting
  3899. @a val.
  3900. @param[in] val the value to add to the JSON object
  3901. @throw std::domain_error when called on a type other than JSON object or
  3902. null; example: `"cannot use push_back() with number"`
  3903. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  3904. @liveexample{The example shows how `push_back()` and `+=` can be used to
  3905. add elements to a JSON object. Note how the `null` value was silently
  3906. converted to a JSON object.,push_back__object_t__value}
  3907. @since version 1.0.0
  3908. */
  3909. void push_back(const typename object_t::value_type& val)
  3910. {
  3911. // push_back only works for null objects or objects
  3912. if (not(is_null() or is_object()))
  3913. {
  3914. throw std::domain_error("cannot use push_back() with " + type_name());
  3915. }
  3916. // transform null object into an object
  3917. if (is_null())
  3918. {
  3919. m_type = value_t::object;
  3920. m_value = value_t::object;
  3921. assert_invariant();
  3922. }
  3923. // add element to array
  3924. m_value.object->insert(val);
  3925. }
  3926. /*!
  3927. @brief add an object to an object
  3928. @copydoc push_back(const typename object_t::value_type&)
  3929. */
  3930. reference operator+=(const typename object_t::value_type& val)
  3931. {
  3932. push_back(val);
  3933. return *this;
  3934. }
  3935. /*!
  3936. @brief add an object to an object
  3937. This function allows to use `push_back` with an initializer list. In case
  3938. 1. the current value is an object,
  3939. 2. the initializer list @a init contains only two elements, and
  3940. 3. the first element of @a init is a string,
  3941. @a init is converted into an object element and added using
  3942. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  3943. is converted to a JSON value and added using @ref push_back(basic_json&&).
  3944. @param init an initializer list
  3945. @complexity Linear in the size of the initializer list @a init.
  3946. @note This function is required to resolve an ambiguous overload error,
  3947. because pairs like `{"key", "value"}` can be both interpreted as
  3948. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  3949. https://github.com/nlohmann/json/issues/235 for more information.
  3950. @liveexample{The example shows how initializer lists are treated as
  3951. objects when possible.,push_back__initializer_list}
  3952. */
  3953. void push_back(std::initializer_list<basic_json> init)
  3954. {
  3955. if (is_object() and init.size() == 2 and init.begin()->is_string())
  3956. {
  3957. const string_t key = *init.begin();
  3958. push_back(typename object_t::value_type(key, *(init.begin() + 1)));
  3959. }
  3960. else
  3961. {
  3962. push_back(basic_json(init));
  3963. }
  3964. }
  3965. /*!
  3966. @brief add an object to an object
  3967. @copydoc push_back(std::initializer_list<basic_json>)
  3968. */
  3969. reference operator+=(std::initializer_list<basic_json> init)
  3970. {
  3971. push_back(init);
  3972. return *this;
  3973. }
  3974. /*!
  3975. @brief add an object to an array
  3976. Creates a JSON value from the passed parameters @a args to the end of the
  3977. JSON value. If the function is called on a JSON null value, an empty array
  3978. is created before appending the value created from @a args.
  3979. @param[in] args arguments to forward to a constructor of @ref basic_json
  3980. @tparam Args compatible types to create a @ref basic_json object
  3981. @throw std::domain_error when called on a type other than JSON array or
  3982. null; example: `"cannot use emplace_back() with number"`
  3983. @complexity Amortized constant.
  3984. @liveexample{The example shows how `push_back()` can be used to add
  3985. elements to a JSON array. Note how the `null` value was silently converted
  3986. to a JSON array.,emplace_back}
  3987. @since version 2.0.8
  3988. */
  3989. template<class... Args>
  3990. void emplace_back(Args&& ... args)
  3991. {
  3992. // emplace_back only works for null objects or arrays
  3993. if (not(is_null() or is_array()))
  3994. {
  3995. throw std::domain_error("cannot use emplace_back() with " + type_name());
  3996. }
  3997. // transform null object into an array
  3998. if (is_null())
  3999. {
  4000. m_type = value_t::array;
  4001. m_value = value_t::array;
  4002. assert_invariant();
  4003. }
  4004. // add element to array (perfect forwarding)
  4005. m_value.array->emplace_back(std::forward<Args>(args)...);
  4006. }
  4007. /*!
  4008. @brief add an object to an object if key does not exist
  4009. Inserts a new element into a JSON object constructed in-place with the given
  4010. @a args if there is no element with the key in the container. If the
  4011. function is called on a JSON null value, an empty object is created before
  4012. appending the value created from @a args.
  4013. @param[in] args arguments to forward to a constructor of @ref basic_json
  4014. @tparam Args compatible types to create a @ref basic_json object
  4015. @return a pair consisting of an iterator to the inserted element, or the
  4016. already-existing element if no insertion happened, and a bool
  4017. denoting whether the insertion took place.
  4018. @throw std::domain_error when called on a type other than JSON object or
  4019. null; example: `"cannot use emplace() with number"`
  4020. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4021. @liveexample{The example shows how `emplace()` can be used to add elements
  4022. to a JSON object. Note how the `null` value was silently converted to a
  4023. JSON object. Further note how no value is added if there was already one
  4024. value stored with the same key.,emplace}
  4025. @since version 2.0.8
  4026. */
  4027. template<class... Args>
  4028. std::pair<iterator, bool> emplace(Args&& ... args)
  4029. {
  4030. // emplace only works for null objects or arrays
  4031. if (not(is_null() or is_object()))
  4032. {
  4033. throw std::domain_error("cannot use emplace() with " + type_name());
  4034. }
  4035. // transform null object into an object
  4036. if (is_null())
  4037. {
  4038. m_type = value_t::object;
  4039. m_value = value_t::object;
  4040. assert_invariant();
  4041. }
  4042. // add element to array (perfect forwarding)
  4043. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  4044. // create result iterator and set iterator to the result of emplace
  4045. auto it = begin();
  4046. it.m_it.object_iterator = res.first;
  4047. // return pair of iterator and boolean
  4048. return {it, res.second};
  4049. }
  4050. /*!
  4051. @brief inserts element
  4052. Inserts element @a val before iterator @a pos.
  4053. @param[in] pos iterator before which the content will be inserted; may be
  4054. the end() iterator
  4055. @param[in] val element to insert
  4056. @return iterator pointing to the inserted @a val.
  4057. @throw std::domain_error if called on JSON values other than arrays;
  4058. example: `"cannot use insert() with string"`
  4059. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4060. `"iterator does not fit current value"`
  4061. @complexity Constant plus linear in the distance between pos and end of the
  4062. container.
  4063. @liveexample{The example shows how `insert()` is used.,insert}
  4064. @since version 1.0.0
  4065. */
  4066. iterator insert(const_iterator pos, const basic_json& val)
  4067. {
  4068. // insert only works for arrays
  4069. if (is_array())
  4070. {
  4071. // check if iterator pos fits to this JSON value
  4072. if (pos.m_object != this)
  4073. {
  4074. throw std::domain_error("iterator does not fit current value");
  4075. }
  4076. // insert to array and return iterator
  4077. iterator result(this);
  4078. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  4079. return result;
  4080. }
  4081. else
  4082. {
  4083. throw std::domain_error("cannot use insert() with " + type_name());
  4084. }
  4085. }
  4086. /*!
  4087. @brief inserts element
  4088. @copydoc insert(const_iterator, const basic_json&)
  4089. */
  4090. iterator insert(const_iterator pos, basic_json&& val)
  4091. {
  4092. return insert(pos, val);
  4093. }
  4094. /*!
  4095. @brief inserts elements
  4096. Inserts @a cnt copies of @a val before iterator @a pos.
  4097. @param[in] pos iterator before which the content will be inserted; may be
  4098. the end() iterator
  4099. @param[in] cnt number of copies of @a val to insert
  4100. @param[in] val element to insert
  4101. @return iterator pointing to the first element inserted, or @a pos if
  4102. `cnt==0`
  4103. @throw std::domain_error if called on JSON values other than arrays;
  4104. example: `"cannot use insert() with string"`
  4105. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4106. `"iterator does not fit current value"`
  4107. @complexity Linear in @a cnt plus linear in the distance between @a pos
  4108. and end of the container.
  4109. @liveexample{The example shows how `insert()` is used.,insert__count}
  4110. @since version 1.0.0
  4111. */
  4112. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  4113. {
  4114. // insert only works for arrays
  4115. if (is_array())
  4116. {
  4117. // check if iterator pos fits to this JSON value
  4118. if (pos.m_object != this)
  4119. {
  4120. throw std::domain_error("iterator does not fit current value");
  4121. }
  4122. // insert to array and return iterator
  4123. iterator result(this);
  4124. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  4125. return result;
  4126. }
  4127. else
  4128. {
  4129. throw std::domain_error("cannot use insert() with " + type_name());
  4130. }
  4131. }
  4132. /*!
  4133. @brief inserts elements
  4134. Inserts elements from range `[first, last)` before iterator @a pos.
  4135. @param[in] pos iterator before which the content will be inserted; may be
  4136. the end() iterator
  4137. @param[in] first begin of the range of elements to insert
  4138. @param[in] last end of the range of elements to insert
  4139. @throw std::domain_error if called on JSON values other than arrays;
  4140. example: `"cannot use insert() with string"`
  4141. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4142. `"iterator does not fit current value"`
  4143. @throw std::domain_error if @a first and @a last do not belong to the same
  4144. JSON value; example: `"iterators do not fit"`
  4145. @throw std::domain_error if @a first or @a last are iterators into
  4146. container for which insert is called; example: `"passed iterators may not
  4147. belong to container"`
  4148. @return iterator pointing to the first element inserted, or @a pos if
  4149. `first==last`
  4150. @complexity Linear in `std::distance(first, last)` plus linear in the
  4151. distance between @a pos and end of the container.
  4152. @liveexample{The example shows how `insert()` is used.,insert__range}
  4153. @since version 1.0.0
  4154. */
  4155. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  4156. {
  4157. // insert only works for arrays
  4158. if (not is_array())
  4159. {
  4160. throw std::domain_error("cannot use insert() with " + type_name());
  4161. }
  4162. // check if iterator pos fits to this JSON value
  4163. if (pos.m_object != this)
  4164. {
  4165. throw std::domain_error("iterator does not fit current value");
  4166. }
  4167. // check if range iterators belong to the same JSON object
  4168. if (first.m_object != last.m_object)
  4169. {
  4170. throw std::domain_error("iterators do not fit");
  4171. }
  4172. if (first.m_object == this or last.m_object == this)
  4173. {
  4174. throw std::domain_error("passed iterators may not belong to container");
  4175. }
  4176. // insert to array and return iterator
  4177. iterator result(this);
  4178. result.m_it.array_iterator = m_value.array->insert(
  4179. pos.m_it.array_iterator,
  4180. first.m_it.array_iterator,
  4181. last.m_it.array_iterator);
  4182. return result;
  4183. }
  4184. /*!
  4185. @brief inserts elements
  4186. Inserts elements from initializer list @a ilist before iterator @a pos.
  4187. @param[in] pos iterator before which the content will be inserted; may be
  4188. the end() iterator
  4189. @param[in] ilist initializer list to insert the values from
  4190. @throw std::domain_error if called on JSON values other than arrays;
  4191. example: `"cannot use insert() with string"`
  4192. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4193. `"iterator does not fit current value"`
  4194. @return iterator pointing to the first element inserted, or @a pos if
  4195. `ilist` is empty
  4196. @complexity Linear in `ilist.size()` plus linear in the distance between
  4197. @a pos and end of the container.
  4198. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  4199. @since version 1.0.0
  4200. */
  4201. iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
  4202. {
  4203. // insert only works for arrays
  4204. if (not is_array())
  4205. {
  4206. throw std::domain_error("cannot use insert() with " + type_name());
  4207. }
  4208. // check if iterator pos fits to this JSON value
  4209. if (pos.m_object != this)
  4210. {
  4211. throw std::domain_error("iterator does not fit current value");
  4212. }
  4213. // insert to array and return iterator
  4214. iterator result(this);
  4215. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
  4216. return result;
  4217. }
  4218. /*!
  4219. @brief exchanges the values
  4220. Exchanges the contents of the JSON value with those of @a other. Does not
  4221. invoke any move, copy, or swap operations on individual elements. All
  4222. iterators and references remain valid. The past-the-end iterator is
  4223. invalidated.
  4224. @param[in,out] other JSON value to exchange the contents with
  4225. @complexity Constant.
  4226. @liveexample{The example below shows how JSON values can be swapped with
  4227. `swap()`.,swap__reference}
  4228. @since version 1.0.0
  4229. */
  4230. void swap(reference other) noexcept (
  4231. std::is_nothrow_move_constructible<value_t>::value and
  4232. std::is_nothrow_move_assignable<value_t>::value and
  4233. std::is_nothrow_move_constructible<json_value>::value and
  4234. std::is_nothrow_move_assignable<json_value>::value
  4235. )
  4236. {
  4237. std::swap(m_type, other.m_type);
  4238. std::swap(m_value, other.m_value);
  4239. assert_invariant();
  4240. }
  4241. /*!
  4242. @brief exchanges the values
  4243. Exchanges the contents of a JSON array with those of @a other. Does not
  4244. invoke any move, copy, or swap operations on individual elements. All
  4245. iterators and references remain valid. The past-the-end iterator is
  4246. invalidated.
  4247. @param[in,out] other array to exchange the contents with
  4248. @throw std::domain_error when JSON value is not an array; example: `"cannot
  4249. use swap() with string"`
  4250. @complexity Constant.
  4251. @liveexample{The example below shows how arrays can be swapped with
  4252. `swap()`.,swap__array_t}
  4253. @since version 1.0.0
  4254. */
  4255. void swap(array_t& other)
  4256. {
  4257. // swap only works for arrays
  4258. if (is_array())
  4259. {
  4260. std::swap(*(m_value.array), other);
  4261. }
  4262. else
  4263. {
  4264. throw std::domain_error("cannot use swap() with " + type_name());
  4265. }
  4266. }
  4267. /*!
  4268. @brief exchanges the values
  4269. Exchanges the contents of a JSON object with those of @a other. Does not
  4270. invoke any move, copy, or swap operations on individual elements. All
  4271. iterators and references remain valid. The past-the-end iterator is
  4272. invalidated.
  4273. @param[in,out] other object to exchange the contents with
  4274. @throw std::domain_error when JSON value is not an object; example:
  4275. `"cannot use swap() with string"`
  4276. @complexity Constant.
  4277. @liveexample{The example below shows how objects can be swapped with
  4278. `swap()`.,swap__object_t}
  4279. @since version 1.0.0
  4280. */
  4281. void swap(object_t& other)
  4282. {
  4283. // swap only works for objects
  4284. if (is_object())
  4285. {
  4286. std::swap(*(m_value.object), other);
  4287. }
  4288. else
  4289. {
  4290. throw std::domain_error("cannot use swap() with " + type_name());
  4291. }
  4292. }
  4293. /*!
  4294. @brief exchanges the values
  4295. Exchanges the contents of a JSON string with those of @a other. Does not
  4296. invoke any move, copy, or swap operations on individual elements. All
  4297. iterators and references remain valid. The past-the-end iterator is
  4298. invalidated.
  4299. @param[in,out] other string to exchange the contents with
  4300. @throw std::domain_error when JSON value is not a string; example: `"cannot
  4301. use swap() with boolean"`
  4302. @complexity Constant.
  4303. @liveexample{The example below shows how strings can be swapped with
  4304. `swap()`.,swap__string_t}
  4305. @since version 1.0.0
  4306. */
  4307. void swap(string_t& other)
  4308. {
  4309. // swap only works for strings
  4310. if (is_string())
  4311. {
  4312. std::swap(*(m_value.string), other);
  4313. }
  4314. else
  4315. {
  4316. throw std::domain_error("cannot use swap() with " + type_name());
  4317. }
  4318. }
  4319. /// @}
  4320. //////////////////////////////////////////
  4321. // lexicographical comparison operators //
  4322. //////////////////////////////////////////
  4323. /// @name lexicographical comparison operators
  4324. /// @{
  4325. private:
  4326. /*!
  4327. @brief comparison operator for JSON types
  4328. Returns an ordering that is similar to Python:
  4329. - order: null < boolean < number < object < array < string
  4330. - furthermore, each type is not smaller than itself
  4331. @since version 1.0.0
  4332. */
  4333. friend bool operator<(const value_t lhs, const value_t rhs) noexcept
  4334. {
  4335. static constexpr std::array<uint8_t, 8> order = {{
  4336. 0, // null
  4337. 3, // object
  4338. 4, // array
  4339. 5, // string
  4340. 1, // boolean
  4341. 2, // integer
  4342. 2, // unsigned
  4343. 2, // float
  4344. }
  4345. };
  4346. // discarded values are not comparable
  4347. if (lhs == value_t::discarded or rhs == value_t::discarded)
  4348. {
  4349. return false;
  4350. }
  4351. return order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)];
  4352. }
  4353. public:
  4354. /*!
  4355. @brief comparison: equal
  4356. Compares two JSON values for equality according to the following rules:
  4357. - Two JSON values are equal if (1) they are from the same type and (2)
  4358. their stored values are the same.
  4359. - Integer and floating-point numbers are automatically converted before
  4360. comparison. Floating-point numbers are compared indirectly: two
  4361. floating-point numbers `f1` and `f2` are considered equal if neither
  4362. `f1 > f2` nor `f2 > f1` holds.
  4363. - Two JSON null values are equal.
  4364. @param[in] lhs first JSON value to consider
  4365. @param[in] rhs second JSON value to consider
  4366. @return whether the values @a lhs and @a rhs are equal
  4367. @complexity Linear.
  4368. @liveexample{The example demonstrates comparing several JSON
  4369. types.,operator__equal}
  4370. @since version 1.0.0
  4371. */
  4372. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  4373. {
  4374. const auto lhs_type = lhs.type();
  4375. const auto rhs_type = rhs.type();
  4376. if (lhs_type == rhs_type)
  4377. {
  4378. switch (lhs_type)
  4379. {
  4380. case value_t::array:
  4381. {
  4382. return *lhs.m_value.array == *rhs.m_value.array;
  4383. }
  4384. case value_t::object:
  4385. {
  4386. return *lhs.m_value.object == *rhs.m_value.object;
  4387. }
  4388. case value_t::null:
  4389. {
  4390. return true;
  4391. }
  4392. case value_t::string:
  4393. {
  4394. return *lhs.m_value.string == *rhs.m_value.string;
  4395. }
  4396. case value_t::boolean:
  4397. {
  4398. return lhs.m_value.boolean == rhs.m_value.boolean;
  4399. }
  4400. case value_t::number_integer:
  4401. {
  4402. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  4403. }
  4404. case value_t::number_unsigned:
  4405. {
  4406. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  4407. }
  4408. case value_t::number_float:
  4409. {
  4410. return lhs.m_value.number_float == rhs.m_value.number_float;
  4411. }
  4412. default:
  4413. {
  4414. return false;
  4415. }
  4416. }
  4417. }
  4418. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4419. {
  4420. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  4421. }
  4422. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  4423. {
  4424. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  4425. }
  4426. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  4427. {
  4428. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  4429. }
  4430. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  4431. {
  4432. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  4433. }
  4434. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  4435. {
  4436. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  4437. }
  4438. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  4439. {
  4440. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  4441. }
  4442. return false;
  4443. }
  4444. /*!
  4445. @brief comparison: equal
  4446. The functions compares the given JSON value against a null pointer. As the
  4447. null pointer can be used to initialize a JSON value to null, a comparison
  4448. of JSON value @a v with a null pointer should be equivalent to call
  4449. `v.is_null()`.
  4450. @param[in] v JSON value to consider
  4451. @return whether @a v is null
  4452. @complexity Constant.
  4453. @liveexample{The example compares several JSON types to the null pointer.
  4454. ,operator__equal__nullptr_t}
  4455. @since version 1.0.0
  4456. */
  4457. friend bool operator==(const_reference v, std::nullptr_t) noexcept
  4458. {
  4459. return v.is_null();
  4460. }
  4461. /*!
  4462. @brief comparison: equal
  4463. @copydoc operator==(const_reference, std::nullptr_t)
  4464. */
  4465. friend bool operator==(std::nullptr_t, const_reference v) noexcept
  4466. {
  4467. return v.is_null();
  4468. }
  4469. /*!
  4470. @brief comparison: not equal
  4471. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  4472. @param[in] lhs first JSON value to consider
  4473. @param[in] rhs second JSON value to consider
  4474. @return whether the values @a lhs and @a rhs are not equal
  4475. @complexity Linear.
  4476. @liveexample{The example demonstrates comparing several JSON
  4477. types.,operator__notequal}
  4478. @since version 1.0.0
  4479. */
  4480. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  4481. {
  4482. return not (lhs == rhs);
  4483. }
  4484. /*!
  4485. @brief comparison: not equal
  4486. The functions compares the given JSON value against a null pointer. As the
  4487. null pointer can be used to initialize a JSON value to null, a comparison
  4488. of JSON value @a v with a null pointer should be equivalent to call
  4489. `not v.is_null()`.
  4490. @param[in] v JSON value to consider
  4491. @return whether @a v is not null
  4492. @complexity Constant.
  4493. @liveexample{The example compares several JSON types to the null pointer.
  4494. ,operator__notequal__nullptr_t}
  4495. @since version 1.0.0
  4496. */
  4497. friend bool operator!=(const_reference v, std::nullptr_t) noexcept
  4498. {
  4499. return not v.is_null();
  4500. }
  4501. /*!
  4502. @brief comparison: not equal
  4503. @copydoc operator!=(const_reference, std::nullptr_t)
  4504. */
  4505. friend bool operator!=(std::nullptr_t, const_reference v) noexcept
  4506. {
  4507. return not v.is_null();
  4508. }
  4509. /*!
  4510. @brief comparison: less than
  4511. Compares whether one JSON value @a lhs is less than another JSON value @a
  4512. rhs according to the following rules:
  4513. - If @a lhs and @a rhs have the same type, the values are compared using
  4514. the default `<` operator.
  4515. - Integer and floating-point numbers are automatically converted before
  4516. comparison
  4517. - In case @a lhs and @a rhs have different types, the values are ignored
  4518. and the order of the types is considered, see
  4519. @ref operator<(const value_t, const value_t).
  4520. @param[in] lhs first JSON value to consider
  4521. @param[in] rhs second JSON value to consider
  4522. @return whether @a lhs is less than @a rhs
  4523. @complexity Linear.
  4524. @liveexample{The example demonstrates comparing several JSON
  4525. types.,operator__less}
  4526. @since version 1.0.0
  4527. */
  4528. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  4529. {
  4530. const auto lhs_type = lhs.type();
  4531. const auto rhs_type = rhs.type();
  4532. if (lhs_type == rhs_type)
  4533. {
  4534. switch (lhs_type)
  4535. {
  4536. case value_t::array:
  4537. {
  4538. return *lhs.m_value.array < *rhs.m_value.array;
  4539. }
  4540. case value_t::object:
  4541. {
  4542. return *lhs.m_value.object < *rhs.m_value.object;
  4543. }
  4544. case value_t::null:
  4545. {
  4546. return false;
  4547. }
  4548. case value_t::string:
  4549. {
  4550. return *lhs.m_value.string < *rhs.m_value.string;
  4551. }
  4552. case value_t::boolean:
  4553. {
  4554. return lhs.m_value.boolean < rhs.m_value.boolean;
  4555. }
  4556. case value_t::number_integer:
  4557. {
  4558. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  4559. }
  4560. case value_t::number_unsigned:
  4561. {
  4562. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  4563. }
  4564. case value_t::number_float:
  4565. {
  4566. return lhs.m_value.number_float < rhs.m_value.number_float;
  4567. }
  4568. default:
  4569. {
  4570. return false;
  4571. }
  4572. }
  4573. }
  4574. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4575. {
  4576. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  4577. }
  4578. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  4579. {
  4580. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  4581. }
  4582. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  4583. {
  4584. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  4585. }
  4586. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  4587. {
  4588. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  4589. }
  4590. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  4591. {
  4592. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  4593. }
  4594. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  4595. {
  4596. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  4597. }
  4598. // We only reach this line if we cannot compare values. In that case,
  4599. // we compare types. Note we have to call the operator explicitly,
  4600. // because MSVC has problems otherwise.
  4601. return operator<(lhs_type, rhs_type);
  4602. }
  4603. /*!
  4604. @brief comparison: less than or equal
  4605. Compares whether one JSON value @a lhs is less than or equal to another
  4606. JSON value by calculating `not (rhs < lhs)`.
  4607. @param[in] lhs first JSON value to consider
  4608. @param[in] rhs second JSON value to consider
  4609. @return whether @a lhs is less than or equal to @a rhs
  4610. @complexity Linear.
  4611. @liveexample{The example demonstrates comparing several JSON
  4612. types.,operator__greater}
  4613. @since version 1.0.0
  4614. */
  4615. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  4616. {
  4617. return not (rhs < lhs);
  4618. }
  4619. /*!
  4620. @brief comparison: greater than
  4621. Compares whether one JSON value @a lhs is greater than another
  4622. JSON value by calculating `not (lhs <= rhs)`.
  4623. @param[in] lhs first JSON value to consider
  4624. @param[in] rhs second JSON value to consider
  4625. @return whether @a lhs is greater than to @a rhs
  4626. @complexity Linear.
  4627. @liveexample{The example demonstrates comparing several JSON
  4628. types.,operator__lessequal}
  4629. @since version 1.0.0
  4630. */
  4631. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  4632. {
  4633. return not (lhs <= rhs);
  4634. }
  4635. /*!
  4636. @brief comparison: greater than or equal
  4637. Compares whether one JSON value @a lhs is greater than or equal to another
  4638. JSON value by calculating `not (lhs < rhs)`.
  4639. @param[in] lhs first JSON value to consider
  4640. @param[in] rhs second JSON value to consider
  4641. @return whether @a lhs is greater than or equal to @a rhs
  4642. @complexity Linear.
  4643. @liveexample{The example demonstrates comparing several JSON
  4644. types.,operator__greaterequal}
  4645. @since version 1.0.0
  4646. */
  4647. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  4648. {
  4649. return not (lhs < rhs);
  4650. }
  4651. /// @}
  4652. ///////////////////
  4653. // serialization //
  4654. ///////////////////
  4655. /// @name serialization
  4656. /// @{
  4657. /*!
  4658. @brief serialize to stream
  4659. Serialize the given JSON value @a j to the output stream @a o. The JSON
  4660. value will be serialized using the @ref dump member function. The
  4661. indentation of the output can be controlled with the member variable
  4662. `width` of the output stream @a o. For instance, using the manipulator
  4663. `std::setw(4)` on @a o sets the indentation level to `4` and the
  4664. serialization result is the same as calling `dump(4)`.
  4665. @note During serializaion, the locale and the precision of the output
  4666. stream @a o are changed. The original values are restored when the
  4667. function returns.
  4668. @param[in,out] o stream to serialize to
  4669. @param[in] j JSON value to serialize
  4670. @return the stream @a o
  4671. @complexity Linear.
  4672. @liveexample{The example below shows the serialization with different
  4673. parameters to `width` to adjust the indentation level.,operator_serialize}
  4674. @since version 1.0.0
  4675. */
  4676. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  4677. {
  4678. // read width member and use it as indentation parameter if nonzero
  4679. const bool pretty_print = (o.width() > 0);
  4680. const auto indentation = (pretty_print ? o.width() : 0);
  4681. // reset width to 0 for subsequent calls to this stream
  4682. o.width(0);
  4683. // fix locale problems
  4684. const auto old_locale = o.imbue(std::locale::classic());
  4685. // set precision
  4686. // 6, 15 or 16 digits of precision allows round-trip IEEE 754
  4687. // string->float->string, string->double->string or string->long
  4688. // double->string; to be safe, we read this value from
  4689. // std::numeric_limits<number_float_t>::digits10
  4690. const auto old_precision = o.precision(std::numeric_limits<double>::digits10);
  4691. // do the actual serialization
  4692. j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
  4693. // reset locale and precision
  4694. o.imbue(old_locale);
  4695. o.precision(old_precision);
  4696. return o;
  4697. }
  4698. /*!
  4699. @brief serialize to stream
  4700. @copydoc operator<<(std::ostream&, const basic_json&)
  4701. */
  4702. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  4703. {
  4704. return o << j;
  4705. }
  4706. /// @}
  4707. /////////////////////
  4708. // deserialization //
  4709. /////////////////////
  4710. /// @name deserialization
  4711. /// @{
  4712. /*!
  4713. @brief deserialize from an array
  4714. This function reads from an array of 1-byte values.
  4715. @pre Each element of the container has a size of 1 byte. Violating this
  4716. precondition yields undefined behavior. **This precondition is enforced
  4717. with a static assertion.**
  4718. @param[in] array array to read from
  4719. @param[in] cb a parser callback function of type @ref parser_callback_t
  4720. which is used to control the deserialization by filtering unwanted values
  4721. (optional)
  4722. @return result of the deserialization
  4723. @complexity Linear in the length of the input. The parser is a predictive
  4724. LL(1) parser. The complexity can be higher if the parser callback function
  4725. @a cb has a super-linear complexity.
  4726. @note A UTF-8 byte order mark is silently ignored.
  4727. @liveexample{The example below demonstrates the `parse()` function reading
  4728. from an array.,parse__array__parser_callback_t}
  4729. @since version 2.0.3
  4730. */
  4731. template<class T, std::size_t N>
  4732. static basic_json parse(T (&array)[N],
  4733. const parser_callback_t cb = nullptr)
  4734. {
  4735. // delegate the call to the iterator-range parse overload
  4736. return parse(std::begin(array), std::end(array), cb);
  4737. }
  4738. /*!
  4739. @brief deserialize from string literal
  4740. @tparam CharT character/literal type with size of 1 byte
  4741. @param[in] s string literal to read a serialized JSON value from
  4742. @param[in] cb a parser callback function of type @ref parser_callback_t
  4743. which is used to control the deserialization by filtering unwanted values
  4744. (optional)
  4745. @return result of the deserialization
  4746. @complexity Linear in the length of the input. The parser is a predictive
  4747. LL(1) parser. The complexity can be higher if the parser callback function
  4748. @a cb has a super-linear complexity.
  4749. @note A UTF-8 byte order mark is silently ignored.
  4750. @note String containers like `std::string` or @ref string_t can be parsed
  4751. with @ref parse(const ContiguousContainer&, const parser_callback_t)
  4752. @liveexample{The example below demonstrates the `parse()` function with
  4753. and without callback function.,parse__string__parser_callback_t}
  4754. @sa @ref parse(std::istream&, const parser_callback_t) for a version that
  4755. reads from an input stream
  4756. @since version 1.0.0 (originally for @ref string_t)
  4757. */
  4758. template<typename CharT, typename std::enable_if<
  4759. std::is_pointer<CharT>::value and
  4760. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  4761. sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0>
  4762. static basic_json parse(const CharT s,
  4763. const parser_callback_t cb = nullptr)
  4764. {
  4765. return parser(reinterpret_cast<const char*>(s), cb).parse();
  4766. }
  4767. /*!
  4768. @brief deserialize from stream
  4769. @param[in,out] i stream to read a serialized JSON value from
  4770. @param[in] cb a parser callback function of type @ref parser_callback_t
  4771. which is used to control the deserialization by filtering unwanted values
  4772. (optional)
  4773. @return result of the deserialization
  4774. @complexity Linear in the length of the input. The parser is a predictive
  4775. LL(1) parser. The complexity can be higher if the parser callback function
  4776. @a cb has a super-linear complexity.
  4777. @note A UTF-8 byte order mark is silently ignored.
  4778. @liveexample{The example below demonstrates the `parse()` function with
  4779. and without callback function.,parse__istream__parser_callback_t}
  4780. @sa @ref parse(const CharT, const parser_callback_t) for a version
  4781. that reads from a string
  4782. @since version 1.0.0
  4783. */
  4784. static basic_json parse(std::istream& i,
  4785. const parser_callback_t cb = nullptr)
  4786. {
  4787. return parser(i, cb).parse();
  4788. }
  4789. /*!
  4790. @copydoc parse(std::istream&, const parser_callback_t)
  4791. */
  4792. static basic_json parse(std::istream&& i,
  4793. const parser_callback_t cb = nullptr)
  4794. {
  4795. return parser(i, cb).parse();
  4796. }
  4797. /*!
  4798. @brief deserialize from an iterator range with contiguous storage
  4799. This function reads from an iterator range of a container with contiguous
  4800. storage of 1-byte values. Compatible container types include
  4801. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  4802. `std::initializer_list`. Furthermore, C-style arrays can be used with
  4803. `std::begin()`/`std::end()`. User-defined containers can be used as long
  4804. as they implement random-access iterators and a contiguous storage.
  4805. @pre The iterator range is contiguous. Violating this precondition yields
  4806. undefined behavior. **This precondition is enforced with an assertion.**
  4807. @pre Each element in the range has a size of 1 byte. Violating this
  4808. precondition yields undefined behavior. **This precondition is enforced
  4809. with a static assertion.**
  4810. @warning There is no way to enforce all preconditions at compile-time. If
  4811. the function is called with noncompliant iterators and with
  4812. assertions switched off, the behavior is undefined and will most
  4813. likely yield segmentation violation.
  4814. @tparam IteratorType iterator of container with contiguous storage
  4815. @param[in] first begin of the range to parse (included)
  4816. @param[in] last end of the range to parse (excluded)
  4817. @param[in] cb a parser callback function of type @ref parser_callback_t
  4818. which is used to control the deserialization by filtering unwanted values
  4819. (optional)
  4820. @return result of the deserialization
  4821. @complexity Linear in the length of the input. The parser is a predictive
  4822. LL(1) parser. The complexity can be higher if the parser callback function
  4823. @a cb has a super-linear complexity.
  4824. @note A UTF-8 byte order mark is silently ignored.
  4825. @liveexample{The example below demonstrates the `parse()` function reading
  4826. from an iterator range.,parse__iteratortype__parser_callback_t}
  4827. @since version 2.0.3
  4828. */
  4829. template<class IteratorType, typename std::enable_if<
  4830. std::is_base_of<
  4831. std::random_access_iterator_tag,
  4832. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  4833. static basic_json parse(IteratorType first, IteratorType last,
  4834. const parser_callback_t cb = nullptr)
  4835. {
  4836. // assertion to check that the iterator range is indeed contiguous,
  4837. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  4838. assert(std::accumulate(first, last, std::make_pair<bool, int>(true, 0),
  4839. [&first](std::pair<bool, int> res, decltype(*first) val)
  4840. {
  4841. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  4842. return res;
  4843. }).first);
  4844. // assertion to check that each element is 1 byte long
  4845. static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  4846. "each element in the iterator range must have the size of 1 byte");
  4847. // if iterator range is empty, create a parser with an empty string
  4848. // to generate "unexpected EOF" error message
  4849. if (std::distance(first, last) <= 0)
  4850. {
  4851. return parser("").parse();
  4852. }
  4853. return parser(first, last, cb).parse();
  4854. }
  4855. /*!
  4856. @brief deserialize from a container with contiguous storage
  4857. This function reads from a container with contiguous storage of 1-byte
  4858. values. Compatible container types include `std::vector`, `std::string`,
  4859. `std::array`, and `std::initializer_list`. User-defined containers can be
  4860. used as long as they implement random-access iterators and a contiguous
  4861. storage.
  4862. @pre The container storage is contiguous. Violating this precondition
  4863. yields undefined behavior. **This precondition is enforced with an
  4864. assertion.**
  4865. @pre Each element of the container has a size of 1 byte. Violating this
  4866. precondition yields undefined behavior. **This precondition is enforced
  4867. with a static assertion.**
  4868. @warning There is no way to enforce all preconditions at compile-time. If
  4869. the function is called with a noncompliant container and with
  4870. assertions switched off, the behavior is undefined and will most
  4871. likely yield segmentation violation.
  4872. @tparam ContiguousContainer container type with contiguous storage
  4873. @param[in] c container to read from
  4874. @param[in] cb a parser callback function of type @ref parser_callback_t
  4875. which is used to control the deserialization by filtering unwanted values
  4876. (optional)
  4877. @return result of the deserialization
  4878. @complexity Linear in the length of the input. The parser is a predictive
  4879. LL(1) parser. The complexity can be higher if the parser callback function
  4880. @a cb has a super-linear complexity.
  4881. @note A UTF-8 byte order mark is silently ignored.
  4882. @liveexample{The example below demonstrates the `parse()` function reading
  4883. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  4884. @since version 2.0.3
  4885. */
  4886. template<class ContiguousContainer, typename std::enable_if<
  4887. not std::is_pointer<ContiguousContainer>::value and
  4888. std::is_base_of<
  4889. std::random_access_iterator_tag,
  4890. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
  4891. , int>::type = 0>
  4892. static basic_json parse(const ContiguousContainer& c,
  4893. const parser_callback_t cb = nullptr)
  4894. {
  4895. // delegate the call to the iterator-range parse overload
  4896. return parse(std::begin(c), std::end(c), cb);
  4897. }
  4898. /*!
  4899. @brief deserialize from stream
  4900. Deserializes an input stream to a JSON value.
  4901. @param[in,out] i input stream to read a serialized JSON value from
  4902. @param[in,out] j JSON value to write the deserialized input to
  4903. @throw std::invalid_argument in case of parse errors
  4904. @complexity Linear in the length of the input. The parser is a predictive
  4905. LL(1) parser.
  4906. @note A UTF-8 byte order mark is silently ignored.
  4907. @liveexample{The example below shows how a JSON value is constructed by
  4908. reading a serialization from a stream.,operator_deserialize}
  4909. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  4910. parser callback function to filter values while parsing
  4911. @since version 1.0.0
  4912. */
  4913. friend std::istream& operator<<(basic_json& j, std::istream& i)
  4914. {
  4915. j = parser(i).parse();
  4916. return i;
  4917. }
  4918. /*!
  4919. @brief deserialize from stream
  4920. @copydoc operator<<(basic_json&, std::istream&)
  4921. */
  4922. friend std::istream& operator>>(std::istream& i, basic_json& j)
  4923. {
  4924. j = parser(i).parse();
  4925. return i;
  4926. }
  4927. /// @}
  4928. //////////////////////////////////////////
  4929. // binary serialization/deserialization //
  4930. //////////////////////////////////////////
  4931. /// @name binary serialization/deserialization support
  4932. /// @{
  4933. private:
  4934. template<typename T>
  4935. static void add_to_vector(std::vector<uint8_t>& vec, size_t bytes, const T number)
  4936. {
  4937. assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8);
  4938. switch (bytes)
  4939. {
  4940. case 8:
  4941. {
  4942. vec.push_back(static_cast<uint8_t>((number >> 070) & 0xff));
  4943. vec.push_back(static_cast<uint8_t>((number >> 060) & 0xff));
  4944. vec.push_back(static_cast<uint8_t>((number >> 050) & 0xff));
  4945. vec.push_back(static_cast<uint8_t>((number >> 040) & 0xff));
  4946. // intentional fall-through
  4947. }
  4948. case 4:
  4949. {
  4950. vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff));
  4951. vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff));
  4952. // intentional fall-through
  4953. }
  4954. case 2:
  4955. {
  4956. vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
  4957. // intentional fall-through
  4958. }
  4959. case 1:
  4960. {
  4961. vec.push_back(static_cast<uint8_t>(number & 0xff));
  4962. break;
  4963. }
  4964. }
  4965. }
  4966. /*!
  4967. @brief take sufficient bytes from a vector to fill an integer variable
  4968. In the context of binary serialization formats, we need to read several
  4969. bytes from a byte vector and combine them to multi-byte integral data
  4970. types.
  4971. @param[in] vec byte vector to read from
  4972. @param[in] current_index the position in the vector after which to read
  4973. @return the next sizeof(T) bytes from @a vec, in reverse order as T
  4974. @tparam T the integral return type
  4975. @throw std::out_of_range if there are less than sizeof(T)+1 bytes in the
  4976. vector @a vec to read
  4977. In the for loop, the bytes from the vector are copied in reverse order into
  4978. the return value. In the figures below, let sizeof(T)=4 and `i` be the loop
  4979. variable.
  4980. Precondition:
  4981. vec: | | | a | b | c | d | T: | | | | |
  4982. ^ ^ ^ ^
  4983. current_index i ptr sizeof(T)
  4984. Postcondition:
  4985. vec: | | | a | b | c | d | T: | d | c | b | a |
  4986. ^ ^ ^
  4987. | i ptr
  4988. current_index
  4989. @sa Code adapted from <http://stackoverflow.com/a/41031865/266378>.
  4990. */
  4991. template<typename T>
  4992. static T get_from_vector(const std::vector<uint8_t>& vec, const size_t current_index)
  4993. {
  4994. if (current_index + sizeof(T) + 1 > vec.size())
  4995. {
  4996. throw std::out_of_range("cannot read " + std::to_string(sizeof(T)) + " bytes from vector");
  4997. }
  4998. T result;
  4999. uint8_t* ptr = reinterpret_cast<uint8_t*>(&result);
  5000. for (size_t i = 0; i < sizeof(T); ++i)
  5001. {
  5002. *ptr++ = vec[current_index + sizeof(T) - i];
  5003. }
  5004. return result;
  5005. }
  5006. /*!
  5007. @brief create a MessagePack serialization of a given JSON value
  5008. This is a straightforward implementation of the MessagePack specification.
  5009. @param[in] j JSON value to serialize
  5010. @param[in,out] v byte vector to write the serialization to
  5011. @sa https://github.com/msgpack/msgpack/blob/master/spec.md
  5012. */
  5013. static void to_msgpack_internal(const basic_json& j, std::vector<uint8_t>& v)
  5014. {
  5015. switch (j.type())
  5016. {
  5017. case value_t::null:
  5018. {
  5019. // nil
  5020. v.push_back(0xc0);
  5021. break;
  5022. }
  5023. case value_t::boolean:
  5024. {
  5025. // true and false
  5026. v.push_back(j.m_value.boolean ? 0xc3 : 0xc2);
  5027. break;
  5028. }
  5029. case value_t::number_integer:
  5030. {
  5031. if (j.m_value.number_integer >= 0)
  5032. {
  5033. // MessagePack does not differentiate between positive
  5034. // signed integers and unsigned integers. Therefore, we used
  5035. // the code from the value_t::number_unsigned case here.
  5036. if (j.m_value.number_unsigned < 128)
  5037. {
  5038. // positive fixnum
  5039. add_to_vector(v, 1, j.m_value.number_unsigned);
  5040. }
  5041. else if (j.m_value.number_unsigned <= UINT8_MAX)
  5042. {
  5043. // uint 8
  5044. v.push_back(0xcc);
  5045. add_to_vector(v, 1, j.m_value.number_unsigned);
  5046. }
  5047. else if (j.m_value.number_unsigned <= UINT16_MAX)
  5048. {
  5049. // uint 16
  5050. v.push_back(0xcd);
  5051. add_to_vector(v, 2, j.m_value.number_unsigned);
  5052. }
  5053. else if (j.m_value.number_unsigned <= UINT32_MAX)
  5054. {
  5055. // uint 32
  5056. v.push_back(0xce);
  5057. add_to_vector(v, 4, j.m_value.number_unsigned);
  5058. }
  5059. else if (j.m_value.number_unsigned <= UINT64_MAX)
  5060. {
  5061. // uint 64
  5062. v.push_back(0xcf);
  5063. add_to_vector(v, 8, j.m_value.number_unsigned);
  5064. }
  5065. }
  5066. else
  5067. {
  5068. if (j.m_value.number_integer >= -32)
  5069. {
  5070. // negative fixnum
  5071. add_to_vector(v, 1, j.m_value.number_integer);
  5072. }
  5073. else if (j.m_value.number_integer >= INT8_MIN and j.m_value.number_integer <= INT8_MAX)
  5074. {
  5075. // int 8
  5076. v.push_back(0xd0);
  5077. add_to_vector(v, 1, j.m_value.number_integer);
  5078. }
  5079. else if (j.m_value.number_integer >= INT16_MIN and j.m_value.number_integer <= INT16_MAX)
  5080. {
  5081. // int 16
  5082. v.push_back(0xd1);
  5083. add_to_vector(v, 2, j.m_value.number_integer);
  5084. }
  5085. else if (j.m_value.number_integer >= INT32_MIN and j.m_value.number_integer <= INT32_MAX)
  5086. {
  5087. // int 32
  5088. v.push_back(0xd2);
  5089. add_to_vector(v, 4, j.m_value.number_integer);
  5090. }
  5091. else if (j.m_value.number_integer >= INT64_MIN and j.m_value.number_integer <= INT64_MAX)
  5092. {
  5093. // int 64
  5094. v.push_back(0xd3);
  5095. add_to_vector(v, 8, j.m_value.number_integer);
  5096. }
  5097. }
  5098. break;
  5099. }
  5100. case value_t::number_unsigned:
  5101. {
  5102. if (j.m_value.number_unsigned < 128)
  5103. {
  5104. // positive fixnum
  5105. add_to_vector(v, 1, j.m_value.number_unsigned);
  5106. }
  5107. else if (j.m_value.number_unsigned <= UINT8_MAX)
  5108. {
  5109. // uint 8
  5110. v.push_back(0xcc);
  5111. add_to_vector(v, 1, j.m_value.number_unsigned);
  5112. }
  5113. else if (j.m_value.number_unsigned <= UINT16_MAX)
  5114. {
  5115. // uint 16
  5116. v.push_back(0xcd);
  5117. add_to_vector(v, 2, j.m_value.number_unsigned);
  5118. }
  5119. else if (j.m_value.number_unsigned <= UINT32_MAX)
  5120. {
  5121. // uint 32
  5122. v.push_back(0xce);
  5123. add_to_vector(v, 4, j.m_value.number_unsigned);
  5124. }
  5125. else if (j.m_value.number_unsigned <= UINT64_MAX)
  5126. {
  5127. // uint 64
  5128. v.push_back(0xcf);
  5129. add_to_vector(v, 8, j.m_value.number_unsigned);
  5130. }
  5131. break;
  5132. }
  5133. case value_t::number_float:
  5134. {
  5135. // float 64
  5136. v.push_back(0xcb);
  5137. const uint8_t* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float));
  5138. for (size_t i = 0; i < 8; ++i)
  5139. {
  5140. v.push_back(helper[7 - i]);
  5141. }
  5142. break;
  5143. }
  5144. case value_t::string:
  5145. {
  5146. const auto N = j.m_value.string->size();
  5147. if (N <= 31)
  5148. {
  5149. // fixstr
  5150. v.push_back(static_cast<uint8_t>(0xa0 | N));
  5151. }
  5152. else if (N <= 255)
  5153. {
  5154. // str 8
  5155. v.push_back(0xd9);
  5156. add_to_vector(v, 1, N);
  5157. }
  5158. else if (N <= 65535)
  5159. {
  5160. // str 16
  5161. v.push_back(0xda);
  5162. add_to_vector(v, 2, N);
  5163. }
  5164. else if (N <= 4294967295)
  5165. {
  5166. // str 32
  5167. v.push_back(0xdb);
  5168. add_to_vector(v, 4, N);
  5169. }
  5170. // append string
  5171. std::copy(j.m_value.string->begin(), j.m_value.string->end(),
  5172. std::back_inserter(v));
  5173. break;
  5174. }
  5175. case value_t::array:
  5176. {
  5177. const auto N = j.m_value.array->size();
  5178. if (N <= 15)
  5179. {
  5180. // fixarray
  5181. v.push_back(static_cast<uint8_t>(0x90 | N));
  5182. }
  5183. else if (N <= 0xffff)
  5184. {
  5185. // array 16
  5186. v.push_back(0xdc);
  5187. add_to_vector(v, 2, N);
  5188. }
  5189. else if (N <= 0xffffffff)
  5190. {
  5191. // array 32
  5192. v.push_back(0xdd);
  5193. add_to_vector(v, 4, N);
  5194. }
  5195. // append each element
  5196. for (const auto& el : *j.m_value.array)
  5197. {
  5198. to_msgpack_internal(el, v);
  5199. }
  5200. break;
  5201. }
  5202. case value_t::object:
  5203. {
  5204. const auto N = j.m_value.object->size();
  5205. if (N <= 15)
  5206. {
  5207. // fixmap
  5208. v.push_back(static_cast<uint8_t>(0x80 | (N & 0xf)));
  5209. }
  5210. else if (N <= 65535)
  5211. {
  5212. // map 16
  5213. v.push_back(0xde);
  5214. add_to_vector(v, 2, N);
  5215. }
  5216. else if (N <= 4294967295)
  5217. {
  5218. // map 32
  5219. v.push_back(0xdf);
  5220. add_to_vector(v, 4, N);
  5221. }
  5222. // append each element
  5223. for (const auto& el : *j.m_value.object)
  5224. {
  5225. to_msgpack_internal(el.first, v);
  5226. to_msgpack_internal(el.second, v);
  5227. }
  5228. break;
  5229. }
  5230. default:
  5231. {
  5232. break;
  5233. }
  5234. }
  5235. }
  5236. /*!
  5237. @brief create a CBOR serialization of a given JSON value
  5238. This is a straightforward implementation of the CBOR specification.
  5239. @param[in] j JSON value to serialize
  5240. @param[in,out] v byte vector to write the serialization to
  5241. @sa https://tools.ietf.org/html/rfc7049
  5242. */
  5243. static void to_cbor_internal(const basic_json& j, std::vector<uint8_t>& v)
  5244. {
  5245. switch (j.type())
  5246. {
  5247. case value_t::null:
  5248. {
  5249. v.push_back(0xf6);
  5250. break;
  5251. }
  5252. case value_t::boolean:
  5253. {
  5254. v.push_back(j.m_value.boolean ? 0xf5 : 0xf4);
  5255. break;
  5256. }
  5257. case value_t::number_integer:
  5258. {
  5259. if (j.m_value.number_integer >= 0)
  5260. {
  5261. // CBOR does not differentiate between positive signed
  5262. // integers and unsigned integers. Therefore, we used the
  5263. // code from the value_t::number_unsigned case here.
  5264. if (j.m_value.number_integer <= 0x17)
  5265. {
  5266. add_to_vector(v, 1, j.m_value.number_integer);
  5267. }
  5268. else if (j.m_value.number_integer <= UINT8_MAX)
  5269. {
  5270. v.push_back(0x18);
  5271. // one-byte uint8_t
  5272. add_to_vector(v, 1, j.m_value.number_integer);
  5273. }
  5274. else if (j.m_value.number_integer <= UINT16_MAX)
  5275. {
  5276. v.push_back(0x19);
  5277. // two-byte uint16_t
  5278. add_to_vector(v, 2, j.m_value.number_integer);
  5279. }
  5280. else if (j.m_value.number_integer <= UINT32_MAX)
  5281. {
  5282. v.push_back(0x1a);
  5283. // four-byte uint32_t
  5284. add_to_vector(v, 4, j.m_value.number_integer);
  5285. }
  5286. else
  5287. {
  5288. v.push_back(0x1b);
  5289. // eight-byte uint64_t
  5290. add_to_vector(v, 8, j.m_value.number_integer);
  5291. }
  5292. }
  5293. else
  5294. {
  5295. // The conversions below encode the sign in the first byte,
  5296. // and the value is converted to a positive number.
  5297. const auto positive_number = -1 - j.m_value.number_integer;
  5298. if (j.m_value.number_integer >= -24)
  5299. {
  5300. v.push_back(static_cast<uint8_t>(0x20 + positive_number));
  5301. }
  5302. else if (positive_number <= UINT8_MAX)
  5303. {
  5304. // int 8
  5305. v.push_back(0x38);
  5306. add_to_vector(v, 1, positive_number);
  5307. }
  5308. else if (positive_number <= UINT16_MAX)
  5309. {
  5310. // int 16
  5311. v.push_back(0x39);
  5312. add_to_vector(v, 2, positive_number);
  5313. }
  5314. else if (positive_number <= UINT32_MAX)
  5315. {
  5316. // int 32
  5317. v.push_back(0x3a);
  5318. add_to_vector(v, 4, positive_number);
  5319. }
  5320. else
  5321. {
  5322. // int 64
  5323. v.push_back(0x3b);
  5324. add_to_vector(v, 8, positive_number);
  5325. }
  5326. }
  5327. break;
  5328. }
  5329. case value_t::number_unsigned:
  5330. {
  5331. if (j.m_value.number_unsigned <= 0x17)
  5332. {
  5333. v.push_back(static_cast<uint8_t>(j.m_value.number_unsigned));
  5334. }
  5335. else if (j.m_value.number_unsigned <= 0xff)
  5336. {
  5337. v.push_back(0x18);
  5338. // one-byte uint8_t
  5339. add_to_vector(v, 1, j.m_value.number_unsigned);
  5340. }
  5341. else if (j.m_value.number_unsigned <= 0xffff)
  5342. {
  5343. v.push_back(0x19);
  5344. // two-byte uint16_t
  5345. add_to_vector(v, 2, j.m_value.number_unsigned);
  5346. }
  5347. else if (j.m_value.number_unsigned <= 0xffffffff)
  5348. {
  5349. v.push_back(0x1a);
  5350. // four-byte uint32_t
  5351. add_to_vector(v, 4, j.m_value.number_unsigned);
  5352. }
  5353. else if (j.m_value.number_unsigned <= 0xffffffffffffffff)
  5354. {
  5355. v.push_back(0x1b);
  5356. // eight-byte uint64_t
  5357. add_to_vector(v, 8, j.m_value.number_unsigned);
  5358. }
  5359. break;
  5360. }
  5361. case value_t::number_float:
  5362. {
  5363. // Double-Precision Float
  5364. v.push_back(0xfb);
  5365. const uint8_t* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float));
  5366. for (size_t i = 0; i < 8; ++i)
  5367. {
  5368. v.push_back(helper[7 - i]);
  5369. }
  5370. break;
  5371. }
  5372. case value_t::string:
  5373. {
  5374. const auto N = j.m_value.string->size();
  5375. if (N <= 0x17)
  5376. {
  5377. v.push_back(0x60 + N); // 1 byte for string + size
  5378. }
  5379. else if (N <= 0xff)
  5380. {
  5381. v.push_back(0x78); // one-byte uint8_t for N
  5382. add_to_vector(v, 1, N);
  5383. }
  5384. else if (N <= 0xffff)
  5385. {
  5386. v.push_back(0x79); // two-byte uint16_t for N
  5387. add_to_vector(v, 2, N);
  5388. }
  5389. else if (N <= 0xffffffff)
  5390. {
  5391. v.push_back(0x7a); // four-byte uint32_t for N
  5392. add_to_vector(v, 4, N);
  5393. }
  5394. // LCOV_EXCL_START
  5395. else if (N <= 0xffffffffffffffff)
  5396. {
  5397. v.push_back(0x7b); // eight-byte uint64_t for N
  5398. add_to_vector(v, 8, N);
  5399. }
  5400. // LCOV_EXCL_STOP
  5401. // append string
  5402. std::copy(j.m_value.string->begin(), j.m_value.string->end(),
  5403. std::back_inserter(v));
  5404. break;
  5405. }
  5406. case value_t::array:
  5407. {
  5408. const auto N = j.m_value.array->size();
  5409. if (N <= 0x17)
  5410. {
  5411. v.push_back(0x80 + N); // 1 byte for array + size
  5412. }
  5413. else if (N <= 0xff)
  5414. {
  5415. v.push_back(0x98); // one-byte uint8_t for N
  5416. add_to_vector(v, 1, N);
  5417. }
  5418. else if (N <= 0xffff)
  5419. {
  5420. v.push_back(0x99); // two-byte uint16_t for N
  5421. add_to_vector(v, 2, N);
  5422. }
  5423. else if (N <= 0xffffffff)
  5424. {
  5425. v.push_back(0x9a); // four-byte uint32_t for N
  5426. add_to_vector(v, 4, N);
  5427. }
  5428. // LCOV_EXCL_START
  5429. else if (N <= 0xffffffffffffffff)
  5430. {
  5431. v.push_back(0x9b); // eight-byte uint64_t for N
  5432. add_to_vector(v, 8, N);
  5433. }
  5434. // LCOV_EXCL_STOP
  5435. // append each element
  5436. for (const auto& el : *j.m_value.array)
  5437. {
  5438. to_cbor_internal(el, v);
  5439. }
  5440. break;
  5441. }
  5442. case value_t::object:
  5443. {
  5444. const auto N = j.m_value.object->size();
  5445. if (N <= 0x17)
  5446. {
  5447. v.push_back(0xa0 + N); // 1 byte for object + size
  5448. }
  5449. else if (N <= 0xff)
  5450. {
  5451. v.push_back(0xb8);
  5452. add_to_vector(v, 1, N); // one-byte uint8_t for N
  5453. }
  5454. else if (N <= 0xffff)
  5455. {
  5456. v.push_back(0xb9);
  5457. add_to_vector(v, 2, N); // two-byte uint16_t for N
  5458. }
  5459. else if (N <= 0xffffffff)
  5460. {
  5461. v.push_back(0xba);
  5462. add_to_vector(v, 4, N); // four-byte uint32_t for N
  5463. }
  5464. // LCOV_EXCL_START
  5465. else if (N <= 0xffffffffffffffff)
  5466. {
  5467. v.push_back(0xbb);
  5468. add_to_vector(v, 8, N); // eight-byte uint64_t for N
  5469. }
  5470. // LCOV_EXCL_STOP
  5471. // append each element
  5472. for (const auto& el : *j.m_value.object)
  5473. {
  5474. to_cbor_internal(el.first, v);
  5475. to_cbor_internal(el.second, v);
  5476. }
  5477. break;
  5478. }
  5479. default:
  5480. {
  5481. break;
  5482. }
  5483. }
  5484. }
  5485. /*
  5486. @brief checks if given lengths do not exceed the size of a given vector
  5487. To secure the access to the byte vector during CBOR/MessagePack
  5488. deserialization, bytes are copied from the vector into buffers. This
  5489. function checks if the number of bytes to copy (@a len) does not exceed the
  5490. size @s size of the vector. Additionally, an @a offset is given from where
  5491. to start reading the bytes.
  5492. This function checks whether reading the bytes is safe; that is, offset is a
  5493. valid index in the vector, offset+len
  5494. @param[in] size size of the byte vector
  5495. @param[in] len number of bytes to read
  5496. @param[in] offset offset where to start reading
  5497. vec: x x x x x X X X X X
  5498. ^ ^ ^
  5499. 0 offset len
  5500. @throws out_of_range if `len > v.size()`
  5501. */
  5502. static void check_length(const size_t size, const size_t len, const size_t offset)
  5503. {
  5504. // simple case: requested length is greater than the vector's length
  5505. if (len > size or offset > size)
  5506. {
  5507. throw std::out_of_range("len out of range");
  5508. }
  5509. // second case: adding offset would result in overflow
  5510. if ((size > (std::numeric_limits<size_t>::max() - offset)))
  5511. {
  5512. throw std::out_of_range("len+offset out of range");
  5513. }
  5514. // last case: reading past the end of the vector
  5515. if (len + offset > size)
  5516. {
  5517. throw std::out_of_range("len+offset out of range");
  5518. }
  5519. }
  5520. /*!
  5521. @brief create a JSON value from a given MessagePack vector
  5522. @param[in] v MessagePack serialization
  5523. @param[in] idx byte index to start reading from @a v
  5524. @return deserialized JSON value
  5525. @throw std::invalid_argument if unsupported features from MessagePack were
  5526. used in the given vector @a v or if the input is not valid MessagePack
  5527. @throw std::out_of_range if the given vector ends prematurely
  5528. @sa https://github.com/msgpack/msgpack/blob/master/spec.md
  5529. */
  5530. static basic_json from_msgpack_internal(const std::vector<uint8_t>& v, size_t& idx)
  5531. {
  5532. // make sure reading 1 byte is safe
  5533. check_length(v.size(), 1, idx);
  5534. // store and increment index
  5535. const size_t current_idx = idx++;
  5536. if (v[current_idx] <= 0xbf)
  5537. {
  5538. if (v[current_idx] <= 0x7f) // positive fixint
  5539. {
  5540. return v[current_idx];
  5541. }
  5542. else if (v[current_idx] <= 0x8f) // fixmap
  5543. {
  5544. basic_json result = value_t::object;
  5545. const size_t len = v[current_idx] & 0x0f;
  5546. for (size_t i = 0; i < len; ++i)
  5547. {
  5548. std::string key = from_msgpack_internal(v, idx);
  5549. result[key] = from_msgpack_internal(v, idx);
  5550. }
  5551. return result;
  5552. }
  5553. else if (v[current_idx] <= 0x9f) // fixarray
  5554. {
  5555. basic_json result = value_t::array;
  5556. const size_t len = v[current_idx] & 0x0f;
  5557. for (size_t i = 0; i < len; ++i)
  5558. {
  5559. result.push_back(from_msgpack_internal(v, idx));
  5560. }
  5561. return result;
  5562. }
  5563. else // fixstr
  5564. {
  5565. const size_t len = v[current_idx] & 0x1f;
  5566. const size_t offset = current_idx + 1;
  5567. idx += len; // skip content bytes
  5568. check_length(v.size(), len, offset);
  5569. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5570. }
  5571. }
  5572. else if (v[current_idx] >= 0xe0) // negative fixint
  5573. {
  5574. return static_cast<int8_t>(v[current_idx]);
  5575. }
  5576. else
  5577. {
  5578. switch (v[current_idx])
  5579. {
  5580. case 0xc0: // nil
  5581. {
  5582. return value_t::null;
  5583. }
  5584. case 0xc2: // false
  5585. {
  5586. return false;
  5587. }
  5588. case 0xc3: // true
  5589. {
  5590. return true;
  5591. }
  5592. case 0xca: // float 32
  5593. {
  5594. // copy bytes in reverse order into the double variable
  5595. check_length(v.size(), sizeof(float), 1);
  5596. float res;
  5597. for (size_t byte = 0; byte < sizeof(float); ++byte)
  5598. {
  5599. reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v[current_idx + 1 + byte];
  5600. }
  5601. idx += sizeof(float); // skip content bytes
  5602. return res;
  5603. }
  5604. case 0xcb: // float 64
  5605. {
  5606. // copy bytes in reverse order into the double variable
  5607. check_length(v.size(), sizeof(double), 1);
  5608. double res;
  5609. for (size_t byte = 0; byte < sizeof(double); ++byte)
  5610. {
  5611. reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v[current_idx + 1 + byte];
  5612. }
  5613. idx += sizeof(double); // skip content bytes
  5614. return res;
  5615. }
  5616. case 0xcc: // uint 8
  5617. {
  5618. idx += 1; // skip content byte
  5619. return get_from_vector<uint8_t>(v, current_idx);
  5620. }
  5621. case 0xcd: // uint 16
  5622. {
  5623. idx += 2; // skip 2 content bytes
  5624. return get_from_vector<uint16_t>(v, current_idx);
  5625. }
  5626. case 0xce: // uint 32
  5627. {
  5628. idx += 4; // skip 4 content bytes
  5629. return get_from_vector<uint32_t>(v, current_idx);
  5630. }
  5631. case 0xcf: // uint 64
  5632. {
  5633. idx += 8; // skip 8 content bytes
  5634. return get_from_vector<uint64_t>(v, current_idx);
  5635. }
  5636. case 0xd0: // int 8
  5637. {
  5638. idx += 1; // skip content byte
  5639. return get_from_vector<int8_t>(v, current_idx);
  5640. }
  5641. case 0xd1: // int 16
  5642. {
  5643. idx += 2; // skip 2 content bytes
  5644. return get_from_vector<int16_t>(v, current_idx);
  5645. }
  5646. case 0xd2: // int 32
  5647. {
  5648. idx += 4; // skip 4 content bytes
  5649. return get_from_vector<int32_t>(v, current_idx);
  5650. }
  5651. case 0xd3: // int 64
  5652. {
  5653. idx += 8; // skip 8 content bytes
  5654. return get_from_vector<int64_t>(v, current_idx);
  5655. }
  5656. case 0xd9: // str 8
  5657. {
  5658. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  5659. const size_t offset = current_idx + 2;
  5660. idx += len + 1; // skip size byte + content bytes
  5661. check_length(v.size(), len, offset);
  5662. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5663. }
  5664. case 0xda: // str 16
  5665. {
  5666. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  5667. const size_t offset = current_idx + 3;
  5668. idx += len + 2; // skip 2 size bytes + content bytes
  5669. check_length(v.size(), len, offset);
  5670. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5671. }
  5672. case 0xdb: // str 32
  5673. {
  5674. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  5675. const size_t offset = current_idx + 5;
  5676. idx += len + 4; // skip 4 size bytes + content bytes
  5677. check_length(v.size(), len, offset);
  5678. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5679. }
  5680. case 0xdc: // array 16
  5681. {
  5682. basic_json result = value_t::array;
  5683. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  5684. idx += 2; // skip 2 size bytes
  5685. for (size_t i = 0; i < len; ++i)
  5686. {
  5687. result.push_back(from_msgpack_internal(v, idx));
  5688. }
  5689. return result;
  5690. }
  5691. case 0xdd: // array 32
  5692. {
  5693. basic_json result = value_t::array;
  5694. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  5695. idx += 4; // skip 4 size bytes
  5696. for (size_t i = 0; i < len; ++i)
  5697. {
  5698. result.push_back(from_msgpack_internal(v, idx));
  5699. }
  5700. return result;
  5701. }
  5702. case 0xde: // map 16
  5703. {
  5704. basic_json result = value_t::object;
  5705. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  5706. idx += 2; // skip 2 size bytes
  5707. for (size_t i = 0; i < len; ++i)
  5708. {
  5709. std::string key = from_msgpack_internal(v, idx);
  5710. result[key] = from_msgpack_internal(v, idx);
  5711. }
  5712. return result;
  5713. }
  5714. case 0xdf: // map 32
  5715. {
  5716. basic_json result = value_t::object;
  5717. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  5718. idx += 4; // skip 4 size bytes
  5719. for (size_t i = 0; i < len; ++i)
  5720. {
  5721. std::string key = from_msgpack_internal(v, idx);
  5722. result[key] = from_msgpack_internal(v, idx);
  5723. }
  5724. return result;
  5725. }
  5726. default:
  5727. {
  5728. throw std::invalid_argument("error parsing a msgpack @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx])));
  5729. }
  5730. }
  5731. }
  5732. }
  5733. /*!
  5734. @brief create a JSON value from a given CBOR vector
  5735. @param[in] v CBOR serialization
  5736. @param[in] idx byte index to start reading from @a v
  5737. @return deserialized JSON value
  5738. @throw std::invalid_argument if unsupported features from CBOR were used in
  5739. the given vector @a v or if the input is not valid CBOR
  5740. @throw std::out_of_range if the given vector ends prematurely
  5741. @sa https://tools.ietf.org/html/rfc7049
  5742. */
  5743. static basic_json from_cbor_internal(const std::vector<uint8_t>& v, size_t& idx)
  5744. {
  5745. // store and increment index
  5746. const size_t current_idx = idx++;
  5747. switch (v.at(current_idx))
  5748. {
  5749. // Integer 0x00..0x17 (0..23)
  5750. case 0x00:
  5751. case 0x01:
  5752. case 0x02:
  5753. case 0x03:
  5754. case 0x04:
  5755. case 0x05:
  5756. case 0x06:
  5757. case 0x07:
  5758. case 0x08:
  5759. case 0x09:
  5760. case 0x0a:
  5761. case 0x0b:
  5762. case 0x0c:
  5763. case 0x0d:
  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. {
  5775. return v[current_idx];
  5776. }
  5777. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5778. {
  5779. idx += 1; // skip content byte
  5780. return get_from_vector<uint8_t>(v, current_idx);
  5781. }
  5782. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5783. {
  5784. idx += 2; // skip 2 content bytes
  5785. return get_from_vector<uint16_t>(v, current_idx);
  5786. }
  5787. case 0x1a: // Unsigned integer (four-byte uint32_t follows)
  5788. {
  5789. idx += 4; // skip 4 content bytes
  5790. return get_from_vector<uint32_t>(v, current_idx);
  5791. }
  5792. case 0x1b: // Unsigned integer (eight-byte uint64_t follows)
  5793. {
  5794. idx += 8; // skip 8 content bytes
  5795. return get_from_vector<uint64_t>(v, current_idx);
  5796. }
  5797. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5798. case 0x20:
  5799. case 0x21:
  5800. case 0x22:
  5801. case 0x23:
  5802. case 0x24:
  5803. case 0x25:
  5804. case 0x26:
  5805. case 0x27:
  5806. case 0x28:
  5807. case 0x29:
  5808. case 0x2a:
  5809. case 0x2b:
  5810. case 0x2c:
  5811. case 0x2d:
  5812. case 0x2e:
  5813. case 0x2f:
  5814. case 0x30:
  5815. case 0x31:
  5816. case 0x32:
  5817. case 0x33:
  5818. case 0x34:
  5819. case 0x35:
  5820. case 0x36:
  5821. case 0x37:
  5822. {
  5823. return static_cast<int8_t>(0x20 - 1 - v[current_idx]);
  5824. }
  5825. case 0x38: // Negative integer (one-byte uint8_t follows)
  5826. {
  5827. idx += 1; // skip content byte
  5828. // must be uint8_t !
  5829. return static_cast<number_integer_t>(-1) - get_from_vector<uint8_t>(v, current_idx);
  5830. }
  5831. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5832. {
  5833. idx += 2; // skip 2 content bytes
  5834. return static_cast<number_integer_t>(-1) - get_from_vector<uint16_t>(v, current_idx);
  5835. }
  5836. case 0x3a: // Negative integer -1-n (four-byte uint32_t follows)
  5837. {
  5838. idx += 4; // skip 4 content bytes
  5839. return static_cast<number_integer_t>(-1) - get_from_vector<uint32_t>(v, current_idx);
  5840. }
  5841. case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows)
  5842. {
  5843. idx += 8; // skip 8 content bytes
  5844. return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_from_vector<uint64_t>(v, current_idx));
  5845. }
  5846. // UTF-8 string (0x00..0x17 bytes follow)
  5847. case 0x60:
  5848. case 0x61:
  5849. case 0x62:
  5850. case 0x63:
  5851. case 0x64:
  5852. case 0x65:
  5853. case 0x66:
  5854. case 0x67:
  5855. case 0x68:
  5856. case 0x69:
  5857. case 0x6a:
  5858. case 0x6b:
  5859. case 0x6c:
  5860. case 0x6d:
  5861. case 0x6e:
  5862. case 0x6f:
  5863. case 0x70:
  5864. case 0x71:
  5865. case 0x72:
  5866. case 0x73:
  5867. case 0x74:
  5868. case 0x75:
  5869. case 0x76:
  5870. case 0x77:
  5871. {
  5872. const auto len = static_cast<size_t>(v[current_idx] - 0x60);
  5873. const size_t offset = current_idx + 1;
  5874. idx += len; // skip content bytes
  5875. check_length(v.size(), len, offset);
  5876. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5877. }
  5878. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5879. {
  5880. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  5881. const size_t offset = current_idx + 2;
  5882. idx += len + 1; // skip size byte + content bytes
  5883. check_length(v.size(), len, offset);
  5884. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5885. }
  5886. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5887. {
  5888. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  5889. const size_t offset = current_idx + 3;
  5890. idx += len + 2; // skip 2 size bytes + content bytes
  5891. check_length(v.size(), len, offset);
  5892. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5893. }
  5894. case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
  5895. {
  5896. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  5897. const size_t offset = current_idx + 5;
  5898. idx += len + 4; // skip 4 size bytes + content bytes
  5899. check_length(v.size(), len, offset);
  5900. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5901. }
  5902. case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
  5903. {
  5904. const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
  5905. const size_t offset = current_idx + 9;
  5906. idx += len + 8; // skip 8 size bytes + content bytes
  5907. check_length(v.size(), len, offset);
  5908. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  5909. }
  5910. case 0x7f: // UTF-8 string (indefinite length)
  5911. {
  5912. std::string result;
  5913. while (v.at(idx) != 0xff)
  5914. {
  5915. string_t s = from_cbor_internal(v, idx);
  5916. result += s;
  5917. }
  5918. // skip break byte (0xFF)
  5919. idx += 1;
  5920. return result;
  5921. }
  5922. // array (0x00..0x17 data items follow)
  5923. case 0x80:
  5924. case 0x81:
  5925. case 0x82:
  5926. case 0x83:
  5927. case 0x84:
  5928. case 0x85:
  5929. case 0x86:
  5930. case 0x87:
  5931. case 0x88:
  5932. case 0x89:
  5933. case 0x8a:
  5934. case 0x8b:
  5935. case 0x8c:
  5936. case 0x8d:
  5937. case 0x8e:
  5938. case 0x8f:
  5939. case 0x90:
  5940. case 0x91:
  5941. case 0x92:
  5942. case 0x93:
  5943. case 0x94:
  5944. case 0x95:
  5945. case 0x96:
  5946. case 0x97:
  5947. {
  5948. basic_json result = value_t::array;
  5949. const auto len = static_cast<size_t>(v[current_idx] - 0x80);
  5950. for (size_t i = 0; i < len; ++i)
  5951. {
  5952. result.push_back(from_cbor_internal(v, idx));
  5953. }
  5954. return result;
  5955. }
  5956. case 0x98: // array (one-byte uint8_t for n follows)
  5957. {
  5958. basic_json result = value_t::array;
  5959. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  5960. idx += 1; // skip 1 size byte
  5961. for (size_t i = 0; i < len; ++i)
  5962. {
  5963. result.push_back(from_cbor_internal(v, idx));
  5964. }
  5965. return result;
  5966. }
  5967. case 0x99: // array (two-byte uint16_t for n follow)
  5968. {
  5969. basic_json result = value_t::array;
  5970. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  5971. idx += 2; // skip 4 size bytes
  5972. for (size_t i = 0; i < len; ++i)
  5973. {
  5974. result.push_back(from_cbor_internal(v, idx));
  5975. }
  5976. return result;
  5977. }
  5978. case 0x9a: // array (four-byte uint32_t for n follow)
  5979. {
  5980. basic_json result = value_t::array;
  5981. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  5982. idx += 4; // skip 4 size bytes
  5983. for (size_t i = 0; i < len; ++i)
  5984. {
  5985. result.push_back(from_cbor_internal(v, idx));
  5986. }
  5987. return result;
  5988. }
  5989. case 0x9b: // array (eight-byte uint64_t for n follow)
  5990. {
  5991. basic_json result = value_t::array;
  5992. const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
  5993. idx += 8; // skip 8 size bytes
  5994. for (size_t i = 0; i < len; ++i)
  5995. {
  5996. result.push_back(from_cbor_internal(v, idx));
  5997. }
  5998. return result;
  5999. }
  6000. case 0x9f: // array (indefinite length)
  6001. {
  6002. basic_json result = value_t::array;
  6003. while (v.at(idx) != 0xff)
  6004. {
  6005. result.push_back(from_cbor_internal(v, idx));
  6006. }
  6007. // skip break byte (0xFF)
  6008. idx += 1;
  6009. return result;
  6010. }
  6011. // map (0x00..0x17 pairs of data items follow)
  6012. case 0xa0:
  6013. case 0xa1:
  6014. case 0xa2:
  6015. case 0xa3:
  6016. case 0xa4:
  6017. case 0xa5:
  6018. case 0xa6:
  6019. case 0xa7:
  6020. case 0xa8:
  6021. case 0xa9:
  6022. case 0xaa:
  6023. case 0xab:
  6024. case 0xac:
  6025. case 0xad:
  6026. case 0xae:
  6027. case 0xaf:
  6028. case 0xb0:
  6029. case 0xb1:
  6030. case 0xb2:
  6031. case 0xb3:
  6032. case 0xb4:
  6033. case 0xb5:
  6034. case 0xb6:
  6035. case 0xb7:
  6036. {
  6037. basic_json result = value_t::object;
  6038. const auto len = static_cast<size_t>(v[current_idx] - 0xa0);
  6039. for (size_t i = 0; i < len; ++i)
  6040. {
  6041. std::string key = from_cbor_internal(v, idx);
  6042. result[key] = from_cbor_internal(v, idx);
  6043. }
  6044. return result;
  6045. }
  6046. case 0xb8: // map (one-byte uint8_t for n follows)
  6047. {
  6048. basic_json result = value_t::object;
  6049. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  6050. idx += 1; // skip 1 size byte
  6051. for (size_t i = 0; i < len; ++i)
  6052. {
  6053. std::string key = from_cbor_internal(v, idx);
  6054. result[key] = from_cbor_internal(v, idx);
  6055. }
  6056. return result;
  6057. }
  6058. case 0xb9: // map (two-byte uint16_t for n follow)
  6059. {
  6060. basic_json result = value_t::object;
  6061. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  6062. idx += 2; // skip 2 size bytes
  6063. for (size_t i = 0; i < len; ++i)
  6064. {
  6065. std::string key = from_cbor_internal(v, idx);
  6066. result[key] = from_cbor_internal(v, idx);
  6067. }
  6068. return result;
  6069. }
  6070. case 0xba: // map (four-byte uint32_t for n follow)
  6071. {
  6072. basic_json result = value_t::object;
  6073. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  6074. idx += 4; // skip 4 size bytes
  6075. for (size_t i = 0; i < len; ++i)
  6076. {
  6077. std::string key = from_cbor_internal(v, idx);
  6078. result[key] = from_cbor_internal(v, idx);
  6079. }
  6080. return result;
  6081. }
  6082. case 0xbb: // map (eight-byte uint64_t for n follow)
  6083. {
  6084. basic_json result = value_t::object;
  6085. const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
  6086. idx += 8; // skip 8 size bytes
  6087. for (size_t i = 0; i < len; ++i)
  6088. {
  6089. std::string key = from_cbor_internal(v, idx);
  6090. result[key] = from_cbor_internal(v, idx);
  6091. }
  6092. return result;
  6093. }
  6094. case 0xbf: // map (indefinite length)
  6095. {
  6096. basic_json result = value_t::object;
  6097. while (v.at(idx) != 0xff)
  6098. {
  6099. std::string key = from_cbor_internal(v, idx);
  6100. result[key] = from_cbor_internal(v, idx);
  6101. }
  6102. // skip break byte (0xFF)
  6103. idx += 1;
  6104. return result;
  6105. }
  6106. case 0xf4: // false
  6107. {
  6108. return false;
  6109. }
  6110. case 0xf5: // true
  6111. {
  6112. return true;
  6113. }
  6114. case 0xf6: // null
  6115. {
  6116. return value_t::null;
  6117. }
  6118. case 0xf9: // Half-Precision Float (two-byte IEEE 754)
  6119. {
  6120. check_length(v.size(), 2, 1);
  6121. idx += 2; // skip two content bytes
  6122. // code from RFC 7049, Appendix D, Figure 3:
  6123. // As half-precision floating-point numbers were only added to
  6124. // IEEE 754 in 2008, today's programming platforms often still
  6125. // only have limited support for them. It is very easy to
  6126. // include at least decoding support for them even without such
  6127. // support. An example of a small decoder for half-precision
  6128. // floating-point numbers in the C language is shown in Fig. 3.
  6129. const int half = (v[current_idx + 1] << 8) + v[current_idx + 2];
  6130. const int exp = (half >> 10) & 0x1f;
  6131. const int mant = half & 0x3ff;
  6132. double val;
  6133. if (exp == 0)
  6134. {
  6135. val = std::ldexp(mant, -24);
  6136. }
  6137. else if (exp != 31)
  6138. {
  6139. val = std::ldexp(mant + 1024, exp - 25);
  6140. }
  6141. else
  6142. {
  6143. val = mant == 0 ? INFINITY : NAN;
  6144. }
  6145. return half & 0x8000 ? -val : val;
  6146. }
  6147. case 0xfa: // Single-Precision Float (four-byte IEEE 754)
  6148. {
  6149. // copy bytes in reverse order into the float variable
  6150. check_length(v.size(), sizeof(float), 1);
  6151. float res;
  6152. for (size_t byte = 0; byte < sizeof(float); ++byte)
  6153. {
  6154. reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v[current_idx + 1 + byte];
  6155. }
  6156. idx += sizeof(float); // skip content bytes
  6157. return res;
  6158. }
  6159. case 0xfb: // Double-Precision Float (eight-byte IEEE 754)
  6160. {
  6161. check_length(v.size(), sizeof(double), 1);
  6162. // copy bytes in reverse order into the double variable
  6163. double res;
  6164. for (size_t byte = 0; byte < sizeof(double); ++byte)
  6165. {
  6166. reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v[current_idx + 1 + byte];
  6167. }
  6168. idx += sizeof(double); // skip content bytes
  6169. return res;
  6170. }
  6171. default: // anything else (0xFF is handled inside the other types)
  6172. {
  6173. throw std::invalid_argument("error parsing a CBOR @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx])));
  6174. }
  6175. }
  6176. }
  6177. public:
  6178. /*!
  6179. @brief create a MessagePack serialization of a given JSON value
  6180. Serializes a given JSON value @a j to a byte vector using the MessagePack
  6181. serialization format. MessagePack is a binary serialization format which
  6182. aims to be more compact than JSON itself, yet more efficient to parse.
  6183. @param[in] j JSON value to serialize
  6184. @return MessagePack serialization as byte vector
  6185. @complexity Linear in the size of the JSON value @a j.
  6186. @liveexample{The example shows the serialization of a JSON value to a byte
  6187. vector in MessagePack format.,to_msgpack}
  6188. @sa http://msgpack.org
  6189. @sa @ref from_msgpack(const std::vector<uint8_t>&) for the analogous
  6190. deserialization
  6191. @sa @ref to_cbor(const basic_json& for the related CBOR format
  6192. */
  6193. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  6194. {
  6195. std::vector<uint8_t> result;
  6196. to_msgpack_internal(j, result);
  6197. return result;
  6198. }
  6199. /*!
  6200. @brief create a JSON value from a byte vector in MessagePack format
  6201. Deserializes a given byte vector @a v to a JSON value using the MessagePack
  6202. serialization format.
  6203. @param[in] v a byte vector in MessagePack format
  6204. @return deserialized JSON value
  6205. @throw std::invalid_argument if unsupported features from MessagePack were
  6206. used in the given vector @a v or if the input is not valid MessagePack
  6207. @throw std::out_of_range if the given vector ends prematurely
  6208. @complexity Linear in the size of the byte vector @a v.
  6209. @liveexample{The example shows the deserialization of a byte vector in
  6210. MessagePack format to a JSON value.,from_msgpack}
  6211. @sa http://msgpack.org
  6212. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  6213. @sa @ref from_cbor(const std::vector<uint8_t>&) for the related CBOR format
  6214. */
  6215. static basic_json from_msgpack(const std::vector<uint8_t>& v)
  6216. {
  6217. size_t i = 0;
  6218. return from_msgpack_internal(v, i);
  6219. }
  6220. /*!
  6221. @brief create a MessagePack serialization of a given JSON value
  6222. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  6223. Binary Object Representation) serialization format. CBOR is a binary
  6224. serialization format which aims to be more compact than JSON itself, yet
  6225. more efficient to parse.
  6226. @param[in] j JSON value to serialize
  6227. @return MessagePack serialization as byte vector
  6228. @complexity Linear in the size of the JSON value @a j.
  6229. @liveexample{The example shows the serialization of a JSON value to a byte
  6230. vector in CBOR format.,to_cbor}
  6231. @sa http://cbor.io
  6232. @sa @ref from_cbor(const std::vector<uint8_t>&) for the analogous
  6233. deserialization
  6234. @sa @ref to_msgpack(const basic_json& for the related MessagePack format
  6235. */
  6236. static std::vector<uint8_t> to_cbor(const basic_json& j)
  6237. {
  6238. std::vector<uint8_t> result;
  6239. to_cbor_internal(j, result);
  6240. return result;
  6241. }
  6242. /*!
  6243. @brief create a JSON value from a byte vector in CBOR format
  6244. Deserializes a given byte vector @a v to a JSON value using the CBOR
  6245. (Concise Binary Object Representation) serialization format.
  6246. @param[in] v a byte vector in CBOR format
  6247. @return deserialized JSON value
  6248. @throw std::invalid_argument if unsupported features from CBOR were used in
  6249. the given vector @a v or if the input is not valid MessagePack
  6250. @throw std::out_of_range if the given vector ends prematurely
  6251. @complexity Linear in the size of the byte vector @a v.
  6252. @liveexample{The example shows the deserialization of a byte vector in CBOR
  6253. format to a JSON value.,from_cbor}
  6254. @sa http://cbor.io
  6255. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  6256. @sa @ref from_msgpack(const std::vector<uint8_t>&) for the related
  6257. MessagePack format
  6258. */
  6259. static basic_json from_cbor(const std::vector<uint8_t>& v)
  6260. {
  6261. size_t i = 0;
  6262. return from_cbor_internal(v, i);
  6263. }
  6264. /// @}
  6265. private:
  6266. ///////////////////////////
  6267. // convenience functions //
  6268. ///////////////////////////
  6269. /*!
  6270. @brief return the type as string
  6271. Returns the type name as string to be used in error messages - usually to
  6272. indicate that a function was called on a wrong JSON type.
  6273. @return basically a string representation of a the @a m_type member
  6274. @complexity Constant.
  6275. @since version 1.0.0
  6276. */
  6277. std::string type_name() const
  6278. {
  6279. switch (m_type)
  6280. {
  6281. case value_t::null:
  6282. return "null";
  6283. case value_t::object:
  6284. return "object";
  6285. case value_t::array:
  6286. return "array";
  6287. case value_t::string:
  6288. return "string";
  6289. case value_t::boolean:
  6290. return "boolean";
  6291. case value_t::discarded:
  6292. return "discarded";
  6293. default:
  6294. return "number";
  6295. }
  6296. }
  6297. /*!
  6298. @brief calculates the extra space to escape a JSON string
  6299. @param[in] s the string to escape
  6300. @return the number of characters required to escape string @a s
  6301. @complexity Linear in the length of string @a s.
  6302. */
  6303. static std::size_t extra_space(const string_t& s) noexcept
  6304. {
  6305. return std::accumulate(s.begin(), s.end(), size_t{},
  6306. [](size_t res, typename string_t::value_type c)
  6307. {
  6308. switch (c)
  6309. {
  6310. case '"':
  6311. case '\\':
  6312. case '\b':
  6313. case '\f':
  6314. case '\n':
  6315. case '\r':
  6316. case '\t':
  6317. {
  6318. // from c (1 byte) to \x (2 bytes)
  6319. return res + 1;
  6320. }
  6321. default:
  6322. {
  6323. if (c >= 0x00 and c <= 0x1f)
  6324. {
  6325. // from c (1 byte) to \uxxxx (6 bytes)
  6326. return res + 5;
  6327. }
  6328. else
  6329. {
  6330. return res;
  6331. }
  6332. }
  6333. }
  6334. });
  6335. }
  6336. /*!
  6337. @brief escape a string
  6338. Escape a string by replacing certain special characters by a sequence of
  6339. an escape character (backslash) and another character and other control
  6340. characters by a sequence of "\u" followed by a four-digit hex
  6341. representation.
  6342. @param[in] s the string to escape
  6343. @return the escaped string
  6344. @complexity Linear in the length of string @a s.
  6345. */
  6346. static string_t escape_string(const string_t& s)
  6347. {
  6348. const auto space = extra_space(s);
  6349. if (space == 0)
  6350. {
  6351. return s;
  6352. }
  6353. // create a result string of necessary size
  6354. string_t result(s.size() + space, '\\');
  6355. std::size_t pos = 0;
  6356. for (const auto& c : s)
  6357. {
  6358. switch (c)
  6359. {
  6360. // quotation mark (0x22)
  6361. case '"':
  6362. {
  6363. result[pos + 1] = '"';
  6364. pos += 2;
  6365. break;
  6366. }
  6367. // reverse solidus (0x5c)
  6368. case '\\':
  6369. {
  6370. // nothing to change
  6371. pos += 2;
  6372. break;
  6373. }
  6374. // backspace (0x08)
  6375. case '\b':
  6376. {
  6377. result[pos + 1] = 'b';
  6378. pos += 2;
  6379. break;
  6380. }
  6381. // formfeed (0x0c)
  6382. case '\f':
  6383. {
  6384. result[pos + 1] = 'f';
  6385. pos += 2;
  6386. break;
  6387. }
  6388. // newline (0x0a)
  6389. case '\n':
  6390. {
  6391. result[pos + 1] = 'n';
  6392. pos += 2;
  6393. break;
  6394. }
  6395. // carriage return (0x0d)
  6396. case '\r':
  6397. {
  6398. result[pos + 1] = 'r';
  6399. pos += 2;
  6400. break;
  6401. }
  6402. // horizontal tab (0x09)
  6403. case '\t':
  6404. {
  6405. result[pos + 1] = 't';
  6406. pos += 2;
  6407. break;
  6408. }
  6409. default:
  6410. {
  6411. if (c >= 0x00 and c <= 0x1f)
  6412. {
  6413. // convert a number 0..15 to its hex representation
  6414. // (0..f)
  6415. static const char hexify[16] =
  6416. {
  6417. '0', '1', '2', '3', '4', '5', '6', '7',
  6418. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  6419. };
  6420. // print character c as \uxxxx
  6421. for (const char m :
  6422. { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f]
  6423. })
  6424. {
  6425. result[++pos] = m;
  6426. }
  6427. ++pos;
  6428. }
  6429. else
  6430. {
  6431. // all other characters are added as-is
  6432. result[pos++] = c;
  6433. }
  6434. break;
  6435. }
  6436. }
  6437. }
  6438. return result;
  6439. }
  6440. /*!
  6441. @brief internal implementation of the serialization function
  6442. This function is called by the public member function dump and organizes
  6443. the serialization internally. The indentation level is propagated as
  6444. additional parameter. In case of arrays and objects, the function is
  6445. called recursively. Note that
  6446. - strings and object keys are escaped using `escape_string()`
  6447. - integer numbers are converted implicitly via `operator<<`
  6448. - floating-point numbers are converted to a string using `"%g"` format
  6449. @param[out] o stream to write to
  6450. @param[in] pretty_print whether the output shall be pretty-printed
  6451. @param[in] indent_step the indent level
  6452. @param[in] current_indent the current indent level (only used internally)
  6453. */
  6454. void dump(std::ostream& o,
  6455. const bool pretty_print,
  6456. const unsigned int indent_step,
  6457. const unsigned int current_indent = 0) const
  6458. {
  6459. // variable to hold indentation for recursive calls
  6460. unsigned int new_indent = current_indent;
  6461. switch (m_type)
  6462. {
  6463. case value_t::object:
  6464. {
  6465. if (m_value.object->empty())
  6466. {
  6467. o << "{}";
  6468. return;
  6469. }
  6470. o << "{";
  6471. // increase indentation
  6472. if (pretty_print)
  6473. {
  6474. new_indent += indent_step;
  6475. o << "\n";
  6476. }
  6477. for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
  6478. {
  6479. if (i != m_value.object->cbegin())
  6480. {
  6481. o << (pretty_print ? ",\n" : ",");
  6482. }
  6483. o << string_t(new_indent, ' ') << "\""
  6484. << escape_string(i->first) << "\":"
  6485. << (pretty_print ? " " : "");
  6486. i->second.dump(o, pretty_print, indent_step, new_indent);
  6487. }
  6488. // decrease indentation
  6489. if (pretty_print)
  6490. {
  6491. new_indent -= indent_step;
  6492. o << "\n";
  6493. }
  6494. o << string_t(new_indent, ' ') + "}";
  6495. return;
  6496. }
  6497. case value_t::array:
  6498. {
  6499. if (m_value.array->empty())
  6500. {
  6501. o << "[]";
  6502. return;
  6503. }
  6504. o << "[";
  6505. // increase indentation
  6506. if (pretty_print)
  6507. {
  6508. new_indent += indent_step;
  6509. o << "\n";
  6510. }
  6511. for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
  6512. {
  6513. if (i != m_value.array->cbegin())
  6514. {
  6515. o << (pretty_print ? ",\n" : ",");
  6516. }
  6517. o << string_t(new_indent, ' ');
  6518. i->dump(o, pretty_print, indent_step, new_indent);
  6519. }
  6520. // decrease indentation
  6521. if (pretty_print)
  6522. {
  6523. new_indent -= indent_step;
  6524. o << "\n";
  6525. }
  6526. o << string_t(new_indent, ' ') << "]";
  6527. return;
  6528. }
  6529. case value_t::string:
  6530. {
  6531. o << string_t("\"") << escape_string(*m_value.string) << "\"";
  6532. return;
  6533. }
  6534. case value_t::boolean:
  6535. {
  6536. o << (m_value.boolean ? "true" : "false");
  6537. return;
  6538. }
  6539. case value_t::number_integer:
  6540. {
  6541. o << m_value.number_integer;
  6542. return;
  6543. }
  6544. case value_t::number_unsigned:
  6545. {
  6546. o << m_value.number_unsigned;
  6547. return;
  6548. }
  6549. case value_t::number_float:
  6550. {
  6551. if (m_value.number_float == 0)
  6552. {
  6553. // special case for zero to get "0.0"/"-0.0"
  6554. o << (std::signbit(m_value.number_float) ? "-0.0" : "0.0");
  6555. }
  6556. else
  6557. {
  6558. o << m_value.number_float;
  6559. }
  6560. return;
  6561. }
  6562. case value_t::discarded:
  6563. {
  6564. o << "<discarded>";
  6565. return;
  6566. }
  6567. case value_t::null:
  6568. {
  6569. o << "null";
  6570. return;
  6571. }
  6572. }
  6573. }
  6574. private:
  6575. //////////////////////
  6576. // member variables //
  6577. //////////////////////
  6578. /// the type of the current element
  6579. value_t m_type = value_t::null;
  6580. /// the value of the current element
  6581. json_value m_value = {};
  6582. private:
  6583. ///////////////
  6584. // iterators //
  6585. ///////////////
  6586. /*!
  6587. @brief an iterator for primitive JSON types
  6588. This class models an iterator for primitive JSON types (boolean, number,
  6589. string). It's only purpose is to allow the iterator/const_iterator classes
  6590. to "iterate" over primitive values. Internally, the iterator is modeled by
  6591. a `difference_type` variable. Value begin_value (`0`) models the begin,
  6592. end_value (`1`) models past the end.
  6593. */
  6594. class primitive_iterator_t
  6595. {
  6596. public:
  6597. /// set iterator to a defined beginning
  6598. void set_begin() noexcept
  6599. {
  6600. m_it = begin_value;
  6601. }
  6602. /// set iterator to a defined past the end
  6603. void set_end() noexcept
  6604. {
  6605. m_it = end_value;
  6606. }
  6607. /// return whether the iterator can be dereferenced
  6608. constexpr bool is_begin() const noexcept
  6609. {
  6610. return (m_it == begin_value);
  6611. }
  6612. /// return whether the iterator is at end
  6613. constexpr bool is_end() const noexcept
  6614. {
  6615. return (m_it == end_value);
  6616. }
  6617. /// return reference to the value to change and compare
  6618. operator difference_type& () noexcept
  6619. {
  6620. return m_it;
  6621. }
  6622. /// return value to compare
  6623. constexpr operator difference_type () const noexcept
  6624. {
  6625. return m_it;
  6626. }
  6627. private:
  6628. static constexpr difference_type begin_value = 0;
  6629. static constexpr difference_type end_value = begin_value + 1;
  6630. /// iterator as signed integer type
  6631. difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
  6632. };
  6633. /*!
  6634. @brief an iterator value
  6635. @note This structure could easily be a union, but MSVC currently does not
  6636. allow unions members with complex constructors, see
  6637. https://github.com/nlohmann/json/pull/105.
  6638. */
  6639. struct internal_iterator
  6640. {
  6641. /// iterator for JSON objects
  6642. typename object_t::iterator object_iterator;
  6643. /// iterator for JSON arrays
  6644. typename array_t::iterator array_iterator;
  6645. /// generic iterator for all other types
  6646. primitive_iterator_t primitive_iterator;
  6647. /// create an uninitialized internal_iterator
  6648. internal_iterator() noexcept
  6649. : object_iterator(), array_iterator(), primitive_iterator()
  6650. {}
  6651. };
  6652. /// proxy class for the iterator_wrapper functions
  6653. template<typename IteratorType>
  6654. class iteration_proxy
  6655. {
  6656. private:
  6657. /// helper class for iteration
  6658. class iteration_proxy_internal
  6659. {
  6660. private:
  6661. /// the iterator
  6662. IteratorType anchor;
  6663. /// an index for arrays (used to create key names)
  6664. size_t array_index = 0;
  6665. public:
  6666. explicit iteration_proxy_internal(IteratorType it) noexcept
  6667. : anchor(it)
  6668. {}
  6669. /// dereference operator (needed for range-based for)
  6670. iteration_proxy_internal& operator*()
  6671. {
  6672. return *this;
  6673. }
  6674. /// increment operator (needed for range-based for)
  6675. iteration_proxy_internal& operator++()
  6676. {
  6677. ++anchor;
  6678. ++array_index;
  6679. return *this;
  6680. }
  6681. /// inequality operator (needed for range-based for)
  6682. bool operator!= (const iteration_proxy_internal& o) const
  6683. {
  6684. return anchor != o.anchor;
  6685. }
  6686. /// return key of the iterator
  6687. typename basic_json::string_t key() const
  6688. {
  6689. assert(anchor.m_object != nullptr);
  6690. switch (anchor.m_object->type())
  6691. {
  6692. // use integer array index as key
  6693. case value_t::array:
  6694. {
  6695. return std::to_string(array_index);
  6696. }
  6697. // use key from the object
  6698. case value_t::object:
  6699. {
  6700. return anchor.key();
  6701. }
  6702. // use an empty key for all primitive types
  6703. default:
  6704. {
  6705. return "";
  6706. }
  6707. }
  6708. }
  6709. /// return value of the iterator
  6710. typename IteratorType::reference value() const
  6711. {
  6712. return anchor.value();
  6713. }
  6714. };
  6715. /// the container to iterate
  6716. typename IteratorType::reference container;
  6717. public:
  6718. /// construct iteration proxy from a container
  6719. explicit iteration_proxy(typename IteratorType::reference cont)
  6720. : container(cont)
  6721. {}
  6722. /// return iterator begin (needed for range-based for)
  6723. iteration_proxy_internal begin() noexcept
  6724. {
  6725. return iteration_proxy_internal(container.begin());
  6726. }
  6727. /// return iterator end (needed for range-based for)
  6728. iteration_proxy_internal end() noexcept
  6729. {
  6730. return iteration_proxy_internal(container.end());
  6731. }
  6732. };
  6733. public:
  6734. /*!
  6735. @brief a template for a random access iterator for the @ref basic_json class
  6736. This class implements a both iterators (iterator and const_iterator) for the
  6737. @ref basic_json class.
  6738. @note An iterator is called *initialized* when a pointer to a JSON value
  6739. has been set (e.g., by a constructor or a copy assignment). If the
  6740. iterator is default-constructed, it is *uninitialized* and most
  6741. methods are undefined. **The library uses assertions to detect calls
  6742. on uninitialized iterators.**
  6743. @requirement The class satisfies the following concept requirements:
  6744. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  6745. The iterator that can be moved to point (forward and backward) to any
  6746. element in constant time.
  6747. @since version 1.0.0, simplified in version 2.0.9
  6748. */
  6749. template<typename U>
  6750. class iter_impl : public std::iterator<std::random_access_iterator_tag, U>
  6751. {
  6752. /// allow basic_json to access private members
  6753. friend class basic_json;
  6754. // make sure U is basic_json or const basic_json
  6755. static_assert(std::is_same<U, basic_json>::value
  6756. or std::is_same<U, const basic_json>::value,
  6757. "iter_impl only accepts (const) basic_json");
  6758. public:
  6759. /// the type of the values when the iterator is dereferenced
  6760. using value_type = typename basic_json::value_type;
  6761. /// a type to represent differences between iterators
  6762. using difference_type = typename basic_json::difference_type;
  6763. /// defines a pointer to the type iterated over (value_type)
  6764. using pointer = typename std::conditional<std::is_const<U>::value,
  6765. typename basic_json::const_pointer,
  6766. typename basic_json::pointer>::type;
  6767. /// defines a reference to the type iterated over (value_type)
  6768. using reference = typename std::conditional<std::is_const<U>::value,
  6769. typename basic_json::const_reference,
  6770. typename basic_json::reference>::type;
  6771. /// the category of the iterator
  6772. using iterator_category = std::bidirectional_iterator_tag;
  6773. /// default constructor
  6774. iter_impl() = default;
  6775. /*!
  6776. @brief constructor for a given JSON instance
  6777. @param[in] object pointer to a JSON object for this iterator
  6778. @pre object != nullptr
  6779. @post The iterator is initialized; i.e. `m_object != nullptr`.
  6780. */
  6781. explicit iter_impl(pointer object) noexcept
  6782. : m_object(object)
  6783. {
  6784. assert(m_object != nullptr);
  6785. switch (m_object->m_type)
  6786. {
  6787. case basic_json::value_t::object:
  6788. {
  6789. m_it.object_iterator = typename object_t::iterator();
  6790. break;
  6791. }
  6792. case basic_json::value_t::array:
  6793. {
  6794. m_it.array_iterator = typename array_t::iterator();
  6795. break;
  6796. }
  6797. default:
  6798. {
  6799. m_it.primitive_iterator = primitive_iterator_t();
  6800. break;
  6801. }
  6802. }
  6803. }
  6804. /*
  6805. Use operator `const_iterator` instead of `const_iterator(const iterator&
  6806. other) noexcept` to avoid two class definitions for @ref iterator and
  6807. @ref const_iterator.
  6808. This function is only called if this class is an @ref iterator. If this
  6809. class is a @ref const_iterator this function is not called.
  6810. */
  6811. operator const_iterator() const
  6812. {
  6813. const_iterator ret;
  6814. if (m_object)
  6815. {
  6816. ret.m_object = m_object;
  6817. ret.m_it = m_it;
  6818. }
  6819. return ret;
  6820. }
  6821. /*!
  6822. @brief copy constructor
  6823. @param[in] other iterator to copy from
  6824. @note It is not checked whether @a other is initialized.
  6825. */
  6826. iter_impl(const iter_impl& other) noexcept
  6827. : m_object(other.m_object), m_it(other.m_it)
  6828. {}
  6829. /*!
  6830. @brief copy assignment
  6831. @param[in,out] other iterator to copy from
  6832. @note It is not checked whether @a other is initialized.
  6833. */
  6834. iter_impl& operator=(iter_impl other) noexcept(
  6835. std::is_nothrow_move_constructible<pointer>::value and
  6836. std::is_nothrow_move_assignable<pointer>::value and
  6837. std::is_nothrow_move_constructible<internal_iterator>::value and
  6838. std::is_nothrow_move_assignable<internal_iterator>::value
  6839. )
  6840. {
  6841. std::swap(m_object, other.m_object);
  6842. std::swap(m_it, other.m_it);
  6843. return *this;
  6844. }
  6845. private:
  6846. /*!
  6847. @brief set the iterator to the first value
  6848. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6849. */
  6850. void set_begin() noexcept
  6851. {
  6852. assert(m_object != nullptr);
  6853. switch (m_object->m_type)
  6854. {
  6855. case basic_json::value_t::object:
  6856. {
  6857. m_it.object_iterator = m_object->m_value.object->begin();
  6858. break;
  6859. }
  6860. case basic_json::value_t::array:
  6861. {
  6862. m_it.array_iterator = m_object->m_value.array->begin();
  6863. break;
  6864. }
  6865. case basic_json::value_t::null:
  6866. {
  6867. // set to end so begin()==end() is true: null is empty
  6868. m_it.primitive_iterator.set_end();
  6869. break;
  6870. }
  6871. default:
  6872. {
  6873. m_it.primitive_iterator.set_begin();
  6874. break;
  6875. }
  6876. }
  6877. }
  6878. /*!
  6879. @brief set the iterator past the last value
  6880. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6881. */
  6882. void set_end() noexcept
  6883. {
  6884. assert(m_object != nullptr);
  6885. switch (m_object->m_type)
  6886. {
  6887. case basic_json::value_t::object:
  6888. {
  6889. m_it.object_iterator = m_object->m_value.object->end();
  6890. break;
  6891. }
  6892. case basic_json::value_t::array:
  6893. {
  6894. m_it.array_iterator = m_object->m_value.array->end();
  6895. break;
  6896. }
  6897. default:
  6898. {
  6899. m_it.primitive_iterator.set_end();
  6900. break;
  6901. }
  6902. }
  6903. }
  6904. public:
  6905. /*!
  6906. @brief return a reference to the value pointed to by the iterator
  6907. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6908. */
  6909. reference operator*() const
  6910. {
  6911. assert(m_object != nullptr);
  6912. switch (m_object->m_type)
  6913. {
  6914. case basic_json::value_t::object:
  6915. {
  6916. assert(m_it.object_iterator != m_object->m_value.object->end());
  6917. return m_it.object_iterator->second;
  6918. }
  6919. case basic_json::value_t::array:
  6920. {
  6921. assert(m_it.array_iterator != m_object->m_value.array->end());
  6922. return *m_it.array_iterator;
  6923. }
  6924. case basic_json::value_t::null:
  6925. {
  6926. throw std::out_of_range("cannot get value");
  6927. }
  6928. default:
  6929. {
  6930. if (m_it.primitive_iterator.is_begin())
  6931. {
  6932. return *m_object;
  6933. }
  6934. else
  6935. {
  6936. throw std::out_of_range("cannot get value");
  6937. }
  6938. }
  6939. }
  6940. }
  6941. /*!
  6942. @brief dereference the iterator
  6943. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6944. */
  6945. pointer operator->() const
  6946. {
  6947. assert(m_object != nullptr);
  6948. switch (m_object->m_type)
  6949. {
  6950. case basic_json::value_t::object:
  6951. {
  6952. assert(m_it.object_iterator != m_object->m_value.object->end());
  6953. return &(m_it.object_iterator->second);
  6954. }
  6955. case basic_json::value_t::array:
  6956. {
  6957. assert(m_it.array_iterator != m_object->m_value.array->end());
  6958. return &*m_it.array_iterator;
  6959. }
  6960. default:
  6961. {
  6962. if (m_it.primitive_iterator.is_begin())
  6963. {
  6964. return m_object;
  6965. }
  6966. else
  6967. {
  6968. throw std::out_of_range("cannot get value");
  6969. }
  6970. }
  6971. }
  6972. }
  6973. /*!
  6974. @brief post-increment (it++)
  6975. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6976. */
  6977. iter_impl operator++(int)
  6978. {
  6979. auto result = *this;
  6980. ++(*this);
  6981. return result;
  6982. }
  6983. /*!
  6984. @brief pre-increment (++it)
  6985. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6986. */
  6987. iter_impl& operator++()
  6988. {
  6989. assert(m_object != nullptr);
  6990. switch (m_object->m_type)
  6991. {
  6992. case basic_json::value_t::object:
  6993. {
  6994. std::advance(m_it.object_iterator, 1);
  6995. break;
  6996. }
  6997. case basic_json::value_t::array:
  6998. {
  6999. std::advance(m_it.array_iterator, 1);
  7000. break;
  7001. }
  7002. default:
  7003. {
  7004. ++m_it.primitive_iterator;
  7005. break;
  7006. }
  7007. }
  7008. return *this;
  7009. }
  7010. /*!
  7011. @brief post-decrement (it--)
  7012. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7013. */
  7014. iter_impl operator--(int)
  7015. {
  7016. auto result = *this;
  7017. --(*this);
  7018. return result;
  7019. }
  7020. /*!
  7021. @brief pre-decrement (--it)
  7022. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7023. */
  7024. iter_impl& operator--()
  7025. {
  7026. assert(m_object != nullptr);
  7027. switch (m_object->m_type)
  7028. {
  7029. case basic_json::value_t::object:
  7030. {
  7031. std::advance(m_it.object_iterator, -1);
  7032. break;
  7033. }
  7034. case basic_json::value_t::array:
  7035. {
  7036. std::advance(m_it.array_iterator, -1);
  7037. break;
  7038. }
  7039. default:
  7040. {
  7041. --m_it.primitive_iterator;
  7042. break;
  7043. }
  7044. }
  7045. return *this;
  7046. }
  7047. /*!
  7048. @brief comparison: equal
  7049. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7050. */
  7051. bool operator==(const iter_impl& other) const
  7052. {
  7053. // if objects are not the same, the comparison is undefined
  7054. if (m_object != other.m_object)
  7055. {
  7056. throw std::domain_error("cannot compare iterators of different containers");
  7057. }
  7058. assert(m_object != nullptr);
  7059. switch (m_object->m_type)
  7060. {
  7061. case basic_json::value_t::object:
  7062. {
  7063. return (m_it.object_iterator == other.m_it.object_iterator);
  7064. }
  7065. case basic_json::value_t::array:
  7066. {
  7067. return (m_it.array_iterator == other.m_it.array_iterator);
  7068. }
  7069. default:
  7070. {
  7071. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  7072. }
  7073. }
  7074. }
  7075. /*!
  7076. @brief comparison: not equal
  7077. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7078. */
  7079. bool operator!=(const iter_impl& other) const
  7080. {
  7081. return not operator==(other);
  7082. }
  7083. /*!
  7084. @brief comparison: smaller
  7085. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7086. */
  7087. bool operator<(const iter_impl& other) const
  7088. {
  7089. // if objects are not the same, the comparison is undefined
  7090. if (m_object != other.m_object)
  7091. {
  7092. throw std::domain_error("cannot compare iterators of different containers");
  7093. }
  7094. assert(m_object != nullptr);
  7095. switch (m_object->m_type)
  7096. {
  7097. case basic_json::value_t::object:
  7098. {
  7099. throw std::domain_error("cannot compare order of object iterators");
  7100. }
  7101. case basic_json::value_t::array:
  7102. {
  7103. return (m_it.array_iterator < other.m_it.array_iterator);
  7104. }
  7105. default:
  7106. {
  7107. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  7108. }
  7109. }
  7110. }
  7111. /*!
  7112. @brief comparison: less than or equal
  7113. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7114. */
  7115. bool operator<=(const iter_impl& other) const
  7116. {
  7117. return not other.operator < (*this);
  7118. }
  7119. /*!
  7120. @brief comparison: greater than
  7121. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7122. */
  7123. bool operator>(const iter_impl& other) const
  7124. {
  7125. return not operator<=(other);
  7126. }
  7127. /*!
  7128. @brief comparison: greater than or equal
  7129. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7130. */
  7131. bool operator>=(const iter_impl& other) const
  7132. {
  7133. return not operator<(other);
  7134. }
  7135. /*!
  7136. @brief add to iterator
  7137. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7138. */
  7139. iter_impl& operator+=(difference_type i)
  7140. {
  7141. assert(m_object != nullptr);
  7142. switch (m_object->m_type)
  7143. {
  7144. case basic_json::value_t::object:
  7145. {
  7146. throw std::domain_error("cannot use offsets with object iterators");
  7147. }
  7148. case basic_json::value_t::array:
  7149. {
  7150. std::advance(m_it.array_iterator, i);
  7151. break;
  7152. }
  7153. default:
  7154. {
  7155. m_it.primitive_iterator += i;
  7156. break;
  7157. }
  7158. }
  7159. return *this;
  7160. }
  7161. /*!
  7162. @brief subtract from iterator
  7163. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7164. */
  7165. iter_impl& operator-=(difference_type i)
  7166. {
  7167. return operator+=(-i);
  7168. }
  7169. /*!
  7170. @brief add to iterator
  7171. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7172. */
  7173. iter_impl operator+(difference_type i)
  7174. {
  7175. auto result = *this;
  7176. result += i;
  7177. return result;
  7178. }
  7179. /*!
  7180. @brief subtract from iterator
  7181. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7182. */
  7183. iter_impl operator-(difference_type i)
  7184. {
  7185. auto result = *this;
  7186. result -= i;
  7187. return result;
  7188. }
  7189. /*!
  7190. @brief return difference
  7191. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7192. */
  7193. difference_type operator-(const iter_impl& other) const
  7194. {
  7195. assert(m_object != nullptr);
  7196. switch (m_object->m_type)
  7197. {
  7198. case basic_json::value_t::object:
  7199. {
  7200. throw std::domain_error("cannot use offsets with object iterators");
  7201. }
  7202. case basic_json::value_t::array:
  7203. {
  7204. return m_it.array_iterator - other.m_it.array_iterator;
  7205. }
  7206. default:
  7207. {
  7208. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  7209. }
  7210. }
  7211. }
  7212. /*!
  7213. @brief access to successor
  7214. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7215. */
  7216. reference operator[](difference_type n) const
  7217. {
  7218. assert(m_object != nullptr);
  7219. switch (m_object->m_type)
  7220. {
  7221. case basic_json::value_t::object:
  7222. {
  7223. throw std::domain_error("cannot use operator[] for object iterators");
  7224. }
  7225. case basic_json::value_t::array:
  7226. {
  7227. return *std::next(m_it.array_iterator, n);
  7228. }
  7229. case basic_json::value_t::null:
  7230. {
  7231. throw std::out_of_range("cannot get value");
  7232. }
  7233. default:
  7234. {
  7235. if (m_it.primitive_iterator == -n)
  7236. {
  7237. return *m_object;
  7238. }
  7239. else
  7240. {
  7241. throw std::out_of_range("cannot get value");
  7242. }
  7243. }
  7244. }
  7245. }
  7246. /*!
  7247. @brief return the key of an object iterator
  7248. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7249. */
  7250. typename object_t::key_type key() const
  7251. {
  7252. assert(m_object != nullptr);
  7253. if (m_object->is_object())
  7254. {
  7255. return m_it.object_iterator->first;
  7256. }
  7257. else
  7258. {
  7259. throw std::domain_error("cannot use key() for non-object iterators");
  7260. }
  7261. }
  7262. /*!
  7263. @brief return the value of an iterator
  7264. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7265. */
  7266. reference value() const
  7267. {
  7268. return operator*();
  7269. }
  7270. private:
  7271. /// associated JSON instance
  7272. pointer m_object = nullptr;
  7273. /// the actual iterator of the associated instance
  7274. internal_iterator m_it = internal_iterator();
  7275. };
  7276. /*!
  7277. @brief a template for a reverse iterator class
  7278. @tparam Base the base iterator type to reverse. Valid types are @ref
  7279. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  7280. create @ref const_reverse_iterator).
  7281. @requirement The class satisfies the following concept requirements:
  7282. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  7283. The iterator that can be moved to point (forward and backward) to any
  7284. element in constant time.
  7285. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  7286. It is possible to write to the pointed-to element (only if @a Base is
  7287. @ref iterator).
  7288. @since version 1.0.0
  7289. */
  7290. template<typename Base>
  7291. class json_reverse_iterator : public std::reverse_iterator<Base>
  7292. {
  7293. public:
  7294. /// shortcut to the reverse iterator adaptor
  7295. using base_iterator = std::reverse_iterator<Base>;
  7296. /// the reference type for the pointed-to element
  7297. using reference = typename Base::reference;
  7298. /// create reverse iterator from iterator
  7299. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  7300. : base_iterator(it)
  7301. {}
  7302. /// create reverse iterator from base class
  7303. json_reverse_iterator(const base_iterator& it) noexcept
  7304. : base_iterator(it)
  7305. {}
  7306. /// post-increment (it++)
  7307. json_reverse_iterator operator++(int)
  7308. {
  7309. return base_iterator::operator++(1);
  7310. }
  7311. /// pre-increment (++it)
  7312. json_reverse_iterator& operator++()
  7313. {
  7314. base_iterator::operator++();
  7315. return *this;
  7316. }
  7317. /// post-decrement (it--)
  7318. json_reverse_iterator operator--(int)
  7319. {
  7320. return base_iterator::operator--(1);
  7321. }
  7322. /// pre-decrement (--it)
  7323. json_reverse_iterator& operator--()
  7324. {
  7325. base_iterator::operator--();
  7326. return *this;
  7327. }
  7328. /// add to iterator
  7329. json_reverse_iterator& operator+=(difference_type i)
  7330. {
  7331. base_iterator::operator+=(i);
  7332. return *this;
  7333. }
  7334. /// add to iterator
  7335. json_reverse_iterator operator+(difference_type i) const
  7336. {
  7337. auto result = *this;
  7338. result += i;
  7339. return result;
  7340. }
  7341. /// subtract from iterator
  7342. json_reverse_iterator operator-(difference_type i) const
  7343. {
  7344. auto result = *this;
  7345. result -= i;
  7346. return result;
  7347. }
  7348. /// return difference
  7349. difference_type operator-(const json_reverse_iterator& other) const
  7350. {
  7351. return this->base() - other.base();
  7352. }
  7353. /// access to successor
  7354. reference operator[](difference_type n) const
  7355. {
  7356. return *(this->operator+(n));
  7357. }
  7358. /// return the key of an object iterator
  7359. typename object_t::key_type key() const
  7360. {
  7361. auto it = --this->base();
  7362. return it.key();
  7363. }
  7364. /// return the value of an iterator
  7365. reference value() const
  7366. {
  7367. auto it = --this->base();
  7368. return it.operator * ();
  7369. }
  7370. };
  7371. private:
  7372. //////////////////////
  7373. // lexer and parser //
  7374. //////////////////////
  7375. /*!
  7376. @brief lexical analysis
  7377. This class organizes the lexical analysis during JSON deserialization. The
  7378. core of it is a scanner generated by [re2c](http://re2c.org) that
  7379. processes a buffer and recognizes tokens according to RFC 7159.
  7380. */
  7381. class lexer
  7382. {
  7383. public:
  7384. /// token types for the parser
  7385. enum class token_type
  7386. {
  7387. uninitialized, ///< indicating the scanner is uninitialized
  7388. literal_true, ///< the `true` literal
  7389. literal_false, ///< the `false` literal
  7390. literal_null, ///< the `null` literal
  7391. value_string, ///< a string -- use get_string() for actual value
  7392. value_number, ///< a number -- use get_number() for actual value
  7393. begin_array, ///< the character for array begin `[`
  7394. begin_object, ///< the character for object begin `{`
  7395. end_array, ///< the character for array end `]`
  7396. end_object, ///< the character for object end `}`
  7397. name_separator, ///< the name separator `:`
  7398. value_separator, ///< the value separator `,`
  7399. parse_error, ///< indicating a parse error
  7400. end_of_input ///< indicating the end of the input buffer
  7401. };
  7402. /// the char type to use in the lexer
  7403. using lexer_char_t = unsigned char;
  7404. /// a lexer from a buffer with given length
  7405. lexer(const lexer_char_t* buff, const size_t len) noexcept
  7406. : m_content(buff)
  7407. {
  7408. assert(m_content != nullptr);
  7409. m_start = m_cursor = m_content;
  7410. m_limit = m_content + len;
  7411. }
  7412. /// a lexer from an input stream
  7413. explicit lexer(std::istream& s)
  7414. : m_stream(&s), m_line_buffer()
  7415. {
  7416. // immediately abort if stream is erroneous
  7417. if (s.fail())
  7418. {
  7419. throw std::invalid_argument("stream error");
  7420. }
  7421. // fill buffer
  7422. fill_line_buffer();
  7423. // skip UTF-8 byte-order mark
  7424. if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF")
  7425. {
  7426. m_line_buffer[0] = ' ';
  7427. m_line_buffer[1] = ' ';
  7428. m_line_buffer[2] = ' ';
  7429. }
  7430. }
  7431. // switch off unwanted functions (due to pointer members)
  7432. lexer() = delete;
  7433. lexer(const lexer&) = delete;
  7434. lexer operator=(const lexer&) = delete;
  7435. /*!
  7436. @brief create a string from one or two Unicode code points
  7437. There are two cases: (1) @a codepoint1 is in the Basic Multilingual
  7438. Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2)
  7439. @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to
  7440. represent a code point above U+FFFF.
  7441. @param[in] codepoint1 the code point (can be high surrogate)
  7442. @param[in] codepoint2 the code point (can be low surrogate or 0)
  7443. @return string representation of the code point; the length of the
  7444. result string is between 1 and 4 characters.
  7445. @throw std::out_of_range if code point is > 0x10ffff; example: `"code
  7446. points above 0x10FFFF are invalid"`
  7447. @throw std::invalid_argument if the low surrogate is invalid; example:
  7448. `""missing or wrong low surrogate""`
  7449. @complexity Constant.
  7450. @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
  7451. */
  7452. static string_t to_unicode(const std::size_t codepoint1,
  7453. const std::size_t codepoint2 = 0)
  7454. {
  7455. // calculate the code point from the given code points
  7456. std::size_t codepoint = codepoint1;
  7457. // check if codepoint1 is a high surrogate
  7458. if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
  7459. {
  7460. // check if codepoint2 is a low surrogate
  7461. if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
  7462. {
  7463. codepoint =
  7464. // high surrogate occupies the most significant 22 bits
  7465. (codepoint1 << 10)
  7466. // low surrogate occupies the least significant 15 bits
  7467. + codepoint2
  7468. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  7469. // in the result so we have to subtract with:
  7470. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  7471. - 0x35FDC00;
  7472. }
  7473. else
  7474. {
  7475. throw std::invalid_argument("missing or wrong low surrogate");
  7476. }
  7477. }
  7478. string_t result;
  7479. if (codepoint < 0x80)
  7480. {
  7481. // 1-byte characters: 0xxxxxxx (ASCII)
  7482. result.append(1, static_cast<typename string_t::value_type>(codepoint));
  7483. }
  7484. else if (codepoint <= 0x7ff)
  7485. {
  7486. // 2-byte characters: 110xxxxx 10xxxxxx
  7487. result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F)));
  7488. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  7489. }
  7490. else if (codepoint <= 0xffff)
  7491. {
  7492. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  7493. result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F)));
  7494. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
  7495. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  7496. }
  7497. else if (codepoint <= 0x10ffff)
  7498. {
  7499. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  7500. result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07)));
  7501. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
  7502. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
  7503. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  7504. }
  7505. else
  7506. {
  7507. throw std::out_of_range("code points above 0x10FFFF are invalid");
  7508. }
  7509. return result;
  7510. }
  7511. /// return name of values of type token_type (only used for errors)
  7512. static std::string token_type_name(const token_type t)
  7513. {
  7514. switch (t)
  7515. {
  7516. case token_type::uninitialized:
  7517. return "<uninitialized>";
  7518. case token_type::literal_true:
  7519. return "true literal";
  7520. case token_type::literal_false:
  7521. return "false literal";
  7522. case token_type::literal_null:
  7523. return "null literal";
  7524. case token_type::value_string:
  7525. return "string literal";
  7526. case token_type::value_number:
  7527. return "number literal";
  7528. case token_type::begin_array:
  7529. return "'['";
  7530. case token_type::begin_object:
  7531. return "'{'";
  7532. case token_type::end_array:
  7533. return "']'";
  7534. case token_type::end_object:
  7535. return "'}'";
  7536. case token_type::name_separator:
  7537. return "':'";
  7538. case token_type::value_separator:
  7539. return "','";
  7540. case token_type::parse_error:
  7541. return "<parse error>";
  7542. case token_type::end_of_input:
  7543. return "end of input";
  7544. default:
  7545. {
  7546. // catch non-enum values
  7547. return "unknown token"; // LCOV_EXCL_LINE
  7548. }
  7549. }
  7550. }
  7551. /*!
  7552. This function implements a scanner for JSON. It is specified using
  7553. regular expressions that try to follow RFC 7159 as close as possible.
  7554. These regular expressions are then translated into a minimized
  7555. deterministic finite automaton (DFA) by the tool
  7556. [re2c](http://re2c.org). As a result, the translated code for this
  7557. function consists of a large block of code with `goto` jumps.
  7558. @return the class of the next token read from the buffer
  7559. @complexity Linear in the length of the input.\n
  7560. Proposition: The loop below will always terminate for finite input.\n
  7561. Proof (by contradiction): Assume a finite input. To loop forever, the
  7562. loop must never hit code with a `break` statement. The only code
  7563. snippets without a `break` statement are the continue statements for
  7564. whitespace and byte-order-marks. To loop forever, the input must be an
  7565. infinite sequence of whitespace or byte-order-marks. This contradicts
  7566. the assumption of finite input, q.e.d.
  7567. */
  7568. token_type scan()
  7569. {
  7570. while (true)
  7571. {
  7572. // pointer for backtracking information
  7573. m_marker = nullptr;
  7574. // remember the begin of the token
  7575. m_start = m_cursor;
  7576. assert(m_start != nullptr);
  7577. {
  7578. lexer_char_t yych;
  7579. unsigned int yyaccept = 0;
  7580. static const unsigned char yybm[] =
  7581. {
  7582. 0, 0, 0, 0, 0, 0, 0, 0,
  7583. 0, 32, 32, 0, 0, 32, 0, 0,
  7584. 0, 0, 0, 0, 0, 0, 0, 0,
  7585. 0, 0, 0, 0, 0, 0, 0, 0,
  7586. 160, 128, 0, 128, 128, 128, 128, 128,
  7587. 128, 128, 128, 128, 128, 128, 128, 128,
  7588. 192, 192, 192, 192, 192, 192, 192, 192,
  7589. 192, 192, 128, 128, 128, 128, 128, 128,
  7590. 128, 128, 128, 128, 128, 128, 128, 128,
  7591. 128, 128, 128, 128, 128, 128, 128, 128,
  7592. 128, 128, 128, 128, 128, 128, 128, 128,
  7593. 128, 128, 128, 128, 0, 128, 128, 128,
  7594. 128, 128, 128, 128, 128, 128, 128, 128,
  7595. 128, 128, 128, 128, 128, 128, 128, 128,
  7596. 128, 128, 128, 128, 128, 128, 128, 128,
  7597. 128, 128, 128, 128, 128, 128, 128, 128,
  7598. 0, 0, 0, 0, 0, 0, 0, 0,
  7599. 0, 0, 0, 0, 0, 0, 0, 0,
  7600. 0, 0, 0, 0, 0, 0, 0, 0,
  7601. 0, 0, 0, 0, 0, 0, 0, 0,
  7602. 0, 0, 0, 0, 0, 0, 0, 0,
  7603. 0, 0, 0, 0, 0, 0, 0, 0,
  7604. 0, 0, 0, 0, 0, 0, 0, 0,
  7605. 0, 0, 0, 0, 0, 0, 0, 0,
  7606. 0, 0, 0, 0, 0, 0, 0, 0,
  7607. 0, 0, 0, 0, 0, 0, 0, 0,
  7608. 0, 0, 0, 0, 0, 0, 0, 0,
  7609. 0, 0, 0, 0, 0, 0, 0, 0,
  7610. 0, 0, 0, 0, 0, 0, 0, 0,
  7611. 0, 0, 0, 0, 0, 0, 0, 0,
  7612. 0, 0, 0, 0, 0, 0, 0, 0,
  7613. 0, 0, 0, 0, 0, 0, 0, 0,
  7614. };
  7615. if ((m_limit - m_cursor) < 5)
  7616. {
  7617. fill_line_buffer(5); // LCOV_EXCL_LINE
  7618. }
  7619. yych = *m_cursor;
  7620. if (yybm[0 + yych] & 32)
  7621. {
  7622. goto basic_json_parser_6;
  7623. }
  7624. if (yych <= '[')
  7625. {
  7626. if (yych <= '-')
  7627. {
  7628. if (yych <= '"')
  7629. {
  7630. if (yych <= 0x00)
  7631. {
  7632. goto basic_json_parser_2;
  7633. }
  7634. if (yych <= '!')
  7635. {
  7636. goto basic_json_parser_4;
  7637. }
  7638. goto basic_json_parser_9;
  7639. }
  7640. else
  7641. {
  7642. if (yych <= '+')
  7643. {
  7644. goto basic_json_parser_4;
  7645. }
  7646. if (yych <= ',')
  7647. {
  7648. goto basic_json_parser_10;
  7649. }
  7650. goto basic_json_parser_12;
  7651. }
  7652. }
  7653. else
  7654. {
  7655. if (yych <= '9')
  7656. {
  7657. if (yych <= '/')
  7658. {
  7659. goto basic_json_parser_4;
  7660. }
  7661. if (yych <= '0')
  7662. {
  7663. goto basic_json_parser_13;
  7664. }
  7665. goto basic_json_parser_15;
  7666. }
  7667. else
  7668. {
  7669. if (yych <= ':')
  7670. {
  7671. goto basic_json_parser_17;
  7672. }
  7673. if (yych <= 'Z')
  7674. {
  7675. goto basic_json_parser_4;
  7676. }
  7677. goto basic_json_parser_19;
  7678. }
  7679. }
  7680. }
  7681. else
  7682. {
  7683. if (yych <= 'n')
  7684. {
  7685. if (yych <= 'e')
  7686. {
  7687. if (yych == ']')
  7688. {
  7689. goto basic_json_parser_21;
  7690. }
  7691. goto basic_json_parser_4;
  7692. }
  7693. else
  7694. {
  7695. if (yych <= 'f')
  7696. {
  7697. goto basic_json_parser_23;
  7698. }
  7699. if (yych <= 'm')
  7700. {
  7701. goto basic_json_parser_4;
  7702. }
  7703. goto basic_json_parser_24;
  7704. }
  7705. }
  7706. else
  7707. {
  7708. if (yych <= 'z')
  7709. {
  7710. if (yych == 't')
  7711. {
  7712. goto basic_json_parser_25;
  7713. }
  7714. goto basic_json_parser_4;
  7715. }
  7716. else
  7717. {
  7718. if (yych <= '{')
  7719. {
  7720. goto basic_json_parser_26;
  7721. }
  7722. if (yych == '}')
  7723. {
  7724. goto basic_json_parser_28;
  7725. }
  7726. goto basic_json_parser_4;
  7727. }
  7728. }
  7729. }
  7730. basic_json_parser_2:
  7731. ++m_cursor;
  7732. {
  7733. last_token_type = token_type::end_of_input;
  7734. break;
  7735. }
  7736. basic_json_parser_4:
  7737. ++m_cursor;
  7738. basic_json_parser_5:
  7739. {
  7740. last_token_type = token_type::parse_error;
  7741. break;
  7742. }
  7743. basic_json_parser_6:
  7744. ++m_cursor;
  7745. if (m_limit <= m_cursor)
  7746. {
  7747. fill_line_buffer(1); // LCOV_EXCL_LINE
  7748. }
  7749. yych = *m_cursor;
  7750. if (yybm[0 + yych] & 32)
  7751. {
  7752. goto basic_json_parser_6;
  7753. }
  7754. {
  7755. continue;
  7756. }
  7757. basic_json_parser_9:
  7758. yyaccept = 0;
  7759. yych = *(m_marker = ++m_cursor);
  7760. if (yych <= 0x1F)
  7761. {
  7762. goto basic_json_parser_5;
  7763. }
  7764. if (yych <= 0x7F)
  7765. {
  7766. goto basic_json_parser_31;
  7767. }
  7768. if (yych <= 0xC1)
  7769. {
  7770. goto basic_json_parser_5;
  7771. }
  7772. if (yych <= 0xF4)
  7773. {
  7774. goto basic_json_parser_31;
  7775. }
  7776. goto basic_json_parser_5;
  7777. basic_json_parser_10:
  7778. ++m_cursor;
  7779. {
  7780. last_token_type = token_type::value_separator;
  7781. break;
  7782. }
  7783. basic_json_parser_12:
  7784. yych = *++m_cursor;
  7785. if (yych <= '/')
  7786. {
  7787. goto basic_json_parser_5;
  7788. }
  7789. if (yych <= '0')
  7790. {
  7791. goto basic_json_parser_13;
  7792. }
  7793. if (yych <= '9')
  7794. {
  7795. goto basic_json_parser_15;
  7796. }
  7797. goto basic_json_parser_5;
  7798. basic_json_parser_13:
  7799. yyaccept = 1;
  7800. yych = *(m_marker = ++m_cursor);
  7801. if (yych <= 'D')
  7802. {
  7803. if (yych == '.')
  7804. {
  7805. goto basic_json_parser_43;
  7806. }
  7807. }
  7808. else
  7809. {
  7810. if (yych <= 'E')
  7811. {
  7812. goto basic_json_parser_44;
  7813. }
  7814. if (yych == 'e')
  7815. {
  7816. goto basic_json_parser_44;
  7817. }
  7818. }
  7819. basic_json_parser_14:
  7820. {
  7821. last_token_type = token_type::value_number;
  7822. break;
  7823. }
  7824. basic_json_parser_15:
  7825. yyaccept = 1;
  7826. m_marker = ++m_cursor;
  7827. if ((m_limit - m_cursor) < 3)
  7828. {
  7829. fill_line_buffer(3); // LCOV_EXCL_LINE
  7830. }
  7831. yych = *m_cursor;
  7832. if (yybm[0 + yych] & 64)
  7833. {
  7834. goto basic_json_parser_15;
  7835. }
  7836. if (yych <= 'D')
  7837. {
  7838. if (yych == '.')
  7839. {
  7840. goto basic_json_parser_43;
  7841. }
  7842. goto basic_json_parser_14;
  7843. }
  7844. else
  7845. {
  7846. if (yych <= 'E')
  7847. {
  7848. goto basic_json_parser_44;
  7849. }
  7850. if (yych == 'e')
  7851. {
  7852. goto basic_json_parser_44;
  7853. }
  7854. goto basic_json_parser_14;
  7855. }
  7856. basic_json_parser_17:
  7857. ++m_cursor;
  7858. {
  7859. last_token_type = token_type::name_separator;
  7860. break;
  7861. }
  7862. basic_json_parser_19:
  7863. ++m_cursor;
  7864. {
  7865. last_token_type = token_type::begin_array;
  7866. break;
  7867. }
  7868. basic_json_parser_21:
  7869. ++m_cursor;
  7870. {
  7871. last_token_type = token_type::end_array;
  7872. break;
  7873. }
  7874. basic_json_parser_23:
  7875. yyaccept = 0;
  7876. yych = *(m_marker = ++m_cursor);
  7877. if (yych == 'a')
  7878. {
  7879. goto basic_json_parser_45;
  7880. }
  7881. goto basic_json_parser_5;
  7882. basic_json_parser_24:
  7883. yyaccept = 0;
  7884. yych = *(m_marker = ++m_cursor);
  7885. if (yych == 'u')
  7886. {
  7887. goto basic_json_parser_46;
  7888. }
  7889. goto basic_json_parser_5;
  7890. basic_json_parser_25:
  7891. yyaccept = 0;
  7892. yych = *(m_marker = ++m_cursor);
  7893. if (yych == 'r')
  7894. {
  7895. goto basic_json_parser_47;
  7896. }
  7897. goto basic_json_parser_5;
  7898. basic_json_parser_26:
  7899. ++m_cursor;
  7900. {
  7901. last_token_type = token_type::begin_object;
  7902. break;
  7903. }
  7904. basic_json_parser_28:
  7905. ++m_cursor;
  7906. {
  7907. last_token_type = token_type::end_object;
  7908. break;
  7909. }
  7910. basic_json_parser_30:
  7911. ++m_cursor;
  7912. if (m_limit <= m_cursor)
  7913. {
  7914. fill_line_buffer(1); // LCOV_EXCL_LINE
  7915. }
  7916. yych = *m_cursor;
  7917. basic_json_parser_31:
  7918. if (yybm[0 + yych] & 128)
  7919. {
  7920. goto basic_json_parser_30;
  7921. }
  7922. if (yych <= 0xE0)
  7923. {
  7924. if (yych <= '\\')
  7925. {
  7926. if (yych <= 0x1F)
  7927. {
  7928. goto basic_json_parser_32;
  7929. }
  7930. if (yych <= '"')
  7931. {
  7932. goto basic_json_parser_33;
  7933. }
  7934. goto basic_json_parser_35;
  7935. }
  7936. else
  7937. {
  7938. if (yych <= 0xC1)
  7939. {
  7940. goto basic_json_parser_32;
  7941. }
  7942. if (yych <= 0xDF)
  7943. {
  7944. goto basic_json_parser_36;
  7945. }
  7946. goto basic_json_parser_37;
  7947. }
  7948. }
  7949. else
  7950. {
  7951. if (yych <= 0xEF)
  7952. {
  7953. if (yych == 0xED)
  7954. {
  7955. goto basic_json_parser_39;
  7956. }
  7957. goto basic_json_parser_38;
  7958. }
  7959. else
  7960. {
  7961. if (yych <= 0xF0)
  7962. {
  7963. goto basic_json_parser_40;
  7964. }
  7965. if (yych <= 0xF3)
  7966. {
  7967. goto basic_json_parser_41;
  7968. }
  7969. if (yych <= 0xF4)
  7970. {
  7971. goto basic_json_parser_42;
  7972. }
  7973. }
  7974. }
  7975. basic_json_parser_32:
  7976. m_cursor = m_marker;
  7977. if (yyaccept == 0)
  7978. {
  7979. goto basic_json_parser_5;
  7980. }
  7981. else
  7982. {
  7983. goto basic_json_parser_14;
  7984. }
  7985. basic_json_parser_33:
  7986. ++m_cursor;
  7987. {
  7988. last_token_type = token_type::value_string;
  7989. break;
  7990. }
  7991. basic_json_parser_35:
  7992. ++m_cursor;
  7993. if (m_limit <= m_cursor)
  7994. {
  7995. fill_line_buffer(1); // LCOV_EXCL_LINE
  7996. }
  7997. yych = *m_cursor;
  7998. if (yych <= 'e')
  7999. {
  8000. if (yych <= '/')
  8001. {
  8002. if (yych == '"')
  8003. {
  8004. goto basic_json_parser_30;
  8005. }
  8006. if (yych <= '.')
  8007. {
  8008. goto basic_json_parser_32;
  8009. }
  8010. goto basic_json_parser_30;
  8011. }
  8012. else
  8013. {
  8014. if (yych <= '\\')
  8015. {
  8016. if (yych <= '[')
  8017. {
  8018. goto basic_json_parser_32;
  8019. }
  8020. goto basic_json_parser_30;
  8021. }
  8022. else
  8023. {
  8024. if (yych == 'b')
  8025. {
  8026. goto basic_json_parser_30;
  8027. }
  8028. goto basic_json_parser_32;
  8029. }
  8030. }
  8031. }
  8032. else
  8033. {
  8034. if (yych <= 'q')
  8035. {
  8036. if (yych <= 'f')
  8037. {
  8038. goto basic_json_parser_30;
  8039. }
  8040. if (yych == 'n')
  8041. {
  8042. goto basic_json_parser_30;
  8043. }
  8044. goto basic_json_parser_32;
  8045. }
  8046. else
  8047. {
  8048. if (yych <= 's')
  8049. {
  8050. if (yych <= 'r')
  8051. {
  8052. goto basic_json_parser_30;
  8053. }
  8054. goto basic_json_parser_32;
  8055. }
  8056. else
  8057. {
  8058. if (yych <= 't')
  8059. {
  8060. goto basic_json_parser_30;
  8061. }
  8062. if (yych <= 'u')
  8063. {
  8064. goto basic_json_parser_48;
  8065. }
  8066. goto basic_json_parser_32;
  8067. }
  8068. }
  8069. }
  8070. basic_json_parser_36:
  8071. ++m_cursor;
  8072. if (m_limit <= m_cursor)
  8073. {
  8074. fill_line_buffer(1); // LCOV_EXCL_LINE
  8075. }
  8076. yych = *m_cursor;
  8077. if (yych <= 0x7F)
  8078. {
  8079. goto basic_json_parser_32;
  8080. }
  8081. if (yych <= 0xBF)
  8082. {
  8083. goto basic_json_parser_30;
  8084. }
  8085. goto basic_json_parser_32;
  8086. basic_json_parser_37:
  8087. ++m_cursor;
  8088. if (m_limit <= m_cursor)
  8089. {
  8090. fill_line_buffer(1); // LCOV_EXCL_LINE
  8091. }
  8092. yych = *m_cursor;
  8093. if (yych <= 0x9F)
  8094. {
  8095. goto basic_json_parser_32;
  8096. }
  8097. if (yych <= 0xBF)
  8098. {
  8099. goto basic_json_parser_36;
  8100. }
  8101. goto basic_json_parser_32;
  8102. basic_json_parser_38:
  8103. ++m_cursor;
  8104. if (m_limit <= m_cursor)
  8105. {
  8106. fill_line_buffer(1); // LCOV_EXCL_LINE
  8107. }
  8108. yych = *m_cursor;
  8109. if (yych <= 0x7F)
  8110. {
  8111. goto basic_json_parser_32;
  8112. }
  8113. if (yych <= 0xBF)
  8114. {
  8115. goto basic_json_parser_36;
  8116. }
  8117. goto basic_json_parser_32;
  8118. basic_json_parser_39:
  8119. ++m_cursor;
  8120. if (m_limit <= m_cursor)
  8121. {
  8122. fill_line_buffer(1); // LCOV_EXCL_LINE
  8123. }
  8124. yych = *m_cursor;
  8125. if (yych <= 0x7F)
  8126. {
  8127. goto basic_json_parser_32;
  8128. }
  8129. if (yych <= 0x9F)
  8130. {
  8131. goto basic_json_parser_36;
  8132. }
  8133. goto basic_json_parser_32;
  8134. basic_json_parser_40:
  8135. ++m_cursor;
  8136. if (m_limit <= m_cursor)
  8137. {
  8138. fill_line_buffer(1); // LCOV_EXCL_LINE
  8139. }
  8140. yych = *m_cursor;
  8141. if (yych <= 0x8F)
  8142. {
  8143. goto basic_json_parser_32;
  8144. }
  8145. if (yych <= 0xBF)
  8146. {
  8147. goto basic_json_parser_38;
  8148. }
  8149. goto basic_json_parser_32;
  8150. basic_json_parser_41:
  8151. ++m_cursor;
  8152. if (m_limit <= m_cursor)
  8153. {
  8154. fill_line_buffer(1); // LCOV_EXCL_LINE
  8155. }
  8156. yych = *m_cursor;
  8157. if (yych <= 0x7F)
  8158. {
  8159. goto basic_json_parser_32;
  8160. }
  8161. if (yych <= 0xBF)
  8162. {
  8163. goto basic_json_parser_38;
  8164. }
  8165. goto basic_json_parser_32;
  8166. basic_json_parser_42:
  8167. ++m_cursor;
  8168. if (m_limit <= m_cursor)
  8169. {
  8170. fill_line_buffer(1); // LCOV_EXCL_LINE
  8171. }
  8172. yych = *m_cursor;
  8173. if (yych <= 0x7F)
  8174. {
  8175. goto basic_json_parser_32;
  8176. }
  8177. if (yych <= 0x8F)
  8178. {
  8179. goto basic_json_parser_38;
  8180. }
  8181. goto basic_json_parser_32;
  8182. basic_json_parser_43:
  8183. yych = *++m_cursor;
  8184. if (yych <= '/')
  8185. {
  8186. goto basic_json_parser_32;
  8187. }
  8188. if (yych <= '9')
  8189. {
  8190. goto basic_json_parser_49;
  8191. }
  8192. goto basic_json_parser_32;
  8193. basic_json_parser_44:
  8194. yych = *++m_cursor;
  8195. if (yych <= ',')
  8196. {
  8197. if (yych == '+')
  8198. {
  8199. goto basic_json_parser_51;
  8200. }
  8201. goto basic_json_parser_32;
  8202. }
  8203. else
  8204. {
  8205. if (yych <= '-')
  8206. {
  8207. goto basic_json_parser_51;
  8208. }
  8209. if (yych <= '/')
  8210. {
  8211. goto basic_json_parser_32;
  8212. }
  8213. if (yych <= '9')
  8214. {
  8215. goto basic_json_parser_52;
  8216. }
  8217. goto basic_json_parser_32;
  8218. }
  8219. basic_json_parser_45:
  8220. yych = *++m_cursor;
  8221. if (yych == 'l')
  8222. {
  8223. goto basic_json_parser_54;
  8224. }
  8225. goto basic_json_parser_32;
  8226. basic_json_parser_46:
  8227. yych = *++m_cursor;
  8228. if (yych == 'l')
  8229. {
  8230. goto basic_json_parser_55;
  8231. }
  8232. goto basic_json_parser_32;
  8233. basic_json_parser_47:
  8234. yych = *++m_cursor;
  8235. if (yych == 'u')
  8236. {
  8237. goto basic_json_parser_56;
  8238. }
  8239. goto basic_json_parser_32;
  8240. basic_json_parser_48:
  8241. ++m_cursor;
  8242. if (m_limit <= m_cursor)
  8243. {
  8244. fill_line_buffer(1); // LCOV_EXCL_LINE
  8245. }
  8246. yych = *m_cursor;
  8247. if (yych <= '@')
  8248. {
  8249. if (yych <= '/')
  8250. {
  8251. goto basic_json_parser_32;
  8252. }
  8253. if (yych <= '9')
  8254. {
  8255. goto basic_json_parser_57;
  8256. }
  8257. goto basic_json_parser_32;
  8258. }
  8259. else
  8260. {
  8261. if (yych <= 'F')
  8262. {
  8263. goto basic_json_parser_57;
  8264. }
  8265. if (yych <= '`')
  8266. {
  8267. goto basic_json_parser_32;
  8268. }
  8269. if (yych <= 'f')
  8270. {
  8271. goto basic_json_parser_57;
  8272. }
  8273. goto basic_json_parser_32;
  8274. }
  8275. basic_json_parser_49:
  8276. yyaccept = 1;
  8277. m_marker = ++m_cursor;
  8278. if ((m_limit - m_cursor) < 3)
  8279. {
  8280. fill_line_buffer(3); // LCOV_EXCL_LINE
  8281. }
  8282. yych = *m_cursor;
  8283. if (yych <= 'D')
  8284. {
  8285. if (yych <= '/')
  8286. {
  8287. goto basic_json_parser_14;
  8288. }
  8289. if (yych <= '9')
  8290. {
  8291. goto basic_json_parser_49;
  8292. }
  8293. goto basic_json_parser_14;
  8294. }
  8295. else
  8296. {
  8297. if (yych <= 'E')
  8298. {
  8299. goto basic_json_parser_44;
  8300. }
  8301. if (yych == 'e')
  8302. {
  8303. goto basic_json_parser_44;
  8304. }
  8305. goto basic_json_parser_14;
  8306. }
  8307. basic_json_parser_51:
  8308. yych = *++m_cursor;
  8309. if (yych <= '/')
  8310. {
  8311. goto basic_json_parser_32;
  8312. }
  8313. if (yych >= ':')
  8314. {
  8315. goto basic_json_parser_32;
  8316. }
  8317. basic_json_parser_52:
  8318. ++m_cursor;
  8319. if (m_limit <= m_cursor)
  8320. {
  8321. fill_line_buffer(1); // LCOV_EXCL_LINE
  8322. }
  8323. yych = *m_cursor;
  8324. if (yych <= '/')
  8325. {
  8326. goto basic_json_parser_14;
  8327. }
  8328. if (yych <= '9')
  8329. {
  8330. goto basic_json_parser_52;
  8331. }
  8332. goto basic_json_parser_14;
  8333. basic_json_parser_54:
  8334. yych = *++m_cursor;
  8335. if (yych == 's')
  8336. {
  8337. goto basic_json_parser_58;
  8338. }
  8339. goto basic_json_parser_32;
  8340. basic_json_parser_55:
  8341. yych = *++m_cursor;
  8342. if (yych == 'l')
  8343. {
  8344. goto basic_json_parser_59;
  8345. }
  8346. goto basic_json_parser_32;
  8347. basic_json_parser_56:
  8348. yych = *++m_cursor;
  8349. if (yych == 'e')
  8350. {
  8351. goto basic_json_parser_61;
  8352. }
  8353. goto basic_json_parser_32;
  8354. basic_json_parser_57:
  8355. ++m_cursor;
  8356. if (m_limit <= m_cursor)
  8357. {
  8358. fill_line_buffer(1); // LCOV_EXCL_LINE
  8359. }
  8360. yych = *m_cursor;
  8361. if (yych <= '@')
  8362. {
  8363. if (yych <= '/')
  8364. {
  8365. goto basic_json_parser_32;
  8366. }
  8367. if (yych <= '9')
  8368. {
  8369. goto basic_json_parser_63;
  8370. }
  8371. goto basic_json_parser_32;
  8372. }
  8373. else
  8374. {
  8375. if (yych <= 'F')
  8376. {
  8377. goto basic_json_parser_63;
  8378. }
  8379. if (yych <= '`')
  8380. {
  8381. goto basic_json_parser_32;
  8382. }
  8383. if (yych <= 'f')
  8384. {
  8385. goto basic_json_parser_63;
  8386. }
  8387. goto basic_json_parser_32;
  8388. }
  8389. basic_json_parser_58:
  8390. yych = *++m_cursor;
  8391. if (yych == 'e')
  8392. {
  8393. goto basic_json_parser_64;
  8394. }
  8395. goto basic_json_parser_32;
  8396. basic_json_parser_59:
  8397. ++m_cursor;
  8398. {
  8399. last_token_type = token_type::literal_null;
  8400. break;
  8401. }
  8402. basic_json_parser_61:
  8403. ++m_cursor;
  8404. {
  8405. last_token_type = token_type::literal_true;
  8406. break;
  8407. }
  8408. basic_json_parser_63:
  8409. ++m_cursor;
  8410. if (m_limit <= m_cursor)
  8411. {
  8412. fill_line_buffer(1); // LCOV_EXCL_LINE
  8413. }
  8414. yych = *m_cursor;
  8415. if (yych <= '@')
  8416. {
  8417. if (yych <= '/')
  8418. {
  8419. goto basic_json_parser_32;
  8420. }
  8421. if (yych <= '9')
  8422. {
  8423. goto basic_json_parser_66;
  8424. }
  8425. goto basic_json_parser_32;
  8426. }
  8427. else
  8428. {
  8429. if (yych <= 'F')
  8430. {
  8431. goto basic_json_parser_66;
  8432. }
  8433. if (yych <= '`')
  8434. {
  8435. goto basic_json_parser_32;
  8436. }
  8437. if (yych <= 'f')
  8438. {
  8439. goto basic_json_parser_66;
  8440. }
  8441. goto basic_json_parser_32;
  8442. }
  8443. basic_json_parser_64:
  8444. ++m_cursor;
  8445. {
  8446. last_token_type = token_type::literal_false;
  8447. break;
  8448. }
  8449. basic_json_parser_66:
  8450. ++m_cursor;
  8451. if (m_limit <= m_cursor)
  8452. {
  8453. fill_line_buffer(1); // LCOV_EXCL_LINE
  8454. }
  8455. yych = *m_cursor;
  8456. if (yych <= '@')
  8457. {
  8458. if (yych <= '/')
  8459. {
  8460. goto basic_json_parser_32;
  8461. }
  8462. if (yych <= '9')
  8463. {
  8464. goto basic_json_parser_30;
  8465. }
  8466. goto basic_json_parser_32;
  8467. }
  8468. else
  8469. {
  8470. if (yych <= 'F')
  8471. {
  8472. goto basic_json_parser_30;
  8473. }
  8474. if (yych <= '`')
  8475. {
  8476. goto basic_json_parser_32;
  8477. }
  8478. if (yych <= 'f')
  8479. {
  8480. goto basic_json_parser_30;
  8481. }
  8482. goto basic_json_parser_32;
  8483. }
  8484. }
  8485. }
  8486. return last_token_type;
  8487. }
  8488. /*!
  8489. @brief append data from the stream to the line buffer
  8490. This function is called by the scan() function when the end of the
  8491. buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be
  8492. incremented without leaving the limits of the line buffer. Note re2c
  8493. decides when to call this function.
  8494. If the lexer reads from contiguous storage, there is no trailing null
  8495. byte. Therefore, this function must make sure to add these padding
  8496. null bytes.
  8497. If the lexer reads from an input stream, this function reads the next
  8498. line of the input.
  8499. @pre
  8500. p p p p p p u u u u u x . . . . . .
  8501. ^ ^ ^ ^
  8502. m_content m_start | m_limit
  8503. m_cursor
  8504. @post
  8505. u u u u u x x x x x x x . . . . . .
  8506. ^ ^ ^
  8507. | m_cursor m_limit
  8508. m_start
  8509. m_content
  8510. */
  8511. void fill_line_buffer(size_t n = 0)
  8512. {
  8513. // if line buffer is used, m_content points to its data
  8514. assert(m_line_buffer.empty()
  8515. or m_content == reinterpret_cast<const lexer_char_t*>(m_line_buffer.data()));
  8516. // if line buffer is used, m_limit is set past the end of its data
  8517. assert(m_line_buffer.empty()
  8518. or m_limit == m_content + m_line_buffer.size());
  8519. // pointer relationships
  8520. assert(m_content <= m_start);
  8521. assert(m_start <= m_cursor);
  8522. assert(m_cursor <= m_limit);
  8523. assert(m_marker == nullptr or m_marker <= m_limit);
  8524. // number of processed characters (p)
  8525. const size_t num_processed_chars = static_cast<size_t>(m_start - m_content);
  8526. // offset for m_marker wrt. to m_start
  8527. const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start;
  8528. // number of unprocessed characters (u)
  8529. const auto offset_cursor = m_cursor - m_start;
  8530. // no stream is used or end of file is reached
  8531. if (m_stream == nullptr or m_stream->eof())
  8532. {
  8533. // m_start may or may not be pointing into m_line_buffer at
  8534. // this point. We trust the standand library to do the right
  8535. // thing. See http://stackoverflow.com/q/28142011/266378
  8536. m_line_buffer.assign(m_start, m_limit);
  8537. // append n characters to make sure that there is sufficient
  8538. // space between m_cursor and m_limit
  8539. m_line_buffer.append(1, '\x00');
  8540. if (n > 0)
  8541. {
  8542. m_line_buffer.append(n - 1, '\x01');
  8543. }
  8544. }
  8545. else
  8546. {
  8547. // delete processed characters from line buffer
  8548. m_line_buffer.erase(0, num_processed_chars);
  8549. // read next line from input stream
  8550. m_line_buffer_tmp.clear();
  8551. std::getline(*m_stream, m_line_buffer_tmp, '\n');
  8552. // add line with newline symbol to the line buffer
  8553. m_line_buffer += m_line_buffer_tmp;
  8554. m_line_buffer.push_back('\n');
  8555. }
  8556. // set pointers
  8557. m_content = reinterpret_cast<const lexer_char_t*>(m_line_buffer.data());
  8558. assert(m_content != nullptr);
  8559. m_start = m_content;
  8560. m_marker = m_start + offset_marker;
  8561. m_cursor = m_start + offset_cursor;
  8562. m_limit = m_start + m_line_buffer.size();
  8563. }
  8564. /// return string representation of last read token
  8565. string_t get_token_string() const
  8566. {
  8567. assert(m_start != nullptr);
  8568. return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
  8569. static_cast<size_t>(m_cursor - m_start));
  8570. }
  8571. /*!
  8572. @brief return string value for string tokens
  8573. The function iterates the characters between the opening and closing
  8574. quotes of the string value. The complete string is the range
  8575. [m_start,m_cursor). Consequently, we iterate from m_start+1 to
  8576. m_cursor-1.
  8577. We differentiate two cases:
  8578. 1. Escaped characters. In this case, a new character is constructed
  8579. according to the nature of the escape. Some escapes create new
  8580. characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied
  8581. as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape
  8582. `"\\uxxxx"` need special care. In this case, to_unicode takes care
  8583. of the construction of the values.
  8584. 2. Unescaped characters are copied as is.
  8585. @pre `m_cursor - m_start >= 2`, meaning the length of the last token
  8586. is at least 2 bytes which is trivially true for any string (which
  8587. consists of at least two quotes).
  8588. " c1 c2 c3 ... "
  8589. ^ ^
  8590. m_start m_cursor
  8591. @complexity Linear in the length of the string.\n
  8592. Lemma: The loop body will always terminate.\n
  8593. Proof (by contradiction): Assume the loop body does not terminate. As
  8594. the loop body does not contain another loop, one of the called
  8595. functions must never return. The called functions are `std::strtoul`
  8596. and to_unicode. Neither function can loop forever, so the loop body
  8597. will never loop forever which contradicts the assumption that the loop
  8598. body does not terminate, q.e.d.\n
  8599. Lemma: The loop condition for the for loop is eventually false.\n
  8600. Proof (by contradiction): Assume the loop does not terminate. Due to
  8601. the above lemma, this can only be due to a tautological loop
  8602. condition; that is, the loop condition i < m_cursor - 1 must always be
  8603. true. Let x be the change of i for any loop iteration. Then
  8604. m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This
  8605. can be rephrased to m_cursor - m_start - 2 > x. With the
  8606. precondition, we x <= 0, meaning that the loop condition holds
  8607. indefinitly if i is always decreased. However, observe that the value
  8608. of i is strictly increasing with each iteration, as it is incremented
  8609. by 1 in the iteration expression and never decremented inside the loop
  8610. body. Hence, the loop condition will eventually be false which
  8611. contradicts the assumption that the loop condition is a tautology,
  8612. q.e.d.
  8613. @return string value of current token without opening and closing
  8614. quotes
  8615. @throw std::out_of_range if to_unicode fails
  8616. */
  8617. string_t get_string() const
  8618. {
  8619. assert(m_cursor - m_start >= 2);
  8620. string_t result;
  8621. result.reserve(static_cast<size_t>(m_cursor - m_start - 2));
  8622. // iterate the result between the quotes
  8623. for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
  8624. {
  8625. // find next escape character
  8626. auto e = std::find(i, m_cursor - 1, '\\');
  8627. if (e != i)
  8628. {
  8629. // see https://github.com/nlohmann/json/issues/365#issuecomment-262874705
  8630. for (auto k = i; k < e; k++)
  8631. {
  8632. result.push_back(static_cast<typename string_t::value_type>(*k));
  8633. }
  8634. i = e - 1; // -1 because of ++i
  8635. }
  8636. else
  8637. {
  8638. // processing escaped character
  8639. // read next character
  8640. ++i;
  8641. switch (*i)
  8642. {
  8643. // the default escapes
  8644. case 't':
  8645. {
  8646. result += "\t";
  8647. break;
  8648. }
  8649. case 'b':
  8650. {
  8651. result += "\b";
  8652. break;
  8653. }
  8654. case 'f':
  8655. {
  8656. result += "\f";
  8657. break;
  8658. }
  8659. case 'n':
  8660. {
  8661. result += "\n";
  8662. break;
  8663. }
  8664. case 'r':
  8665. {
  8666. result += "\r";
  8667. break;
  8668. }
  8669. case '\\':
  8670. {
  8671. result += "\\";
  8672. break;
  8673. }
  8674. case '/':
  8675. {
  8676. result += "/";
  8677. break;
  8678. }
  8679. case '"':
  8680. {
  8681. result += "\"";
  8682. break;
  8683. }
  8684. // unicode
  8685. case 'u':
  8686. {
  8687. // get code xxxx from uxxxx
  8688. auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
  8689. 4).c_str(), nullptr, 16);
  8690. // check if codepoint is a high surrogate
  8691. if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
  8692. {
  8693. // make sure there is a subsequent unicode
  8694. if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
  8695. {
  8696. throw std::invalid_argument("missing low surrogate");
  8697. }
  8698. // get code yyyy from uxxxx\uyyyy
  8699. auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
  8700. (i + 7), 4).c_str(), nullptr, 16);
  8701. result += to_unicode(codepoint, codepoint2);
  8702. // skip the next 10 characters (xxxx\uyyyy)
  8703. i += 10;
  8704. }
  8705. else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF)
  8706. {
  8707. // we found a lone low surrogate
  8708. throw std::invalid_argument("missing high surrogate");
  8709. }
  8710. else
  8711. {
  8712. // add unicode character(s)
  8713. result += to_unicode(codepoint);
  8714. // skip the next four characters (xxxx)
  8715. i += 4;
  8716. }
  8717. break;
  8718. }
  8719. }
  8720. }
  8721. }
  8722. return result;
  8723. }
  8724. /*!
  8725. @brief parse floating point number
  8726. This function (and its overloads) serves to select the most approprate
  8727. standard floating point number parsing function based on the type
  8728. supplied via the first parameter. Set this to @a
  8729. static_cast<number_float_t*>(nullptr).
  8730. @param[in,out] endptr recieves a pointer to the first character after
  8731. the number
  8732. @return the floating point number
  8733. */
  8734. long double str_to_float_t(long double* /* type */, char** endptr) const
  8735. {
  8736. return std::strtold(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
  8737. }
  8738. /*!
  8739. @brief parse floating point number
  8740. This function (and its overloads) serves to select the most approprate
  8741. standard floating point number parsing function based on the type
  8742. supplied via the first parameter. Set this to @a
  8743. static_cast<number_float_t*>(nullptr).
  8744. @param[in,out] endptr recieves a pointer to the first character after
  8745. the number
  8746. @return the floating point number
  8747. */
  8748. double str_to_float_t(double* /* type */, char** endptr) const
  8749. {
  8750. return std::strtod(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
  8751. }
  8752. /*!
  8753. @brief parse floating point number
  8754. This function (and its overloads) serves to select the most approprate
  8755. standard floating point number parsing function based on the type
  8756. supplied via the first parameter. Set this to @a
  8757. static_cast<number_float_t*>(nullptr).
  8758. @param[in,out] endptr recieves a pointer to the first character after
  8759. the number
  8760. @return the floating point number
  8761. */
  8762. float str_to_float_t(float* /* type */, char** endptr) const
  8763. {
  8764. return std::strtof(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
  8765. }
  8766. /*!
  8767. @brief return number value for number tokens
  8768. This function translates the last token into the most appropriate
  8769. number type (either integer, unsigned integer or floating point),
  8770. which is passed back to the caller via the result parameter.
  8771. This function parses the integer component up to the radix point or
  8772. exponent while collecting information about the 'floating point
  8773. representation', which it stores in the result parameter. If there is
  8774. no radix point or exponent, and the number can fit into a @ref
  8775. number_integer_t or @ref number_unsigned_t then it sets the result
  8776. parameter accordingly.
  8777. If the number is a floating point number the number is then parsed
  8778. using @a std:strtod (or @a std:strtof or @a std::strtold).
  8779. @param[out] result @ref basic_json object to receive the number, or
  8780. NAN if the conversion read past the current token. The latter case
  8781. needs to be treated by the caller function.
  8782. */
  8783. void get_number(basic_json& result) const
  8784. {
  8785. assert(m_start != nullptr);
  8786. const lexer::lexer_char_t* curptr = m_start;
  8787. // accumulate the integer conversion result (unsigned for now)
  8788. number_unsigned_t value = 0;
  8789. // maximum absolute value of the relevant integer type
  8790. number_unsigned_t max;
  8791. // temporarily store the type to avoid unecessary bitfield access
  8792. value_t type;
  8793. // look for sign
  8794. if (*curptr == '-')
  8795. {
  8796. type = value_t::number_integer;
  8797. max = static_cast<uint64_t>((std::numeric_limits<number_integer_t>::max)()) + 1;
  8798. curptr++;
  8799. }
  8800. else
  8801. {
  8802. type = value_t::number_unsigned;
  8803. max = static_cast<uint64_t>((std::numeric_limits<number_unsigned_t>::max)());
  8804. }
  8805. // count the significant figures
  8806. for (; curptr < m_cursor; curptr++)
  8807. {
  8808. // quickly skip tests if a digit
  8809. if (*curptr < '0' || *curptr > '9')
  8810. {
  8811. if (*curptr == '.')
  8812. {
  8813. // don't count '.' but change to float
  8814. type = value_t::number_float;
  8815. continue;
  8816. }
  8817. // assume exponent (if not then will fail parse): change to
  8818. // float, stop counting and record exponent details
  8819. type = value_t::number_float;
  8820. break;
  8821. }
  8822. // skip if definitely not an integer
  8823. if (type != value_t::number_float)
  8824. {
  8825. auto digit = static_cast<number_unsigned_t>(*curptr - '0');
  8826. // overflow if value * 10 + digit > max, move terms around
  8827. // to avoid overflow in intermediate values
  8828. if (value > (max - digit) / 10)
  8829. {
  8830. // overflow
  8831. type = value_t::number_float;
  8832. }
  8833. else
  8834. {
  8835. // no overflow
  8836. value = value * 10 + digit;
  8837. }
  8838. }
  8839. }
  8840. // save the value (if not a float)
  8841. if (type == value_t::number_unsigned)
  8842. {
  8843. result.m_value.number_unsigned = value;
  8844. }
  8845. else if (type == value_t::number_integer)
  8846. {
  8847. // invariant: if we parsed a '-', the absolute value is between
  8848. // 0 (we allow -0) and max == -INT64_MIN
  8849. assert(value >= 0);
  8850. assert(value <= max);
  8851. if (value == max)
  8852. {
  8853. // we cannot simply negate value (== max == -INT64_MIN),
  8854. // see https://github.com/nlohmann/json/issues/389
  8855. result.m_value.number_integer = static_cast<number_integer_t>(INT64_MIN);
  8856. }
  8857. else
  8858. {
  8859. // all other values can be negated safely
  8860. result.m_value.number_integer = -static_cast<number_integer_t>(value);
  8861. }
  8862. }
  8863. else
  8864. {
  8865. // parse with strtod
  8866. result.m_value.number_float = str_to_float_t(static_cast<number_float_t*>(nullptr), NULL);
  8867. // replace infinity and NAN by null
  8868. if (not std::isfinite(result.m_value.number_float))
  8869. {
  8870. type = value_t::null;
  8871. result.m_value = basic_json::json_value();
  8872. }
  8873. }
  8874. // save the type
  8875. result.m_type = type;
  8876. }
  8877. private:
  8878. /// optional input stream
  8879. std::istream* m_stream = nullptr;
  8880. /// line buffer buffer for m_stream
  8881. string_t m_line_buffer {};
  8882. /// used for filling m_line_buffer
  8883. string_t m_line_buffer_tmp {};
  8884. /// the buffer pointer
  8885. const lexer_char_t* m_content = nullptr;
  8886. /// pointer to the beginning of the current symbol
  8887. const lexer_char_t* m_start = nullptr;
  8888. /// pointer for backtracking information
  8889. const lexer_char_t* m_marker = nullptr;
  8890. /// pointer to the current symbol
  8891. const lexer_char_t* m_cursor = nullptr;
  8892. /// pointer to the end of the buffer
  8893. const lexer_char_t* m_limit = nullptr;
  8894. /// the last token type
  8895. token_type last_token_type = token_type::end_of_input;
  8896. };
  8897. /*!
  8898. @brief syntax analysis
  8899. This class implements a recursive decent parser.
  8900. */
  8901. class parser
  8902. {
  8903. public:
  8904. /// a parser reading from a string literal
  8905. parser(const char* buff, const parser_callback_t cb = nullptr)
  8906. : callback(cb),
  8907. m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(buff), std::strlen(buff))
  8908. {}
  8909. /// a parser reading from an input stream
  8910. parser(std::istream& is, const parser_callback_t cb = nullptr)
  8911. : callback(cb), m_lexer(is)
  8912. {}
  8913. /// a parser reading from an iterator range with contiguous storage
  8914. template<class IteratorType, typename std::enable_if<
  8915. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value
  8916. , int>::type
  8917. = 0>
  8918. parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr)
  8919. : callback(cb),
  8920. m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(&(*first)),
  8921. static_cast<size_t>(std::distance(first, last)))
  8922. {}
  8923. /// public parser interface
  8924. basic_json parse()
  8925. {
  8926. // read first token
  8927. get_token();
  8928. basic_json result = parse_internal(true);
  8929. result.assert_invariant();
  8930. expect(lexer::token_type::end_of_input);
  8931. // return parser result and replace it with null in case the
  8932. // top-level value was discarded by the callback function
  8933. return result.is_discarded() ? basic_json() : std::move(result);
  8934. }
  8935. private:
  8936. /// the actual parser
  8937. basic_json parse_internal(bool keep)
  8938. {
  8939. auto result = basic_json(value_t::discarded);
  8940. switch (last_token)
  8941. {
  8942. case lexer::token_type::begin_object:
  8943. {
  8944. if (keep and (not callback
  8945. or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0)))
  8946. {
  8947. // explicitly set result to object to cope with {}
  8948. result.m_type = value_t::object;
  8949. result.m_value = value_t::object;
  8950. }
  8951. // read next token
  8952. get_token();
  8953. // closing } -> we are done
  8954. if (last_token == lexer::token_type::end_object)
  8955. {
  8956. get_token();
  8957. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  8958. {
  8959. result = basic_json(value_t::discarded);
  8960. }
  8961. return result;
  8962. }
  8963. // no comma is expected here
  8964. unexpect(lexer::token_type::value_separator);
  8965. // otherwise: parse key-value pairs
  8966. do
  8967. {
  8968. // ugly, but could be fixed with loop reorganization
  8969. if (last_token == lexer::token_type::value_separator)
  8970. {
  8971. get_token();
  8972. }
  8973. // store key
  8974. expect(lexer::token_type::value_string);
  8975. const auto key = m_lexer.get_string();
  8976. bool keep_tag = false;
  8977. if (keep)
  8978. {
  8979. if (callback)
  8980. {
  8981. basic_json k(key);
  8982. keep_tag = callback(depth, parse_event_t::key, k);
  8983. }
  8984. else
  8985. {
  8986. keep_tag = true;
  8987. }
  8988. }
  8989. // parse separator (:)
  8990. get_token();
  8991. expect(lexer::token_type::name_separator);
  8992. // parse and add value
  8993. get_token();
  8994. auto value = parse_internal(keep);
  8995. if (keep and keep_tag and not value.is_discarded())
  8996. {
  8997. result[key] = std::move(value);
  8998. }
  8999. }
  9000. while (last_token == lexer::token_type::value_separator);
  9001. // closing }
  9002. expect(lexer::token_type::end_object);
  9003. get_token();
  9004. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  9005. {
  9006. result = basic_json(value_t::discarded);
  9007. }
  9008. return result;
  9009. }
  9010. case lexer::token_type::begin_array:
  9011. {
  9012. if (keep and (not callback
  9013. or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0)))
  9014. {
  9015. // explicitly set result to object to cope with []
  9016. result.m_type = value_t::array;
  9017. result.m_value = value_t::array;
  9018. }
  9019. // read next token
  9020. get_token();
  9021. // closing ] -> we are done
  9022. if (last_token == lexer::token_type::end_array)
  9023. {
  9024. get_token();
  9025. if (callback and not callback(--depth, parse_event_t::array_end, result))
  9026. {
  9027. result = basic_json(value_t::discarded);
  9028. }
  9029. return result;
  9030. }
  9031. // no comma is expected here
  9032. unexpect(lexer::token_type::value_separator);
  9033. // otherwise: parse values
  9034. do
  9035. {
  9036. // ugly, but could be fixed with loop reorganization
  9037. if (last_token == lexer::token_type::value_separator)
  9038. {
  9039. get_token();
  9040. }
  9041. // parse value
  9042. auto value = parse_internal(keep);
  9043. if (keep and not value.is_discarded())
  9044. {
  9045. result.push_back(std::move(value));
  9046. }
  9047. }
  9048. while (last_token == lexer::token_type::value_separator);
  9049. // closing ]
  9050. expect(lexer::token_type::end_array);
  9051. get_token();
  9052. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  9053. {
  9054. result = basic_json(value_t::discarded);
  9055. }
  9056. return result;
  9057. }
  9058. case lexer::token_type::literal_null:
  9059. {
  9060. get_token();
  9061. result.m_type = value_t::null;
  9062. break;
  9063. }
  9064. case lexer::token_type::value_string:
  9065. {
  9066. const auto s = m_lexer.get_string();
  9067. get_token();
  9068. result = basic_json(s);
  9069. break;
  9070. }
  9071. case lexer::token_type::literal_true:
  9072. {
  9073. get_token();
  9074. result.m_type = value_t::boolean;
  9075. result.m_value = true;
  9076. break;
  9077. }
  9078. case lexer::token_type::literal_false:
  9079. {
  9080. get_token();
  9081. result.m_type = value_t::boolean;
  9082. result.m_value = false;
  9083. break;
  9084. }
  9085. case lexer::token_type::value_number:
  9086. {
  9087. m_lexer.get_number(result);
  9088. get_token();
  9089. break;
  9090. }
  9091. default:
  9092. {
  9093. // the last token was unexpected
  9094. unexpect(last_token);
  9095. }
  9096. }
  9097. if (keep and callback and not callback(depth, parse_event_t::value, result))
  9098. {
  9099. result = basic_json(value_t::discarded);
  9100. }
  9101. return result;
  9102. }
  9103. /// get next token from lexer
  9104. typename lexer::token_type get_token()
  9105. {
  9106. last_token = m_lexer.scan();
  9107. return last_token;
  9108. }
  9109. void expect(typename lexer::token_type t) const
  9110. {
  9111. if (t != last_token)
  9112. {
  9113. std::string error_msg = "parse error - unexpected ";
  9114. error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
  9115. "'") :
  9116. lexer::token_type_name(last_token));
  9117. error_msg += "; expected " + lexer::token_type_name(t);
  9118. throw std::invalid_argument(error_msg);
  9119. }
  9120. }
  9121. void unexpect(typename lexer::token_type t) const
  9122. {
  9123. if (t == last_token)
  9124. {
  9125. std::string error_msg = "parse error - unexpected ";
  9126. error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
  9127. "'") :
  9128. lexer::token_type_name(last_token));
  9129. throw std::invalid_argument(error_msg);
  9130. }
  9131. }
  9132. private:
  9133. /// current level of recursion
  9134. int depth = 0;
  9135. /// callback function
  9136. const parser_callback_t callback = nullptr;
  9137. /// the type of the last read token
  9138. typename lexer::token_type last_token = lexer::token_type::uninitialized;
  9139. /// the lexer
  9140. lexer m_lexer;
  9141. };
  9142. public:
  9143. /*!
  9144. @brief JSON Pointer
  9145. A JSON pointer defines a string syntax for identifying a specific value
  9146. within a JSON document. It can be used with functions `at` and
  9147. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  9148. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  9149. @since version 2.0.0
  9150. */
  9151. class json_pointer
  9152. {
  9153. /// allow basic_json to access private members
  9154. friend class basic_json;
  9155. public:
  9156. /*!
  9157. @brief create JSON pointer
  9158. Create a JSON pointer according to the syntax described in
  9159. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  9160. @param[in] s string representing the JSON pointer; if omitted, the
  9161. empty string is assumed which references the whole JSON
  9162. value
  9163. @throw std::domain_error if reference token is nonempty and does not
  9164. begin with a slash (`/`); example: `"JSON pointer must be empty or
  9165. begin with /"`
  9166. @throw std::domain_error if a tilde (`~`) is not followed by `0`
  9167. (representing `~`) or `1` (representing `/`); example: `"escape error:
  9168. ~ must be followed with 0 or 1"`
  9169. @liveexample{The example shows the construction several valid JSON
  9170. pointers as well as the exceptional behavior.,json_pointer}
  9171. @since version 2.0.0
  9172. */
  9173. explicit json_pointer(const std::string& s = "")
  9174. : reference_tokens(split(s))
  9175. {}
  9176. /*!
  9177. @brief return a string representation of the JSON pointer
  9178. @invariant For each JSON pointer `ptr`, it holds:
  9179. @code {.cpp}
  9180. ptr == json_pointer(ptr.to_string());
  9181. @endcode
  9182. @return a string representation of the JSON pointer
  9183. @liveexample{The example shows the result of `to_string`.,
  9184. json_pointer__to_string}
  9185. @since version 2.0.0
  9186. */
  9187. std::string to_string() const noexcept
  9188. {
  9189. return std::accumulate(reference_tokens.begin(),
  9190. reference_tokens.end(), std::string{},
  9191. [](const std::string & a, const std::string & b)
  9192. {
  9193. return a + "/" + escape(b);
  9194. });
  9195. }
  9196. /// @copydoc to_string()
  9197. operator std::string() const
  9198. {
  9199. return to_string();
  9200. }
  9201. private:
  9202. /// remove and return last reference pointer
  9203. std::string pop_back()
  9204. {
  9205. if (is_root())
  9206. {
  9207. throw std::domain_error("JSON pointer has no parent");
  9208. }
  9209. auto last = reference_tokens.back();
  9210. reference_tokens.pop_back();
  9211. return last;
  9212. }
  9213. /// return whether pointer points to the root document
  9214. bool is_root() const
  9215. {
  9216. return reference_tokens.empty();
  9217. }
  9218. json_pointer top() const
  9219. {
  9220. if (is_root())
  9221. {
  9222. throw std::domain_error("JSON pointer has no parent");
  9223. }
  9224. json_pointer result = *this;
  9225. result.reference_tokens = {reference_tokens[0]};
  9226. return result;
  9227. }
  9228. /*!
  9229. @brief create and return a reference to the pointed to value
  9230. @complexity Linear in the number of reference tokens.
  9231. */
  9232. reference get_and_create(reference j) const
  9233. {
  9234. pointer result = &j;
  9235. // in case no reference tokens exist, return a reference to the
  9236. // JSON value j which will be overwritten by a primitive value
  9237. for (const auto& reference_token : reference_tokens)
  9238. {
  9239. switch (result->m_type)
  9240. {
  9241. case value_t::null:
  9242. {
  9243. if (reference_token == "0")
  9244. {
  9245. // start a new array if reference token is 0
  9246. result = &result->operator[](0);
  9247. }
  9248. else
  9249. {
  9250. // start a new object otherwise
  9251. result = &result->operator[](reference_token);
  9252. }
  9253. break;
  9254. }
  9255. case value_t::object:
  9256. {
  9257. // create an entry in the object
  9258. result = &result->operator[](reference_token);
  9259. break;
  9260. }
  9261. case value_t::array:
  9262. {
  9263. // create an entry in the array
  9264. result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
  9265. break;
  9266. }
  9267. /*
  9268. The following code is only reached if there exists a
  9269. reference token _and_ the current value is primitive. In
  9270. this case, we have an error situation, because primitive
  9271. values may only occur as single value; that is, with an
  9272. empty list of reference tokens.
  9273. */
  9274. default:
  9275. {
  9276. throw std::domain_error("invalid value to unflatten");
  9277. }
  9278. }
  9279. }
  9280. return *result;
  9281. }
  9282. /*!
  9283. @brief return a reference to the pointed to value
  9284. @note This version does not throw if a value is not present, but tries
  9285. to create nested values instead. For instance, calling this function
  9286. with pointer `"/this/that"` on a null value is equivalent to calling
  9287. `operator[]("this").operator[]("that")` on that value, effectively
  9288. changing the null value to an object.
  9289. @param[in] ptr a JSON value
  9290. @return reference to the JSON value pointed to by the JSON pointer
  9291. @complexity Linear in the length of the JSON pointer.
  9292. @throw std::out_of_range if the JSON pointer can not be resolved
  9293. @throw std::domain_error if an array index begins with '0'
  9294. @throw std::invalid_argument if an array index was not a number
  9295. */
  9296. reference get_unchecked(pointer ptr) const
  9297. {
  9298. for (const auto& reference_token : reference_tokens)
  9299. {
  9300. // convert null values to arrays or objects before continuing
  9301. if (ptr->m_type == value_t::null)
  9302. {
  9303. // check if reference token is a number
  9304. const bool nums = std::all_of(reference_token.begin(),
  9305. reference_token.end(),
  9306. [](const char x)
  9307. {
  9308. return std::isdigit(x);
  9309. });
  9310. // change value to array for numbers or "-" or to object
  9311. // otherwise
  9312. if (nums or reference_token == "-")
  9313. {
  9314. *ptr = value_t::array;
  9315. }
  9316. else
  9317. {
  9318. *ptr = value_t::object;
  9319. }
  9320. }
  9321. switch (ptr->m_type)
  9322. {
  9323. case value_t::object:
  9324. {
  9325. // use unchecked object access
  9326. ptr = &ptr->operator[](reference_token);
  9327. break;
  9328. }
  9329. case value_t::array:
  9330. {
  9331. // error condition (cf. RFC 6901, Sect. 4)
  9332. if (reference_token.size() > 1 and reference_token[0] == '0')
  9333. {
  9334. throw std::domain_error("array index must not begin with '0'");
  9335. }
  9336. if (reference_token == "-")
  9337. {
  9338. // explicityly treat "-" as index beyond the end
  9339. ptr = &ptr->operator[](ptr->m_value.array->size());
  9340. }
  9341. else
  9342. {
  9343. // convert array index to number; unchecked access
  9344. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  9345. }
  9346. break;
  9347. }
  9348. default:
  9349. {
  9350. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  9351. }
  9352. }
  9353. }
  9354. return *ptr;
  9355. }
  9356. reference get_checked(pointer ptr) const
  9357. {
  9358. for (const auto& reference_token : reference_tokens)
  9359. {
  9360. switch (ptr->m_type)
  9361. {
  9362. case value_t::object:
  9363. {
  9364. // note: at performs range check
  9365. ptr = &ptr->at(reference_token);
  9366. break;
  9367. }
  9368. case value_t::array:
  9369. {
  9370. if (reference_token == "-")
  9371. {
  9372. // "-" always fails the range check
  9373. throw std::out_of_range("array index '-' (" +
  9374. std::to_string(ptr->m_value.array->size()) +
  9375. ") is out of range");
  9376. }
  9377. // error condition (cf. RFC 6901, Sect. 4)
  9378. if (reference_token.size() > 1 and reference_token[0] == '0')
  9379. {
  9380. throw std::domain_error("array index must not begin with '0'");
  9381. }
  9382. // note: at performs range check
  9383. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  9384. break;
  9385. }
  9386. default:
  9387. {
  9388. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  9389. }
  9390. }
  9391. }
  9392. return *ptr;
  9393. }
  9394. /*!
  9395. @brief return a const reference to the pointed to value
  9396. @param[in] ptr a JSON value
  9397. @return const reference to the JSON value pointed to by the JSON
  9398. pointer
  9399. */
  9400. const_reference get_unchecked(const_pointer ptr) const
  9401. {
  9402. for (const auto& reference_token : reference_tokens)
  9403. {
  9404. switch (ptr->m_type)
  9405. {
  9406. case value_t::object:
  9407. {
  9408. // use unchecked object access
  9409. ptr = &ptr->operator[](reference_token);
  9410. break;
  9411. }
  9412. case value_t::array:
  9413. {
  9414. if (reference_token == "-")
  9415. {
  9416. // "-" cannot be used for const access
  9417. throw std::out_of_range("array index '-' (" +
  9418. std::to_string(ptr->m_value.array->size()) +
  9419. ") is out of range");
  9420. }
  9421. // error condition (cf. RFC 6901, Sect. 4)
  9422. if (reference_token.size() > 1 and reference_token[0] == '0')
  9423. {
  9424. throw std::domain_error("array index must not begin with '0'");
  9425. }
  9426. // use unchecked array access
  9427. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  9428. break;
  9429. }
  9430. default:
  9431. {
  9432. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  9433. }
  9434. }
  9435. }
  9436. return *ptr;
  9437. }
  9438. const_reference get_checked(const_pointer ptr) const
  9439. {
  9440. for (const auto& reference_token : reference_tokens)
  9441. {
  9442. switch (ptr->m_type)
  9443. {
  9444. case value_t::object:
  9445. {
  9446. // note: at performs range check
  9447. ptr = &ptr->at(reference_token);
  9448. break;
  9449. }
  9450. case value_t::array:
  9451. {
  9452. if (reference_token == "-")
  9453. {
  9454. // "-" always fails the range check
  9455. throw std::out_of_range("array index '-' (" +
  9456. std::to_string(ptr->m_value.array->size()) +
  9457. ") is out of range");
  9458. }
  9459. // error condition (cf. RFC 6901, Sect. 4)
  9460. if (reference_token.size() > 1 and reference_token[0] == '0')
  9461. {
  9462. throw std::domain_error("array index must not begin with '0'");
  9463. }
  9464. // note: at performs range check
  9465. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  9466. break;
  9467. }
  9468. default:
  9469. {
  9470. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  9471. }
  9472. }
  9473. }
  9474. return *ptr;
  9475. }
  9476. /// split the string input to reference tokens
  9477. static std::vector<std::string> split(const std::string& reference_string)
  9478. {
  9479. std::vector<std::string> result;
  9480. // special case: empty reference string -> no reference tokens
  9481. if (reference_string.empty())
  9482. {
  9483. return result;
  9484. }
  9485. // check if nonempty reference string begins with slash
  9486. if (reference_string[0] != '/')
  9487. {
  9488. throw std::domain_error("JSON pointer must be empty or begin with '/'");
  9489. }
  9490. // extract the reference tokens:
  9491. // - slash: position of the last read slash (or end of string)
  9492. // - start: position after the previous slash
  9493. for (
  9494. // search for the first slash after the first character
  9495. size_t slash = reference_string.find_first_of("/", 1),
  9496. // set the beginning of the first reference token
  9497. start = 1;
  9498. // we can stop if start == string::npos+1 = 0
  9499. start != 0;
  9500. // set the beginning of the next reference token
  9501. // (will eventually be 0 if slash == std::string::npos)
  9502. start = slash + 1,
  9503. // find next slash
  9504. slash = reference_string.find_first_of("/", start))
  9505. {
  9506. // use the text between the beginning of the reference token
  9507. // (start) and the last slash (slash).
  9508. auto reference_token = reference_string.substr(start, slash - start);
  9509. // check reference tokens are properly escaped
  9510. for (size_t pos = reference_token.find_first_of("~");
  9511. pos != std::string::npos;
  9512. pos = reference_token.find_first_of("~", pos + 1))
  9513. {
  9514. assert(reference_token[pos] == '~');
  9515. // ~ must be followed by 0 or 1
  9516. if (pos == reference_token.size() - 1 or
  9517. (reference_token[pos + 1] != '0' and
  9518. reference_token[pos + 1] != '1'))
  9519. {
  9520. throw std::domain_error("escape error: '~' must be followed with '0' or '1'");
  9521. }
  9522. }
  9523. // finally, store the reference token
  9524. unescape(reference_token);
  9525. result.push_back(reference_token);
  9526. }
  9527. return result;
  9528. }
  9529. private:
  9530. /*!
  9531. @brief replace all occurrences of a substring by another string
  9532. @param[in,out] s the string to manipulate; changed so that all
  9533. occurrences of @a f are replaced with @a t
  9534. @param[in] f the substring to replace with @a t
  9535. @param[in] t the string to replace @a f
  9536. @pre The search string @a f must not be empty.
  9537. @since version 2.0.0
  9538. */
  9539. static void replace_substring(std::string& s,
  9540. const std::string& f,
  9541. const std::string& t)
  9542. {
  9543. assert(not f.empty());
  9544. for (
  9545. size_t pos = s.find(f); // find first occurrence of f
  9546. pos != std::string::npos; // make sure f was found
  9547. s.replace(pos, f.size(), t), // replace with t
  9548. pos = s.find(f, pos + t.size()) // find next occurrence of f
  9549. );
  9550. }
  9551. /// escape tilde and slash
  9552. static std::string escape(std::string s)
  9553. {
  9554. // escape "~"" to "~0" and "/" to "~1"
  9555. replace_substring(s, "~", "~0");
  9556. replace_substring(s, "/", "~1");
  9557. return s;
  9558. }
  9559. /// unescape tilde and slash
  9560. static void unescape(std::string& s)
  9561. {
  9562. // first transform any occurrence of the sequence '~1' to '/'
  9563. replace_substring(s, "~1", "/");
  9564. // then transform any occurrence of the sequence '~0' to '~'
  9565. replace_substring(s, "~0", "~");
  9566. }
  9567. /*!
  9568. @param[in] reference_string the reference string to the current value
  9569. @param[in] value the value to consider
  9570. @param[in,out] result the result object to insert values to
  9571. @note Empty objects or arrays are flattened to `null`.
  9572. */
  9573. static void flatten(const std::string& reference_string,
  9574. const basic_json& value,
  9575. basic_json& result)
  9576. {
  9577. switch (value.m_type)
  9578. {
  9579. case value_t::array:
  9580. {
  9581. if (value.m_value.array->empty())
  9582. {
  9583. // flatten empty array as null
  9584. result[reference_string] = nullptr;
  9585. }
  9586. else
  9587. {
  9588. // iterate array and use index as reference string
  9589. for (size_t i = 0; i < value.m_value.array->size(); ++i)
  9590. {
  9591. flatten(reference_string + "/" + std::to_string(i),
  9592. value.m_value.array->operator[](i), result);
  9593. }
  9594. }
  9595. break;
  9596. }
  9597. case value_t::object:
  9598. {
  9599. if (value.m_value.object->empty())
  9600. {
  9601. // flatten empty object as null
  9602. result[reference_string] = nullptr;
  9603. }
  9604. else
  9605. {
  9606. // iterate object and use keys as reference string
  9607. for (const auto& element : *value.m_value.object)
  9608. {
  9609. flatten(reference_string + "/" + escape(element.first),
  9610. element.second, result);
  9611. }
  9612. }
  9613. break;
  9614. }
  9615. default:
  9616. {
  9617. // add primitive value with its reference string
  9618. result[reference_string] = value;
  9619. break;
  9620. }
  9621. }
  9622. }
  9623. /*!
  9624. @param[in] value flattened JSON
  9625. @return unflattened JSON
  9626. */
  9627. static basic_json unflatten(const basic_json& value)
  9628. {
  9629. if (not value.is_object())
  9630. {
  9631. throw std::domain_error("only objects can be unflattened");
  9632. }
  9633. basic_json result;
  9634. // iterate the JSON object values
  9635. for (const auto& element : *value.m_value.object)
  9636. {
  9637. if (not element.second.is_primitive())
  9638. {
  9639. throw std::domain_error("values in object must be primitive");
  9640. }
  9641. // assign value to reference pointed to by JSON pointer; Note
  9642. // that if the JSON pointer is "" (i.e., points to the whole
  9643. // value), function get_and_create returns a reference to
  9644. // result itself. An assignment will then create a primitive
  9645. // value.
  9646. json_pointer(element.first).get_and_create(result) = element.second;
  9647. }
  9648. return result;
  9649. }
  9650. private:
  9651. /// the reference tokens
  9652. std::vector<std::string> reference_tokens {};
  9653. };
  9654. //////////////////////////
  9655. // JSON Pointer support //
  9656. //////////////////////////
  9657. /// @name JSON Pointer functions
  9658. /// @{
  9659. /*!
  9660. @brief access specified element via JSON Pointer
  9661. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  9662. No bound checking is performed. Similar to @ref operator[](const typename
  9663. object_t::key_type&), `null` values are created in arrays and objects if
  9664. necessary.
  9665. In particular:
  9666. - If the JSON pointer points to an object key that does not exist, it
  9667. is created an filled with a `null` value before a reference to it
  9668. is returned.
  9669. - If the JSON pointer points to an array index that does not exist, it
  9670. is created an filled with a `null` value before a reference to it
  9671. is returned. All indices between the current maximum and the given
  9672. index are also filled with `null`.
  9673. - The special value `-` is treated as a synonym for the index past the
  9674. end.
  9675. @param[in] ptr a JSON pointer
  9676. @return reference to the element pointed to by @a ptr
  9677. @complexity Constant.
  9678. @throw std::out_of_range if the JSON pointer can not be resolved
  9679. @throw std::domain_error if an array index begins with '0'
  9680. @throw std::invalid_argument if an array index was not a number
  9681. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  9682. @since version 2.0.0
  9683. */
  9684. reference operator[](const json_pointer& ptr)
  9685. {
  9686. return ptr.get_unchecked(this);
  9687. }
  9688. /*!
  9689. @brief access specified element via JSON Pointer
  9690. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  9691. No bound checking is performed. The function does not change the JSON
  9692. value; no `null` values are created. In particular, the the special value
  9693. `-` yields an exception.
  9694. @param[in] ptr JSON pointer to the desired element
  9695. @return const reference to the element pointed to by @a ptr
  9696. @complexity Constant.
  9697. @throw std::out_of_range if the JSON pointer can not be resolved
  9698. @throw std::domain_error if an array index begins with '0'
  9699. @throw std::invalid_argument if an array index was not a number
  9700. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  9701. @since version 2.0.0
  9702. */
  9703. const_reference operator[](const json_pointer& ptr) const
  9704. {
  9705. return ptr.get_unchecked(this);
  9706. }
  9707. /*!
  9708. @brief access specified element via JSON Pointer
  9709. Returns a reference to the element at with specified JSON pointer @a ptr,
  9710. with bounds checking.
  9711. @param[in] ptr JSON pointer to the desired element
  9712. @return reference to the element pointed to by @a ptr
  9713. @complexity Constant.
  9714. @throw std::out_of_range if the JSON pointer can not be resolved
  9715. @throw std::domain_error if an array index begins with '0'
  9716. @throw std::invalid_argument if an array index was not a number
  9717. @liveexample{The behavior is shown in the example.,at_json_pointer}
  9718. @since version 2.0.0
  9719. */
  9720. reference at(const json_pointer& ptr)
  9721. {
  9722. return ptr.get_checked(this);
  9723. }
  9724. /*!
  9725. @brief access specified element via JSON Pointer
  9726. Returns a const reference to the element at with specified JSON pointer @a
  9727. ptr, with bounds checking.
  9728. @param[in] ptr JSON pointer to the desired element
  9729. @return reference to the element pointed to by @a ptr
  9730. @complexity Constant.
  9731. @throw std::out_of_range if the JSON pointer can not be resolved
  9732. @throw std::domain_error if an array index begins with '0'
  9733. @throw std::invalid_argument if an array index was not a number
  9734. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  9735. @since version 2.0.0
  9736. */
  9737. const_reference at(const json_pointer& ptr) const
  9738. {
  9739. return ptr.get_checked(this);
  9740. }
  9741. /*!
  9742. @brief return flattened JSON value
  9743. The function creates a JSON object whose keys are JSON pointers (see [RFC
  9744. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  9745. primitive. The original JSON value can be restored using the @ref
  9746. unflatten() function.
  9747. @return an object that maps JSON pointers to primitve values
  9748. @note Empty objects and arrays are flattened to `null` and will not be
  9749. reconstructed correctly by the @ref unflatten() function.
  9750. @complexity Linear in the size the JSON value.
  9751. @liveexample{The following code shows how a JSON object is flattened to an
  9752. object whose keys consist of JSON pointers.,flatten}
  9753. @sa @ref unflatten() for the reverse function
  9754. @since version 2.0.0
  9755. */
  9756. basic_json flatten() const
  9757. {
  9758. basic_json result(value_t::object);
  9759. json_pointer::flatten("", *this, result);
  9760. return result;
  9761. }
  9762. /*!
  9763. @brief unflatten a previously flattened JSON value
  9764. The function restores the arbitrary nesting of a JSON value that has been
  9765. flattened before using the @ref flatten() function. The JSON value must
  9766. meet certain constraints:
  9767. 1. The value must be an object.
  9768. 2. The keys must be JSON pointers (see
  9769. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  9770. 3. The mapped values must be primitive JSON types.
  9771. @return the original JSON from a flattened version
  9772. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  9773. values and can not unflattened to their original type. Apart from
  9774. this example, for a JSON value `j`, the following is always true:
  9775. `j == j.flatten().unflatten()`.
  9776. @complexity Linear in the size the JSON value.
  9777. @liveexample{The following code shows how a flattened JSON object is
  9778. unflattened into the original nested JSON object.,unflatten}
  9779. @sa @ref flatten() for the reverse function
  9780. @since version 2.0.0
  9781. */
  9782. basic_json unflatten() const
  9783. {
  9784. return json_pointer::unflatten(*this);
  9785. }
  9786. /// @}
  9787. //////////////////////////
  9788. // JSON Patch functions //
  9789. //////////////////////////
  9790. /// @name JSON Patch functions
  9791. /// @{
  9792. /*!
  9793. @brief applies a JSON patch
  9794. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  9795. expressing a sequence of operations to apply to a JSON) document. With
  9796. this funcion, a JSON Patch is applied to the current JSON value by
  9797. executing all operations from the patch.
  9798. @param[in] json_patch JSON patch document
  9799. @return patched document
  9800. @note The application of a patch is atomic: Either all operations succeed
  9801. and the patched document is returned or an exception is thrown. In
  9802. any case, the original value is not changed: the patch is applied
  9803. to a copy of the value.
  9804. @throw std::out_of_range if a JSON pointer inside the patch could not
  9805. be resolved successfully in the current JSON value; example: `"key baz
  9806. not found"`
  9807. @throw invalid_argument if the JSON patch is malformed (e.g., mandatory
  9808. attributes are missing); example: `"operation add must have member path"`
  9809. @complexity Linear in the size of the JSON value and the length of the
  9810. JSON patch. As usually only a fraction of the JSON value is affected by
  9811. the patch, the complexity can usually be neglected.
  9812. @liveexample{The following code shows how a JSON patch is applied to a
  9813. value.,patch}
  9814. @sa @ref diff -- create a JSON patch by comparing two JSON values
  9815. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  9816. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  9817. @since version 2.0.0
  9818. */
  9819. basic_json patch(const basic_json& json_patch) const
  9820. {
  9821. // make a working copy to apply the patch to
  9822. basic_json result = *this;
  9823. // the valid JSON Patch operations
  9824. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  9825. const auto get_op = [](const std::string op)
  9826. {
  9827. if (op == "add")
  9828. {
  9829. return patch_operations::add;
  9830. }
  9831. if (op == "remove")
  9832. {
  9833. return patch_operations::remove;
  9834. }
  9835. if (op == "replace")
  9836. {
  9837. return patch_operations::replace;
  9838. }
  9839. if (op == "move")
  9840. {
  9841. return patch_operations::move;
  9842. }
  9843. if (op == "copy")
  9844. {
  9845. return patch_operations::copy;
  9846. }
  9847. if (op == "test")
  9848. {
  9849. return patch_operations::test;
  9850. }
  9851. return patch_operations::invalid;
  9852. };
  9853. // wrapper for "add" operation; add value at ptr
  9854. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  9855. {
  9856. // adding to the root of the target document means replacing it
  9857. if (ptr.is_root())
  9858. {
  9859. result = val;
  9860. }
  9861. else
  9862. {
  9863. // make sure the top element of the pointer exists
  9864. json_pointer top_pointer = ptr.top();
  9865. if (top_pointer != ptr)
  9866. {
  9867. result.at(top_pointer);
  9868. }
  9869. // get reference to parent of JSON pointer ptr
  9870. const auto last_path = ptr.pop_back();
  9871. basic_json& parent = result[ptr];
  9872. switch (parent.m_type)
  9873. {
  9874. case value_t::null:
  9875. case value_t::object:
  9876. {
  9877. // use operator[] to add value
  9878. parent[last_path] = val;
  9879. break;
  9880. }
  9881. case value_t::array:
  9882. {
  9883. if (last_path == "-")
  9884. {
  9885. // special case: append to back
  9886. parent.push_back(val);
  9887. }
  9888. else
  9889. {
  9890. const auto idx = std::stoi(last_path);
  9891. if (static_cast<size_type>(idx) > parent.size())
  9892. {
  9893. // avoid undefined behavior
  9894. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  9895. }
  9896. else
  9897. {
  9898. // default case: insert add offset
  9899. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  9900. }
  9901. }
  9902. break;
  9903. }
  9904. default:
  9905. {
  9906. // if there exists a parent it cannot be primitive
  9907. assert(false); // LCOV_EXCL_LINE
  9908. }
  9909. }
  9910. }
  9911. };
  9912. // wrapper for "remove" operation; remove value at ptr
  9913. const auto operation_remove = [&result](json_pointer & ptr)
  9914. {
  9915. // get reference to parent of JSON pointer ptr
  9916. const auto last_path = ptr.pop_back();
  9917. basic_json& parent = result.at(ptr);
  9918. // remove child
  9919. if (parent.is_object())
  9920. {
  9921. // perform range check
  9922. auto it = parent.find(last_path);
  9923. if (it != parent.end())
  9924. {
  9925. parent.erase(it);
  9926. }
  9927. else
  9928. {
  9929. throw std::out_of_range("key '" + last_path + "' not found");
  9930. }
  9931. }
  9932. else if (parent.is_array())
  9933. {
  9934. // note erase performs range check
  9935. parent.erase(static_cast<size_type>(std::stoi(last_path)));
  9936. }
  9937. };
  9938. // type check
  9939. if (not json_patch.is_array())
  9940. {
  9941. // a JSON patch must be an array of objects
  9942. throw std::invalid_argument("JSON patch must be an array of objects");
  9943. }
  9944. // iterate and apply th eoperations
  9945. for (const auto& val : json_patch)
  9946. {
  9947. // wrapper to get a value for an operation
  9948. const auto get_value = [&val](const std::string & op,
  9949. const std::string & member,
  9950. bool string_type) -> basic_json&
  9951. {
  9952. // find value
  9953. auto it = val.m_value.object->find(member);
  9954. // context-sensitive error message
  9955. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  9956. // check if desired value is present
  9957. if (it == val.m_value.object->end())
  9958. {
  9959. throw std::invalid_argument(error_msg + " must have member '" + member + "'");
  9960. }
  9961. // check if result is of type string
  9962. if (string_type and not it->second.is_string())
  9963. {
  9964. throw std::invalid_argument(error_msg + " must have string member '" + member + "'");
  9965. }
  9966. // no error: return value
  9967. return it->second;
  9968. };
  9969. // type check
  9970. if (not val.is_object())
  9971. {
  9972. throw std::invalid_argument("JSON patch must be an array of objects");
  9973. }
  9974. // collect mandatory members
  9975. const std::string op = get_value("op", "op", true);
  9976. const std::string path = get_value(op, "path", true);
  9977. json_pointer ptr(path);
  9978. switch (get_op(op))
  9979. {
  9980. case patch_operations::add:
  9981. {
  9982. operation_add(ptr, get_value("add", "value", false));
  9983. break;
  9984. }
  9985. case patch_operations::remove:
  9986. {
  9987. operation_remove(ptr);
  9988. break;
  9989. }
  9990. case patch_operations::replace:
  9991. {
  9992. // the "path" location must exist - use at()
  9993. result.at(ptr) = get_value("replace", "value", false);
  9994. break;
  9995. }
  9996. case patch_operations::move:
  9997. {
  9998. const std::string from_path = get_value("move", "from", true);
  9999. json_pointer from_ptr(from_path);
  10000. // the "from" location must exist - use at()
  10001. basic_json v = result.at(from_ptr);
  10002. // The move operation is functionally identical to a
  10003. // "remove" operation on the "from" location, followed
  10004. // immediately by an "add" operation at the target
  10005. // location with the value that was just removed.
  10006. operation_remove(from_ptr);
  10007. operation_add(ptr, v);
  10008. break;
  10009. }
  10010. case patch_operations::copy:
  10011. {
  10012. const std::string from_path = get_value("copy", "from", true);;
  10013. const json_pointer from_ptr(from_path);
  10014. // the "from" location must exist - use at()
  10015. result[ptr] = result.at(from_ptr);
  10016. break;
  10017. }
  10018. case patch_operations::test:
  10019. {
  10020. bool success = false;
  10021. try
  10022. {
  10023. // check if "value" matches the one at "path"
  10024. // the "path" location must exist - use at()
  10025. success = (result.at(ptr) == get_value("test", "value", false));
  10026. }
  10027. catch (std::out_of_range&)
  10028. {
  10029. // ignore out of range errors: success remains false
  10030. }
  10031. // throw an exception if test fails
  10032. if (not success)
  10033. {
  10034. throw std::domain_error("unsuccessful: " + val.dump());
  10035. }
  10036. break;
  10037. }
  10038. case patch_operations::invalid:
  10039. {
  10040. // op must be "add", "remove", "replace", "move", "copy", or
  10041. // "test"
  10042. throw std::invalid_argument("operation value '" + op + "' is invalid");
  10043. }
  10044. }
  10045. }
  10046. return result;
  10047. }
  10048. /*!
  10049. @brief creates a diff as a JSON patch
  10050. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  10051. be changed into the value @a target by calling @ref patch function.
  10052. @invariant For two JSON values @a source and @a target, the following code
  10053. yields always `true`:
  10054. @code {.cpp}
  10055. source.patch(diff(source, target)) == target;
  10056. @endcode
  10057. @note Currently, only `remove`, `add`, and `replace` operations are
  10058. generated.
  10059. @param[in] source JSON value to copare from
  10060. @param[in] target JSON value to copare against
  10061. @param[in] path helper value to create JSON pointers
  10062. @return a JSON patch to convert the @a source to @a target
  10063. @complexity Linear in the lengths of @a source and @a target.
  10064. @liveexample{The following code shows how a JSON patch is created as a
  10065. diff for two JSON values.,diff}
  10066. @sa @ref patch -- apply a JSON patch
  10067. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  10068. @since version 2.0.0
  10069. */
  10070. static basic_json diff(const basic_json& source,
  10071. const basic_json& target,
  10072. const std::string& path = "")
  10073. {
  10074. // the patch
  10075. basic_json result(value_t::array);
  10076. // if the values are the same, return empty patch
  10077. if (source == target)
  10078. {
  10079. return result;
  10080. }
  10081. if (source.type() != target.type())
  10082. {
  10083. // different types: replace value
  10084. result.push_back(
  10085. {
  10086. {"op", "replace"},
  10087. {"path", path},
  10088. {"value", target}
  10089. });
  10090. }
  10091. else
  10092. {
  10093. switch (source.type())
  10094. {
  10095. case value_t::array:
  10096. {
  10097. // first pass: traverse common elements
  10098. size_t i = 0;
  10099. while (i < source.size() and i < target.size())
  10100. {
  10101. // recursive call to compare array values at index i
  10102. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  10103. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  10104. ++i;
  10105. }
  10106. // i now reached the end of at least one array
  10107. // in a second pass, traverse the remaining elements
  10108. // remove my remaining elements
  10109. const auto end_index = static_cast<difference_type>(result.size());
  10110. while (i < source.size())
  10111. {
  10112. // add operations in reverse order to avoid invalid
  10113. // indices
  10114. result.insert(result.begin() + end_index, object(
  10115. {
  10116. {"op", "remove"},
  10117. {"path", path + "/" + std::to_string(i)}
  10118. }));
  10119. ++i;
  10120. }
  10121. // add other remaining elements
  10122. while (i < target.size())
  10123. {
  10124. result.push_back(
  10125. {
  10126. {"op", "add"},
  10127. {"path", path + "/" + std::to_string(i)},
  10128. {"value", target[i]}
  10129. });
  10130. ++i;
  10131. }
  10132. break;
  10133. }
  10134. case value_t::object:
  10135. {
  10136. // first pass: traverse this object's elements
  10137. for (auto it = source.begin(); it != source.end(); ++it)
  10138. {
  10139. // escape the key name to be used in a JSON patch
  10140. const auto key = json_pointer::escape(it.key());
  10141. if (target.find(it.key()) != target.end())
  10142. {
  10143. // recursive call to compare object values at key it
  10144. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  10145. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  10146. }
  10147. else
  10148. {
  10149. // found a key that is not in o -> remove it
  10150. result.push_back(object(
  10151. {
  10152. {"op", "remove"},
  10153. {"path", path + "/" + key}
  10154. }));
  10155. }
  10156. }
  10157. // second pass: traverse other object's elements
  10158. for (auto it = target.begin(); it != target.end(); ++it)
  10159. {
  10160. if (source.find(it.key()) == source.end())
  10161. {
  10162. // found a key that is not in this -> add it
  10163. const auto key = json_pointer::escape(it.key());
  10164. result.push_back(
  10165. {
  10166. {"op", "add"},
  10167. {"path", path + "/" + key},
  10168. {"value", it.value()}
  10169. });
  10170. }
  10171. }
  10172. break;
  10173. }
  10174. default:
  10175. {
  10176. // both primitive type: replace value
  10177. result.push_back(
  10178. {
  10179. {"op", "replace"},
  10180. {"path", path},
  10181. {"value", target}
  10182. });
  10183. break;
  10184. }
  10185. }
  10186. }
  10187. return result;
  10188. }
  10189. /// @}
  10190. };
  10191. /////////////
  10192. // presets //
  10193. /////////////
  10194. /*!
  10195. @brief default JSON class
  10196. This type is the default specialization of the @ref basic_json class which
  10197. uses the standard template types.
  10198. @since version 1.0.0
  10199. */
  10200. using json = basic_json<>;
  10201. }
  10202. ///////////////////////
  10203. // nonmember support //
  10204. ///////////////////////
  10205. // specialization of std::swap, and std::hash
  10206. namespace std
  10207. {
  10208. /*!
  10209. @brief exchanges the values of two JSON objects
  10210. @since version 1.0.0
  10211. */
  10212. template<>
  10213. inline void swap(nlohmann::json& j1,
  10214. nlohmann::json& j2) noexcept(
  10215. is_nothrow_move_constructible<nlohmann::json>::value and
  10216. is_nothrow_move_assignable<nlohmann::json>::value
  10217. )
  10218. {
  10219. j1.swap(j2);
  10220. }
  10221. /// hash value for JSON objects
  10222. template<>
  10223. struct hash<nlohmann::json>
  10224. {
  10225. /*!
  10226. @brief return a hash value for a JSON object
  10227. @since version 1.0.0
  10228. */
  10229. std::size_t operator()(const nlohmann::json& j) const
  10230. {
  10231. // a naive hashing via the string representation
  10232. const auto& h = hash<nlohmann::json::string_t>();
  10233. return h(j.dump());
  10234. }
  10235. };
  10236. }
  10237. /*!
  10238. @brief user-defined string literal for JSON values
  10239. This operator implements a user-defined string literal for JSON objects. It
  10240. can be used by adding `"_json"` to a string literal and returns a JSON object
  10241. if no parse error occurred.
  10242. @param[in] s a string representation of a JSON object
  10243. @param[in] n the length of string @a s
  10244. @return a JSON object
  10245. @since version 1.0.0
  10246. */
  10247. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  10248. {
  10249. return nlohmann::json::parse(s, s + n);
  10250. }
  10251. /*!
  10252. @brief user-defined string literal for JSON pointer
  10253. This operator implements a user-defined string literal for JSON Pointers. It
  10254. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  10255. object if no parse error occurred.
  10256. @param[in] s a string representation of a JSON Pointer
  10257. @param[in] n the length of string @a s
  10258. @return a JSON pointer object
  10259. @since version 2.0.0
  10260. */
  10261. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  10262. {
  10263. return nlohmann::json::json_pointer(std::string(s, n));
  10264. }
  10265. // restore GCC/clang diagnostic settings
  10266. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  10267. #pragma GCC diagnostic pop
  10268. #endif
  10269. #endif