json.hpp 192 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254
  1. // __ _____ _____ _____
  2. // __| | __| | | | JSON for Modern C++
  3. // | | |__ | | | | | | version 3.11.2
  4. // |_____|_____|_____|_|___| https://github.com/nlohmann/json
  5. //
  6. // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me>
  7. // SPDX-License-Identifier: MIT
  8. /****************************************************************************\
  9. * Note on documentation: The source files contain links to the online *
  10. * documentation of the public API at https://json.nlohmann.me. This URL *
  11. * contains the most recent documentation and should also be applicable to *
  12. * previous versions; documentation for deprecated functions is not *
  13. * removed, but marked deprecated. See "Generate documentation" section in *
  14. * file docs/README.md. *
  15. \****************************************************************************/
  16. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  17. #define INCLUDE_NLOHMANN_JSON_HPP_
  18. #include <algorithm> // all_of, find, for_each
  19. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  20. #include <functional> // hash, less
  21. #include <initializer_list> // initializer_list
  22. #ifndef JSON_NO_IO
  23. #include <iosfwd> // istream, ostream
  24. #endif // JSON_NO_IO
  25. #include <iterator> // random_access_iterator_tag
  26. #include <memory> // unique_ptr
  27. #include <string> // string, stoi, to_string
  28. #include <utility> // declval, forward, move, pair, swap
  29. #include <vector> // vector
  30. #include <nlohmann/adl_serializer.hpp>
  31. #include <nlohmann/byte_container_with_subtype.hpp>
  32. #include <nlohmann/detail/conversions/from_json.hpp>
  33. #include <nlohmann/detail/conversions/to_json.hpp>
  34. #include <nlohmann/detail/exceptions.hpp>
  35. #include <nlohmann/detail/hash.hpp>
  36. #include <nlohmann/detail/input/binary_reader.hpp>
  37. #include <nlohmann/detail/input/input_adapters.hpp>
  38. #include <nlohmann/detail/input/lexer.hpp>
  39. #include <nlohmann/detail/input/parser.hpp>
  40. #include <nlohmann/detail/iterators/internal_iterator.hpp>
  41. #include <nlohmann/detail/iterators/iter_impl.hpp>
  42. #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  43. #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  44. #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  45. #include <nlohmann/detail/json_custom_base_class.hpp>
  46. #include <nlohmann/detail/json_pointer.hpp>
  47. #include <nlohmann/detail/json_ref.hpp>
  48. #include <nlohmann/detail/macro_scope.hpp>
  49. #include <nlohmann/detail/string_concat.hpp>
  50. #include <nlohmann/detail/string_escape.hpp>
  51. #include <nlohmann/detail/meta/cpp_future.hpp>
  52. #include <nlohmann/detail/meta/type_traits.hpp>
  53. #include <nlohmann/detail/output/binary_writer.hpp>
  54. #include <nlohmann/detail/output/output_adapters.hpp>
  55. #include <nlohmann/detail/output/serializer.hpp>
  56. #include <nlohmann/detail/value_t.hpp>
  57. #include <nlohmann/json_fwd.hpp>
  58. #include <nlohmann/ordered_map.hpp>
  59. #if defined(JSON_HAS_CPP_17)
  60. #include <any>
  61. #include <string_view>
  62. #endif
  63. /*!
  64. @brief namespace for Niels Lohmann
  65. @see https://github.com/nlohmann
  66. @since version 1.0.0
  67. */
  68. NLOHMANN_JSON_NAMESPACE_BEGIN
  69. /*!
  70. @brief a class to store JSON values
  71. @internal
  72. @invariant The member variables @a m_value and @a m_type have the following
  73. relationship:
  74. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  75. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  76. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  77. The invariants are checked by member function assert_invariant().
  78. @note ObjectType trick from https://stackoverflow.com/a/9860911
  79. @endinternal
  80. @since version 1.0.0
  81. @nosubgrouping
  82. */
  83. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  84. class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions)
  85. : public ::nlohmann::detail::json_base_class<CustomBaseClass>
  86. {
  87. private:
  88. template<detail::value_t> friend struct detail::external_constructor;
  89. template<typename>
  90. friend class ::nlohmann::json_pointer;
  91. // can be restored when json_pointer backwards compatibility is removed
  92. // friend ::nlohmann::json_pointer<StringType>;
  93. template<typename BasicJsonType, typename InputType>
  94. friend class ::nlohmann::detail::parser;
  95. friend ::nlohmann::detail::serializer<basic_json>;
  96. template<typename BasicJsonType>
  97. friend class ::nlohmann::detail::iter_impl;
  98. template<typename BasicJsonType, typename CharType>
  99. friend class ::nlohmann::detail::binary_writer;
  100. template<typename BasicJsonType, typename InputType, typename SAX>
  101. friend class ::nlohmann::detail::binary_reader;
  102. template<typename BasicJsonType>
  103. friend class ::nlohmann::detail::json_sax_dom_parser;
  104. template<typename BasicJsonType>
  105. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  106. friend class ::nlohmann::detail::exception;
  107. /// workaround type for MSVC
  108. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  109. using json_base_class_t = ::nlohmann::detail::json_base_class<CustomBaseClass>;
  110. JSON_PRIVATE_UNLESS_TESTED:
  111. // convenience aliases for types residing in namespace detail;
  112. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  113. template<typename InputAdapterType>
  114. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  115. InputAdapterType adapter,
  116. detail::parser_callback_t<basic_json>cb = nullptr,
  117. const bool allow_exceptions = true,
  118. const bool ignore_comments = false
  119. )
  120. {
  121. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  122. std::move(cb), allow_exceptions, ignore_comments);
  123. }
  124. private:
  125. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  126. template<typename BasicJsonType>
  127. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  128. template<typename BasicJsonType>
  129. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  130. template<typename Iterator>
  131. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  132. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  133. template<typename CharType>
  134. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  135. template<typename InputType>
  136. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  137. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  138. JSON_PRIVATE_UNLESS_TESTED:
  139. using serializer = ::nlohmann::detail::serializer<basic_json>;
  140. public:
  141. using value_t = detail::value_t;
  142. /// JSON Pointer, see @ref nlohmann::json_pointer
  143. using json_pointer = ::nlohmann::json_pointer<StringType>;
  144. template<typename T, typename SFINAE>
  145. using json_serializer = JSONSerializer<T, SFINAE>;
  146. /// how to treat decoding errors
  147. using error_handler_t = detail::error_handler_t;
  148. /// how to treat CBOR tags
  149. using cbor_tag_handler_t = detail::cbor_tag_handler_t;
  150. /// helper type for initializer lists of basic_json values
  151. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  152. using input_format_t = detail::input_format_t;
  153. /// SAX interface type, see @ref nlohmann::json_sax
  154. using json_sax_t = json_sax<basic_json>;
  155. ////////////////
  156. // exceptions //
  157. ////////////////
  158. /// @name exceptions
  159. /// Classes to implement user-defined exceptions.
  160. /// @{
  161. using exception = detail::exception;
  162. using parse_error = detail::parse_error;
  163. using invalid_iterator = detail::invalid_iterator;
  164. using type_error = detail::type_error;
  165. using out_of_range = detail::out_of_range;
  166. using other_error = detail::other_error;
  167. /// @}
  168. /////////////////////
  169. // container types //
  170. /////////////////////
  171. /// @name container types
  172. /// The canonic container types to use @ref basic_json like any other STL
  173. /// container.
  174. /// @{
  175. /// the type of elements in a basic_json container
  176. using value_type = basic_json;
  177. /// the type of an element reference
  178. using reference = value_type&;
  179. /// the type of an element const reference
  180. using const_reference = const value_type&;
  181. /// a type to represent differences between iterators
  182. using difference_type = std::ptrdiff_t;
  183. /// a type to represent container sizes
  184. using size_type = std::size_t;
  185. /// the allocator type
  186. using allocator_type = AllocatorType<basic_json>;
  187. /// the type of an element pointer
  188. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  189. /// the type of an element const pointer
  190. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  191. /// an iterator for a basic_json container
  192. using iterator = iter_impl<basic_json>;
  193. /// a const iterator for a basic_json container
  194. using const_iterator = iter_impl<const basic_json>;
  195. /// a reverse iterator for a basic_json container
  196. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  197. /// a const reverse iterator for a basic_json container
  198. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  199. /// @}
  200. /// @brief returns the allocator associated with the container
  201. /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/
  202. static allocator_type get_allocator()
  203. {
  204. return allocator_type();
  205. }
  206. /// @brief returns version information on the library
  207. /// @sa https://json.nlohmann.me/api/basic_json/meta/
  208. JSON_HEDLEY_WARN_UNUSED_RESULT
  209. static basic_json meta()
  210. {
  211. basic_json result;
  212. result["copyright"] = "(C) 2013-2022 Niels Lohmann";
  213. result["name"] = "JSON for Modern C++";
  214. result["url"] = "https://github.com/nlohmann/json";
  215. result["version"]["string"] =
  216. detail::concat(std::to_string(NLOHMANN_JSON_VERSION_MAJOR), '.',
  217. std::to_string(NLOHMANN_JSON_VERSION_MINOR), '.',
  218. std::to_string(NLOHMANN_JSON_VERSION_PATCH));
  219. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  220. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  221. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  222. #ifdef _WIN32
  223. result["platform"] = "win32";
  224. #elif defined __linux__
  225. result["platform"] = "linux";
  226. #elif defined __APPLE__
  227. result["platform"] = "apple";
  228. #elif defined __unix__
  229. result["platform"] = "unix";
  230. #else
  231. result["platform"] = "unknown";
  232. #endif
  233. #if defined(__ICC) || defined(__INTEL_COMPILER)
  234. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  235. #elif defined(__clang__)
  236. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  237. #elif defined(__GNUC__) || defined(__GNUG__)
  238. result["compiler"] = {{"family", "gcc"}, {"version", detail::concat(
  239. std::to_string(__GNUC__), '.',
  240. std::to_string(__GNUC_MINOR__), '.',
  241. std::to_string(__GNUC_PATCHLEVEL__))
  242. }
  243. };
  244. #elif defined(__HP_cc) || defined(__HP_aCC)
  245. result["compiler"] = "hp"
  246. #elif defined(__IBMCPP__)
  247. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  248. #elif defined(_MSC_VER)
  249. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  250. #elif defined(__PGI)
  251. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  252. #elif defined(__SUNPRO_CC)
  253. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  254. #else
  255. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  256. #endif
  257. #if defined(_MSVC_LANG)
  258. result["compiler"]["c++"] = std::to_string(_MSVC_LANG);
  259. #elif defined(__cplusplus)
  260. result["compiler"]["c++"] = std::to_string(__cplusplus);
  261. #else
  262. result["compiler"]["c++"] = "unknown";
  263. #endif
  264. return result;
  265. }
  266. ///////////////////////////
  267. // JSON value data types //
  268. ///////////////////////////
  269. /// @name JSON value data types
  270. /// The data types to store a JSON value. These types are derived from
  271. /// the template arguments passed to class @ref basic_json.
  272. /// @{
  273. /// @brief default object key comparator type
  274. /// The actual object key comparator type (@ref object_comparator_t) may be
  275. /// different.
  276. /// @sa https://json.nlohmann.me/api/basic_json/default_object_comparator_t/
  277. #if defined(JSON_HAS_CPP_14)
  278. // use of transparent comparator avoids unnecessary repeated construction of temporaries
  279. // in functions involving lookup by key with types other than object_t::key_type (aka. StringType)
  280. using default_object_comparator_t = std::less<>;
  281. #else
  282. using default_object_comparator_t = std::less<StringType>;
  283. #endif
  284. /// @brief a type for an object
  285. /// @sa https://json.nlohmann.me/api/basic_json/object_t/
  286. using object_t = ObjectType<StringType,
  287. basic_json,
  288. default_object_comparator_t,
  289. AllocatorType<std::pair<const StringType,
  290. basic_json>>>;
  291. /// @brief a type for an array
  292. /// @sa https://json.nlohmann.me/api/basic_json/array_t/
  293. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  294. /// @brief a type for a string
  295. /// @sa https://json.nlohmann.me/api/basic_json/string_t/
  296. using string_t = StringType;
  297. /// @brief a type for a boolean
  298. /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/
  299. using boolean_t = BooleanType;
  300. /// @brief a type for a number (integer)
  301. /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/
  302. using number_integer_t = NumberIntegerType;
  303. /// @brief a type for a number (unsigned)
  304. /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/
  305. using number_unsigned_t = NumberUnsignedType;
  306. /// @brief a type for a number (floating-point)
  307. /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/
  308. using number_float_t = NumberFloatType;
  309. /// @brief a type for a packed binary type
  310. /// @sa https://json.nlohmann.me/api/basic_json/binary_t/
  311. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  312. /// @brief object key comparator type
  313. /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/
  314. using object_comparator_t = detail::actual_object_comparator_t<basic_json>;
  315. /// @}
  316. private:
  317. /// helper for exception-safe object creation
  318. template<typename T, typename... Args>
  319. JSON_HEDLEY_RETURNS_NON_NULL
  320. static T* create(Args&& ... args)
  321. {
  322. AllocatorType<T> alloc;
  323. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  324. auto deleter = [&](T * obj)
  325. {
  326. AllocatorTraits::deallocate(alloc, obj, 1);
  327. };
  328. std::unique_ptr<T, decltype(deleter)> obj(AllocatorTraits::allocate(alloc, 1), deleter);
  329. AllocatorTraits::construct(alloc, obj.get(), std::forward<Args>(args)...);
  330. JSON_ASSERT(obj != nullptr);
  331. return obj.release();
  332. }
  333. ////////////////////////
  334. // JSON value storage //
  335. ////////////////////////
  336. JSON_PRIVATE_UNLESS_TESTED:
  337. /*!
  338. @brief a JSON value
  339. The actual storage for a JSON value of the @ref basic_json class. This
  340. union combines the different storage types for the JSON value types
  341. defined in @ref value_t.
  342. JSON type | value_t type | used type
  343. --------- | --------------- | ------------------------
  344. object | object | pointer to @ref object_t
  345. array | array | pointer to @ref array_t
  346. string | string | pointer to @ref string_t
  347. boolean | boolean | @ref boolean_t
  348. number | number_integer | @ref number_integer_t
  349. number | number_unsigned | @ref number_unsigned_t
  350. number | number_float | @ref number_float_t
  351. binary | binary | pointer to @ref binary_t
  352. null | null | *no value is stored*
  353. @note Variable-length types (objects, arrays, and strings) are stored as
  354. pointers. The size of the union should not exceed 64 bits if the default
  355. value types are used.
  356. @since version 1.0.0
  357. */
  358. union json_value
  359. {
  360. /// object (stored with pointer to save storage)
  361. object_t* object;
  362. /// array (stored with pointer to save storage)
  363. array_t* array;
  364. /// string (stored with pointer to save storage)
  365. string_t* string;
  366. /// binary (stored with pointer to save storage)
  367. binary_t* binary;
  368. /// boolean
  369. boolean_t boolean;
  370. /// number (integer)
  371. number_integer_t number_integer;
  372. /// number (unsigned integer)
  373. number_unsigned_t number_unsigned;
  374. /// number (floating-point)
  375. number_float_t number_float;
  376. /// default constructor (for null values)
  377. json_value() = default;
  378. /// constructor for booleans
  379. json_value(boolean_t v) noexcept : boolean(v) {}
  380. /// constructor for numbers (integer)
  381. json_value(number_integer_t v) noexcept : number_integer(v) {}
  382. /// constructor for numbers (unsigned)
  383. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  384. /// constructor for numbers (floating-point)
  385. json_value(number_float_t v) noexcept : number_float(v) {}
  386. /// constructor for empty values of a given type
  387. json_value(value_t t)
  388. {
  389. switch (t)
  390. {
  391. case value_t::object:
  392. {
  393. object = create<object_t>();
  394. break;
  395. }
  396. case value_t::array:
  397. {
  398. array = create<array_t>();
  399. break;
  400. }
  401. case value_t::string:
  402. {
  403. string = create<string_t>("");
  404. break;
  405. }
  406. case value_t::binary:
  407. {
  408. binary = create<binary_t>();
  409. break;
  410. }
  411. case value_t::boolean:
  412. {
  413. boolean = static_cast<boolean_t>(false);
  414. break;
  415. }
  416. case value_t::number_integer:
  417. {
  418. number_integer = static_cast<number_integer_t>(0);
  419. break;
  420. }
  421. case value_t::number_unsigned:
  422. {
  423. number_unsigned = static_cast<number_unsigned_t>(0);
  424. break;
  425. }
  426. case value_t::number_float:
  427. {
  428. number_float = static_cast<number_float_t>(0.0);
  429. break;
  430. }
  431. case value_t::null:
  432. {
  433. object = nullptr; // silence warning, see #821
  434. break;
  435. }
  436. case value_t::discarded:
  437. default:
  438. {
  439. object = nullptr; // silence warning, see #821
  440. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  441. {
  442. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.11.2", nullptr)); // LCOV_EXCL_LINE
  443. }
  444. break;
  445. }
  446. }
  447. }
  448. /// constructor for strings
  449. json_value(const string_t& value) : string(create<string_t>(value)) {}
  450. /// constructor for rvalue strings
  451. json_value(string_t&& value) : string(create<string_t>(std::move(value))) {}
  452. /// constructor for objects
  453. json_value(const object_t& value) : object(create<object_t>(value)) {}
  454. /// constructor for rvalue objects
  455. json_value(object_t&& value) : object(create<object_t>(std::move(value))) {}
  456. /// constructor for arrays
  457. json_value(const array_t& value) : array(create<array_t>(value)) {}
  458. /// constructor for rvalue arrays
  459. json_value(array_t&& value) : array(create<array_t>(std::move(value))) {}
  460. /// constructor for binary arrays
  461. json_value(const typename binary_t::container_type& value) : binary(create<binary_t>(value)) {}
  462. /// constructor for rvalue binary arrays
  463. json_value(typename binary_t::container_type&& value) : binary(create<binary_t>(std::move(value))) {}
  464. /// constructor for binary arrays (internal type)
  465. json_value(const binary_t& value) : binary(create<binary_t>(value)) {}
  466. /// constructor for rvalue binary arrays (internal type)
  467. json_value(binary_t&& value) : binary(create<binary_t>(std::move(value))) {}
  468. void destroy(value_t t)
  469. {
  470. if (
  471. (t == value_t::object && object == nullptr) ||
  472. (t == value_t::array && array == nullptr) ||
  473. (t == value_t::string && string == nullptr) ||
  474. (t == value_t::binary && binary == nullptr)
  475. )
  476. {
  477. //not initialized (e.g. due to exception in the ctor)
  478. return;
  479. }
  480. if (t == value_t::array || t == value_t::object)
  481. {
  482. // flatten the current json_value to a heap-allocated stack
  483. std::vector<basic_json> stack;
  484. // move the top-level items to stack
  485. if (t == value_t::array)
  486. {
  487. stack.reserve(array->size());
  488. std::move(array->begin(), array->end(), std::back_inserter(stack));
  489. }
  490. else
  491. {
  492. stack.reserve(object->size());
  493. for (auto&& it : *object)
  494. {
  495. stack.push_back(std::move(it.second));
  496. }
  497. }
  498. while (!stack.empty())
  499. {
  500. // move the last item to local variable to be processed
  501. basic_json current_item(std::move(stack.back()));
  502. stack.pop_back();
  503. // if current_item is array/object, move
  504. // its children to the stack to be processed later
  505. if (current_item.is_array())
  506. {
  507. std::move(current_item.m_data.m_value.array->begin(), current_item.m_data.m_value.array->end(), std::back_inserter(stack));
  508. current_item.m_data.m_value.array->clear();
  509. }
  510. else if (current_item.is_object())
  511. {
  512. for (auto&& it : *current_item.m_data.m_value.object)
  513. {
  514. stack.push_back(std::move(it.second));
  515. }
  516. current_item.m_data.m_value.object->clear();
  517. }
  518. // it's now safe that current_item get destructed
  519. // since it doesn't have any children
  520. }
  521. }
  522. switch (t)
  523. {
  524. case value_t::object:
  525. {
  526. AllocatorType<object_t> alloc;
  527. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  528. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  529. break;
  530. }
  531. case value_t::array:
  532. {
  533. AllocatorType<array_t> alloc;
  534. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  535. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  536. break;
  537. }
  538. case value_t::string:
  539. {
  540. AllocatorType<string_t> alloc;
  541. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  542. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  543. break;
  544. }
  545. case value_t::binary:
  546. {
  547. AllocatorType<binary_t> alloc;
  548. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  549. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  550. break;
  551. }
  552. case value_t::null:
  553. case value_t::boolean:
  554. case value_t::number_integer:
  555. case value_t::number_unsigned:
  556. case value_t::number_float:
  557. case value_t::discarded:
  558. default:
  559. {
  560. break;
  561. }
  562. }
  563. }
  564. };
  565. private:
  566. /*!
  567. @brief checks the class invariants
  568. This function asserts the class invariants. It needs to be called at the
  569. end of every constructor to make sure that created objects respect the
  570. invariant. Furthermore, it has to be called each time the type of a JSON
  571. value is changed, because the invariant expresses a relationship between
  572. @a m_type and @a m_value.
  573. Furthermore, the parent relation is checked for arrays and objects: If
  574. @a check_parents true and the value is an array or object, then the
  575. container's elements must have the current value as parent.
  576. @param[in] check_parents whether the parent relation should be checked.
  577. The value is true by default and should only be set to false
  578. during destruction of objects when the invariant does not
  579. need to hold.
  580. */
  581. void assert_invariant(bool check_parents = true) const noexcept
  582. {
  583. JSON_ASSERT(m_data.m_type != value_t::object || m_data.m_value.object != nullptr);
  584. JSON_ASSERT(m_data.m_type != value_t::array || m_data.m_value.array != nullptr);
  585. JSON_ASSERT(m_data.m_type != value_t::string || m_data.m_value.string != nullptr);
  586. JSON_ASSERT(m_data.m_type != value_t::binary || m_data.m_value.binary != nullptr);
  587. #if JSON_DIAGNOSTICS
  588. JSON_TRY
  589. {
  590. // cppcheck-suppress assertWithSideEffect
  591. JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j)
  592. {
  593. return j.m_parent == this;
  594. }));
  595. }
  596. JSON_CATCH(...) {} // LCOV_EXCL_LINE
  597. #endif
  598. static_cast<void>(check_parents);
  599. }
  600. void set_parents()
  601. {
  602. #if JSON_DIAGNOSTICS
  603. switch (m_data.m_type)
  604. {
  605. case value_t::array:
  606. {
  607. for (auto& element : *m_data.m_value.array)
  608. {
  609. element.m_parent = this;
  610. }
  611. break;
  612. }
  613. case value_t::object:
  614. {
  615. for (auto& element : *m_data.m_value.object)
  616. {
  617. element.second.m_parent = this;
  618. }
  619. break;
  620. }
  621. case value_t::null:
  622. case value_t::string:
  623. case value_t::boolean:
  624. case value_t::number_integer:
  625. case value_t::number_unsigned:
  626. case value_t::number_float:
  627. case value_t::binary:
  628. case value_t::discarded:
  629. default:
  630. break;
  631. }
  632. #endif
  633. }
  634. iterator set_parents(iterator it, typename iterator::difference_type count_set_parents)
  635. {
  636. #if JSON_DIAGNOSTICS
  637. for (typename iterator::difference_type i = 0; i < count_set_parents; ++i)
  638. {
  639. (it + i)->m_parent = this;
  640. }
  641. #else
  642. static_cast<void>(count_set_parents);
  643. #endif
  644. return it;
  645. }
  646. reference set_parent(reference j, std::size_t old_capacity = static_cast<std::size_t>(-1))
  647. {
  648. #if JSON_DIAGNOSTICS
  649. if (old_capacity != static_cast<std::size_t>(-1))
  650. {
  651. // see https://github.com/nlohmann/json/issues/2838
  652. JSON_ASSERT(type() == value_t::array);
  653. if (JSON_HEDLEY_UNLIKELY(m_data.m_value.array->capacity() != old_capacity))
  654. {
  655. // capacity has changed: update all parents
  656. set_parents();
  657. return j;
  658. }
  659. }
  660. // ordered_json uses a vector internally, so pointers could have
  661. // been invalidated; see https://github.com/nlohmann/json/issues/2962
  662. #ifdef JSON_HEDLEY_MSVC_VERSION
  663. #pragma warning(push )
  664. #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
  665. #endif
  666. if (detail::is_ordered_map<object_t>::value)
  667. {
  668. set_parents();
  669. return j;
  670. }
  671. #ifdef JSON_HEDLEY_MSVC_VERSION
  672. #pragma warning( pop )
  673. #endif
  674. j.m_parent = this;
  675. #else
  676. static_cast<void>(j);
  677. static_cast<void>(old_capacity);
  678. #endif
  679. return j;
  680. }
  681. public:
  682. //////////////////////////
  683. // JSON parser callback //
  684. //////////////////////////
  685. /// @brief parser event types
  686. /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/
  687. using parse_event_t = detail::parse_event_t;
  688. /// @brief per-element parser callback type
  689. /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/
  690. using parser_callback_t = detail::parser_callback_t<basic_json>;
  691. //////////////////
  692. // constructors //
  693. //////////////////
  694. /// @name constructors and destructors
  695. /// Constructors of class @ref basic_json, copy/move constructor, copy
  696. /// assignment, static functions creating objects, and the destructor.
  697. /// @{
  698. /// @brief create an empty value with a given type
  699. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  700. basic_json(const value_t v)
  701. : m_data(v)
  702. {
  703. assert_invariant();
  704. }
  705. /// @brief create a null object
  706. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  707. basic_json(std::nullptr_t = nullptr) noexcept // NOLINT(bugprone-exception-escape)
  708. : basic_json(value_t::null)
  709. {
  710. assert_invariant();
  711. }
  712. /// @brief create a JSON value from compatible types
  713. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  714. template < typename CompatibleType,
  715. typename U = detail::uncvref_t<CompatibleType>,
  716. detail::enable_if_t <
  717. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  718. basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape)
  719. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  720. std::forward<CompatibleType>(val))))
  721. {
  722. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  723. set_parents();
  724. assert_invariant();
  725. }
  726. /// @brief create a JSON value from an existing one
  727. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  728. template < typename BasicJsonType,
  729. detail::enable_if_t <
  730. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  731. basic_json(const BasicJsonType& val)
  732. {
  733. using other_boolean_t = typename BasicJsonType::boolean_t;
  734. using other_number_float_t = typename BasicJsonType::number_float_t;
  735. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  736. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  737. using other_string_t = typename BasicJsonType::string_t;
  738. using other_object_t = typename BasicJsonType::object_t;
  739. using other_array_t = typename BasicJsonType::array_t;
  740. using other_binary_t = typename BasicJsonType::binary_t;
  741. switch (val.type())
  742. {
  743. case value_t::boolean:
  744. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  745. break;
  746. case value_t::number_float:
  747. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  748. break;
  749. case value_t::number_integer:
  750. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  751. break;
  752. case value_t::number_unsigned:
  753. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  754. break;
  755. case value_t::string:
  756. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  757. break;
  758. case value_t::object:
  759. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  760. break;
  761. case value_t::array:
  762. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  763. break;
  764. case value_t::binary:
  765. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  766. break;
  767. case value_t::null:
  768. *this = nullptr;
  769. break;
  770. case value_t::discarded:
  771. m_data.m_type = value_t::discarded;
  772. break;
  773. default: // LCOV_EXCL_LINE
  774. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  775. }
  776. JSON_ASSERT(m_data.m_type == val.type());
  777. set_parents();
  778. assert_invariant();
  779. }
  780. /// @brief create a container (array or object) from an initializer list
  781. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  782. basic_json(initializer_list_t init,
  783. bool type_deduction = true,
  784. value_t manual_type = value_t::array)
  785. {
  786. // check if each element is an array with two elements whose first
  787. // element is a string
  788. bool is_an_object = std::all_of(init.begin(), init.end(),
  789. [](const detail::json_ref<basic_json>& element_ref)
  790. {
  791. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  792. });
  793. // adjust type if type deduction is not wanted
  794. if (!type_deduction)
  795. {
  796. // if array is wanted, do not create an object though possible
  797. if (manual_type == value_t::array)
  798. {
  799. is_an_object = false;
  800. }
  801. // if object is wanted but impossible, throw an exception
  802. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  803. {
  804. JSON_THROW(type_error::create(301, "cannot create object from initializer list", nullptr));
  805. }
  806. }
  807. if (is_an_object)
  808. {
  809. // the initializer list is a list of pairs -> create object
  810. m_data.m_type = value_t::object;
  811. m_data.m_value = value_t::object;
  812. for (auto& element_ref : init)
  813. {
  814. auto element = element_ref.moved_or_copied();
  815. m_data.m_value.object->emplace(
  816. std::move(*((*element.m_data.m_value.array)[0].m_data.m_value.string)),
  817. std::move((*element.m_data.m_value.array)[1]));
  818. }
  819. }
  820. else
  821. {
  822. // the initializer list describes an array -> create array
  823. m_data.m_type = value_t::array;
  824. m_data.m_value.array = create<array_t>(init.begin(), init.end());
  825. }
  826. set_parents();
  827. assert_invariant();
  828. }
  829. /// @brief explicitly create a binary array (without subtype)
  830. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  831. JSON_HEDLEY_WARN_UNUSED_RESULT
  832. static basic_json binary(const typename binary_t::container_type& init)
  833. {
  834. auto res = basic_json();
  835. res.m_data.m_type = value_t::binary;
  836. res.m_data.m_value = init;
  837. return res;
  838. }
  839. /// @brief explicitly create a binary array (with subtype)
  840. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  841. JSON_HEDLEY_WARN_UNUSED_RESULT
  842. static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype)
  843. {
  844. auto res = basic_json();
  845. res.m_data.m_type = value_t::binary;
  846. res.m_data.m_value = binary_t(init, subtype);
  847. return res;
  848. }
  849. /// @brief explicitly create a binary array
  850. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  851. JSON_HEDLEY_WARN_UNUSED_RESULT
  852. static basic_json binary(typename binary_t::container_type&& init)
  853. {
  854. auto res = basic_json();
  855. res.m_data.m_type = value_t::binary;
  856. res.m_data.m_value = std::move(init);
  857. return res;
  858. }
  859. /// @brief explicitly create a binary array (with subtype)
  860. /// @sa https://json.nlohmann.me/api/basic_json/binary/
  861. JSON_HEDLEY_WARN_UNUSED_RESULT
  862. static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype)
  863. {
  864. auto res = basic_json();
  865. res.m_data.m_type = value_t::binary;
  866. res.m_data.m_value = binary_t(std::move(init), subtype);
  867. return res;
  868. }
  869. /// @brief explicitly create an array from an initializer list
  870. /// @sa https://json.nlohmann.me/api/basic_json/array/
  871. JSON_HEDLEY_WARN_UNUSED_RESULT
  872. static basic_json array(initializer_list_t init = {})
  873. {
  874. return basic_json(init, false, value_t::array);
  875. }
  876. /// @brief explicitly create an object from an initializer list
  877. /// @sa https://json.nlohmann.me/api/basic_json/object/
  878. JSON_HEDLEY_WARN_UNUSED_RESULT
  879. static basic_json object(initializer_list_t init = {})
  880. {
  881. return basic_json(init, false, value_t::object);
  882. }
  883. /// @brief construct an array with count copies of given value
  884. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  885. basic_json(size_type cnt, const basic_json& val):
  886. m_data{cnt, val}
  887. {
  888. set_parents();
  889. assert_invariant();
  890. }
  891. /// @brief construct a JSON container given an iterator range
  892. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  893. template < class InputIT, typename std::enable_if <
  894. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  895. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  896. basic_json(InputIT first, InputIT last)
  897. {
  898. JSON_ASSERT(first.m_object != nullptr);
  899. JSON_ASSERT(last.m_object != nullptr);
  900. // make sure iterator fits the current value
  901. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  902. {
  903. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", nullptr));
  904. }
  905. // copy type from first iterator
  906. m_data.m_type = first.m_object->m_data.m_type;
  907. // check if iterator range is complete for primitive values
  908. switch (m_data.m_type)
  909. {
  910. case value_t::boolean:
  911. case value_t::number_float:
  912. case value_t::number_integer:
  913. case value_t::number_unsigned:
  914. case value_t::string:
  915. {
  916. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  917. || !last.m_it.primitive_iterator.is_end()))
  918. {
  919. JSON_THROW(invalid_iterator::create(204, "iterators out of range", first.m_object));
  920. }
  921. break;
  922. }
  923. case value_t::null:
  924. case value_t::object:
  925. case value_t::array:
  926. case value_t::binary:
  927. case value_t::discarded:
  928. default:
  929. break;
  930. }
  931. switch (m_data.m_type)
  932. {
  933. case value_t::number_integer:
  934. {
  935. m_data.m_value.number_integer = first.m_object->m_data.m_value.number_integer;
  936. break;
  937. }
  938. case value_t::number_unsigned:
  939. {
  940. m_data.m_value.number_unsigned = first.m_object->m_data.m_value.number_unsigned;
  941. break;
  942. }
  943. case value_t::number_float:
  944. {
  945. m_data.m_value.number_float = first.m_object->m_data.m_value.number_float;
  946. break;
  947. }
  948. case value_t::boolean:
  949. {
  950. m_data.m_value.boolean = first.m_object->m_data.m_value.boolean;
  951. break;
  952. }
  953. case value_t::string:
  954. {
  955. m_data.m_value = *first.m_object->m_data.m_value.string;
  956. break;
  957. }
  958. case value_t::object:
  959. {
  960. m_data.m_value.object = create<object_t>(first.m_it.object_iterator,
  961. last.m_it.object_iterator);
  962. break;
  963. }
  964. case value_t::array:
  965. {
  966. m_data.m_value.array = create<array_t>(first.m_it.array_iterator,
  967. last.m_it.array_iterator);
  968. break;
  969. }
  970. case value_t::binary:
  971. {
  972. m_data.m_value = *first.m_object->m_data.m_value.binary;
  973. break;
  974. }
  975. case value_t::null:
  976. case value_t::discarded:
  977. default:
  978. JSON_THROW(invalid_iterator::create(206, detail::concat("cannot construct with iterators from ", first.m_object->type_name()), first.m_object));
  979. }
  980. set_parents();
  981. assert_invariant();
  982. }
  983. ///////////////////////////////////////
  984. // other constructors and destructor //
  985. ///////////////////////////////////////
  986. template<typename JsonRef,
  987. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  988. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  989. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  990. /// @brief copy constructor
  991. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  992. basic_json(const basic_json& other)
  993. : json_base_class_t(other)
  994. {
  995. m_data.m_type = other.m_data.m_type;
  996. // check of passed value is valid
  997. other.assert_invariant();
  998. switch (m_data.m_type)
  999. {
  1000. case value_t::object:
  1001. {
  1002. m_data.m_value = *other.m_data.m_value.object;
  1003. break;
  1004. }
  1005. case value_t::array:
  1006. {
  1007. m_data.m_value = *other.m_data.m_value.array;
  1008. break;
  1009. }
  1010. case value_t::string:
  1011. {
  1012. m_data.m_value = *other.m_data.m_value.string;
  1013. break;
  1014. }
  1015. case value_t::boolean:
  1016. {
  1017. m_data.m_value = other.m_data.m_value.boolean;
  1018. break;
  1019. }
  1020. case value_t::number_integer:
  1021. {
  1022. m_data.m_value = other.m_data.m_value.number_integer;
  1023. break;
  1024. }
  1025. case value_t::number_unsigned:
  1026. {
  1027. m_data.m_value = other.m_data.m_value.number_unsigned;
  1028. break;
  1029. }
  1030. case value_t::number_float:
  1031. {
  1032. m_data.m_value = other.m_data.m_value.number_float;
  1033. break;
  1034. }
  1035. case value_t::binary:
  1036. {
  1037. m_data.m_value = *other.m_data.m_value.binary;
  1038. break;
  1039. }
  1040. case value_t::null:
  1041. case value_t::discarded:
  1042. default:
  1043. break;
  1044. }
  1045. set_parents();
  1046. assert_invariant();
  1047. }
  1048. /// @brief move constructor
  1049. /// @sa https://json.nlohmann.me/api/basic_json/basic_json/
  1050. basic_json(basic_json&& other) noexcept
  1051. : json_base_class_t(std::forward<json_base_class_t>(other)),
  1052. m_data(std::move(other.m_data))
  1053. {
  1054. // check that passed value is valid
  1055. other.assert_invariant(false);
  1056. // invalidate payload
  1057. other.m_data.m_type = value_t::null;
  1058. other.m_data.m_value = {};
  1059. set_parents();
  1060. assert_invariant();
  1061. }
  1062. /// @brief copy assignment
  1063. /// @sa https://json.nlohmann.me/api/basic_json/operator=/
  1064. basic_json& operator=(basic_json other) noexcept (
  1065. std::is_nothrow_move_constructible<value_t>::value&&
  1066. std::is_nothrow_move_assignable<value_t>::value&&
  1067. std::is_nothrow_move_constructible<json_value>::value&&
  1068. std::is_nothrow_move_assignable<json_value>::value&&
  1069. std::is_nothrow_move_assignable<json_base_class_t>::value
  1070. )
  1071. {
  1072. // check that passed value is valid
  1073. other.assert_invariant();
  1074. using std::swap;
  1075. swap(m_data.m_type, other.m_data.m_type);
  1076. swap(m_data.m_value, other.m_data.m_value);
  1077. json_base_class_t::operator=(std::move(other));
  1078. set_parents();
  1079. assert_invariant();
  1080. return *this;
  1081. }
  1082. /// @brief destructor
  1083. /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/
  1084. ~basic_json() noexcept
  1085. {
  1086. assert_invariant(false);
  1087. }
  1088. /// @}
  1089. public:
  1090. ///////////////////////
  1091. // object inspection //
  1092. ///////////////////////
  1093. /// @name object inspection
  1094. /// Functions to inspect the type of a JSON value.
  1095. /// @{
  1096. /// @brief serialization
  1097. /// @sa https://json.nlohmann.me/api/basic_json/dump/
  1098. string_t dump(const int indent = -1,
  1099. const char indent_char = ' ',
  1100. const bool ensure_ascii = false,
  1101. const error_handler_t error_handler = error_handler_t::strict) const
  1102. {
  1103. string_t result;
  1104. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  1105. if (indent >= 0)
  1106. {
  1107. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  1108. }
  1109. else
  1110. {
  1111. s.dump(*this, false, ensure_ascii, 0);
  1112. }
  1113. return result;
  1114. }
  1115. /// @brief return the type of the JSON value (explicit)
  1116. /// @sa https://json.nlohmann.me/api/basic_json/type/
  1117. constexpr value_t type() const noexcept
  1118. {
  1119. return m_data.m_type;
  1120. }
  1121. /// @brief return whether type is primitive
  1122. /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/
  1123. constexpr bool is_primitive() const noexcept
  1124. {
  1125. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  1126. }
  1127. /// @brief return whether type is structured
  1128. /// @sa https://json.nlohmann.me/api/basic_json/is_structured/
  1129. constexpr bool is_structured() const noexcept
  1130. {
  1131. return is_array() || is_object();
  1132. }
  1133. /// @brief return whether value is null
  1134. /// @sa https://json.nlohmann.me/api/basic_json/is_null/
  1135. constexpr bool is_null() const noexcept
  1136. {
  1137. return m_data.m_type == value_t::null;
  1138. }
  1139. /// @brief return whether value is a boolean
  1140. /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/
  1141. constexpr bool is_boolean() const noexcept
  1142. {
  1143. return m_data.m_type == value_t::boolean;
  1144. }
  1145. /// @brief return whether value is a number
  1146. /// @sa https://json.nlohmann.me/api/basic_json/is_number/
  1147. constexpr bool is_number() const noexcept
  1148. {
  1149. return is_number_integer() || is_number_float();
  1150. }
  1151. /// @brief return whether value is an integer number
  1152. /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/
  1153. constexpr bool is_number_integer() const noexcept
  1154. {
  1155. return m_data.m_type == value_t::number_integer || m_data.m_type == value_t::number_unsigned;
  1156. }
  1157. /// @brief return whether value is an unsigned integer number
  1158. /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/
  1159. constexpr bool is_number_unsigned() const noexcept
  1160. {
  1161. return m_data.m_type == value_t::number_unsigned;
  1162. }
  1163. /// @brief return whether value is a floating-point number
  1164. /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/
  1165. constexpr bool is_number_float() const noexcept
  1166. {
  1167. return m_data.m_type == value_t::number_float;
  1168. }
  1169. /// @brief return whether value is an object
  1170. /// @sa https://json.nlohmann.me/api/basic_json/is_object/
  1171. constexpr bool is_object() const noexcept
  1172. {
  1173. return m_data.m_type == value_t::object;
  1174. }
  1175. /// @brief return whether value is an array
  1176. /// @sa https://json.nlohmann.me/api/basic_json/is_array/
  1177. constexpr bool is_array() const noexcept
  1178. {
  1179. return m_data.m_type == value_t::array;
  1180. }
  1181. /// @brief return whether value is a string
  1182. /// @sa https://json.nlohmann.me/api/basic_json/is_string/
  1183. constexpr bool is_string() const noexcept
  1184. {
  1185. return m_data.m_type == value_t::string;
  1186. }
  1187. /// @brief return whether value is a binary array
  1188. /// @sa https://json.nlohmann.me/api/basic_json/is_binary/
  1189. constexpr bool is_binary() const noexcept
  1190. {
  1191. return m_data.m_type == value_t::binary;
  1192. }
  1193. /// @brief return whether value is discarded
  1194. /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/
  1195. constexpr bool is_discarded() const noexcept
  1196. {
  1197. return m_data.m_type == value_t::discarded;
  1198. }
  1199. /// @brief return the type of the JSON value (implicit)
  1200. /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/
  1201. constexpr operator value_t() const noexcept
  1202. {
  1203. return m_data.m_type;
  1204. }
  1205. /// @}
  1206. private:
  1207. //////////////////
  1208. // value access //
  1209. //////////////////
  1210. /// get a boolean (explicit)
  1211. boolean_t get_impl(boolean_t* /*unused*/) const
  1212. {
  1213. if (JSON_HEDLEY_LIKELY(is_boolean()))
  1214. {
  1215. return m_data.m_value.boolean;
  1216. }
  1217. JSON_THROW(type_error::create(302, detail::concat("type must be boolean, but is ", type_name()), this));
  1218. }
  1219. /// get a pointer to the value (object)
  1220. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  1221. {
  1222. return is_object() ? m_data.m_value.object : nullptr;
  1223. }
  1224. /// get a pointer to the value (object)
  1225. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  1226. {
  1227. return is_object() ? m_data.m_value.object : nullptr;
  1228. }
  1229. /// get a pointer to the value (array)
  1230. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  1231. {
  1232. return is_array() ? m_data.m_value.array : nullptr;
  1233. }
  1234. /// get a pointer to the value (array)
  1235. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  1236. {
  1237. return is_array() ? m_data.m_value.array : nullptr;
  1238. }
  1239. /// get a pointer to the value (string)
  1240. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  1241. {
  1242. return is_string() ? m_data.m_value.string : nullptr;
  1243. }
  1244. /// get a pointer to the value (string)
  1245. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  1246. {
  1247. return is_string() ? m_data.m_value.string : nullptr;
  1248. }
  1249. /// get a pointer to the value (boolean)
  1250. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  1251. {
  1252. return is_boolean() ? &m_data.m_value.boolean : nullptr;
  1253. }
  1254. /// get a pointer to the value (boolean)
  1255. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  1256. {
  1257. return is_boolean() ? &m_data.m_value.boolean : nullptr;
  1258. }
  1259. /// get a pointer to the value (integer number)
  1260. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  1261. {
  1262. return is_number_integer() ? &m_data.m_value.number_integer : nullptr;
  1263. }
  1264. /// get a pointer to the value (integer number)
  1265. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  1266. {
  1267. return is_number_integer() ? &m_data.m_value.number_integer : nullptr;
  1268. }
  1269. /// get a pointer to the value (unsigned number)
  1270. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  1271. {
  1272. return is_number_unsigned() ? &m_data.m_value.number_unsigned : nullptr;
  1273. }
  1274. /// get a pointer to the value (unsigned number)
  1275. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  1276. {
  1277. return is_number_unsigned() ? &m_data.m_value.number_unsigned : nullptr;
  1278. }
  1279. /// get a pointer to the value (floating-point number)
  1280. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  1281. {
  1282. return is_number_float() ? &m_data.m_value.number_float : nullptr;
  1283. }
  1284. /// get a pointer to the value (floating-point number)
  1285. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  1286. {
  1287. return is_number_float() ? &m_data.m_value.number_float : nullptr;
  1288. }
  1289. /// get a pointer to the value (binary)
  1290. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  1291. {
  1292. return is_binary() ? m_data.m_value.binary : nullptr;
  1293. }
  1294. /// get a pointer to the value (binary)
  1295. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  1296. {
  1297. return is_binary() ? m_data.m_value.binary : nullptr;
  1298. }
  1299. /*!
  1300. @brief helper function to implement get_ref()
  1301. This function helps to implement get_ref() without code duplication for
  1302. const and non-const overloads
  1303. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  1304. @throw type_error.303 if ReferenceType does not match underlying value
  1305. type of the current JSON
  1306. */
  1307. template<typename ReferenceType, typename ThisType>
  1308. static ReferenceType get_ref_impl(ThisType& obj)
  1309. {
  1310. // delegate the call to get_ptr<>()
  1311. auto* ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  1312. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  1313. {
  1314. return *ptr;
  1315. }
  1316. JSON_THROW(type_error::create(303, detail::concat("incompatible ReferenceType for get_ref, actual type is ", obj.type_name()), &obj));
  1317. }
  1318. public:
  1319. /// @name value access
  1320. /// Direct access to the stored value of a JSON value.
  1321. /// @{
  1322. /// @brief get a pointer value (implicit)
  1323. /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
  1324. template<typename PointerType, typename std::enable_if<
  1325. std::is_pointer<PointerType>::value, int>::type = 0>
  1326. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  1327. {
  1328. // delegate the call to get_impl_ptr<>()
  1329. return get_impl_ptr(static_cast<PointerType>(nullptr));
  1330. }
  1331. /// @brief get a pointer value (implicit)
  1332. /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/
  1333. template < typename PointerType, typename std::enable_if <
  1334. std::is_pointer<PointerType>::value&&
  1335. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  1336. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  1337. {
  1338. // delegate the call to get_impl_ptr<>() const
  1339. return get_impl_ptr(static_cast<PointerType>(nullptr));
  1340. }
  1341. private:
  1342. /*!
  1343. @brief get a value (explicit)
  1344. Explicit type conversion between the JSON value and a compatible value
  1345. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  1346. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  1347. The value is converted by calling the @ref json_serializer<ValueType>
  1348. `from_json()` method.
  1349. The function is equivalent to executing
  1350. @code {.cpp}
  1351. ValueType ret;
  1352. JSONSerializer<ValueType>::from_json(*this, ret);
  1353. return ret;
  1354. @endcode
  1355. This overloads is chosen if:
  1356. - @a ValueType is not @ref basic_json,
  1357. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  1358. `void from_json(const basic_json&, ValueType&)`, and
  1359. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  1360. the form `ValueType from_json(const basic_json&)`
  1361. @tparam ValueType the returned value type
  1362. @return copy of the JSON value, converted to @a ValueType
  1363. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  1364. @liveexample{The example below shows several conversions from JSON values
  1365. to other types. There a few things to note: (1) Floating-point numbers can
  1366. be converted to integers\, (2) A JSON array can be converted to a standard
  1367. `std::vector<short>`\, (3) A JSON object can be converted to C++
  1368. associative containers such as `std::unordered_map<std::string\,
  1369. json>`.,get__ValueType_const}
  1370. @since version 2.1.0
  1371. */
  1372. template < typename ValueType,
  1373. detail::enable_if_t <
  1374. detail::is_default_constructible<ValueType>::value&&
  1375. detail::has_from_json<basic_json_t, ValueType>::value,
  1376. int > = 0 >
  1377. ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept(
  1378. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  1379. {
  1380. auto ret = ValueType();
  1381. JSONSerializer<ValueType>::from_json(*this, ret);
  1382. return ret;
  1383. }
  1384. /*!
  1385. @brief get a value (explicit); special case
  1386. Explicit type conversion between the JSON value and a compatible value
  1387. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  1388. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  1389. The value is converted by calling the @ref json_serializer<ValueType>
  1390. `from_json()` method.
  1391. The function is equivalent to executing
  1392. @code {.cpp}
  1393. return JSONSerializer<ValueType>::from_json(*this);
  1394. @endcode
  1395. This overloads is chosen if:
  1396. - @a ValueType is not @ref basic_json and
  1397. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  1398. `ValueType from_json(const basic_json&)`
  1399. @note If @ref json_serializer<ValueType> has both overloads of
  1400. `from_json()`, this one is chosen.
  1401. @tparam ValueType the returned value type
  1402. @return copy of the JSON value, converted to @a ValueType
  1403. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  1404. @since version 2.1.0
  1405. */
  1406. template < typename ValueType,
  1407. detail::enable_if_t <
  1408. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  1409. int > = 0 >
  1410. ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept(
  1411. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  1412. {
  1413. return JSONSerializer<ValueType>::from_json(*this);
  1414. }
  1415. /*!
  1416. @brief get special-case overload
  1417. This overloads converts the current @ref basic_json in a different
  1418. @ref basic_json type
  1419. @tparam BasicJsonType == @ref basic_json
  1420. @return a copy of *this, converted into @a BasicJsonType
  1421. @complexity Depending on the implementation of the called `from_json()`
  1422. method.
  1423. @since version 3.2.0
  1424. */
  1425. template < typename BasicJsonType,
  1426. detail::enable_if_t <
  1427. detail::is_basic_json<BasicJsonType>::value,
  1428. int > = 0 >
  1429. BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const
  1430. {
  1431. return *this;
  1432. }
  1433. /*!
  1434. @brief get special-case overload
  1435. This overloads avoids a lot of template boilerplate, it can be seen as the
  1436. identity method
  1437. @tparam BasicJsonType == @ref basic_json
  1438. @return a copy of *this
  1439. @complexity Constant.
  1440. @since version 2.1.0
  1441. */
  1442. template<typename BasicJsonType,
  1443. detail::enable_if_t<
  1444. std::is_same<BasicJsonType, basic_json_t>::value,
  1445. int> = 0>
  1446. basic_json get_impl(detail::priority_tag<3> /*unused*/) const
  1447. {
  1448. return *this;
  1449. }
  1450. /*!
  1451. @brief get a pointer value (explicit)
  1452. @copydoc get()
  1453. */
  1454. template<typename PointerType,
  1455. detail::enable_if_t<
  1456. std::is_pointer<PointerType>::value,
  1457. int> = 0>
  1458. constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept
  1459. -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  1460. {
  1461. // delegate the call to get_ptr
  1462. return get_ptr<PointerType>();
  1463. }
  1464. public:
  1465. /*!
  1466. @brief get a (pointer) value (explicit)
  1467. Performs explicit type conversion between the JSON value and a compatible value if required.
  1468. - If the requested type is a pointer to the internally stored JSON value that pointer is returned.
  1469. No copies are made.
  1470. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible
  1471. from the current @ref basic_json.
  1472. - Otherwise the value is converted by calling the @ref json_serializer<ValueType> `from_json()`
  1473. method.
  1474. @tparam ValueTypeCV the provided value type
  1475. @tparam ValueType the returned value type
  1476. @return copy of the JSON value, converted to @tparam ValueType if necessary
  1477. @throw what @ref json_serializer<ValueType> `from_json()` method throws if conversion is required
  1478. @since version 2.1.0
  1479. */
  1480. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>>
  1481. #if defined(JSON_HAS_CPP_14)
  1482. constexpr
  1483. #endif
  1484. auto get() const noexcept(
  1485. noexcept(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {})))
  1486. -> decltype(std::declval<const basic_json_t&>().template get_impl<ValueType>(detail::priority_tag<4> {}))
  1487. {
  1488. // we cannot static_assert on ValueTypeCV being non-const, because
  1489. // there is support for get<const basic_json_t>(), which is why we
  1490. // still need the uncvref
  1491. static_assert(!std::is_reference<ValueTypeCV>::value,
  1492. "get() cannot be used with reference types, you might want to use get_ref()");
  1493. return get_impl<ValueType>(detail::priority_tag<4> {});
  1494. }
  1495. /*!
  1496. @brief get a pointer value (explicit)
  1497. Explicit pointer access to the internally stored JSON value. No copies are
  1498. made.
  1499. @warning The pointer becomes invalid if the underlying JSON object
  1500. changes.
  1501. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  1502. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  1503. @ref number_unsigned_t, or @ref number_float_t.
  1504. @return pointer to the internally stored JSON value if the requested
  1505. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  1506. @complexity Constant.
  1507. @liveexample{The example below shows how pointers to internal values of a
  1508. JSON value can be requested. Note that no type conversions are made and a
  1509. `nullptr` is returned if the value and the requested pointer type does not
  1510. match.,get__PointerType}
  1511. @sa see @ref get_ptr() for explicit pointer-member access
  1512. @since version 1.0.0
  1513. */
  1514. template<typename PointerType, typename std::enable_if<
  1515. std::is_pointer<PointerType>::value, int>::type = 0>
  1516. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  1517. {
  1518. // delegate the call to get_ptr
  1519. return get_ptr<PointerType>();
  1520. }
  1521. /// @brief get a value (explicit)
  1522. /// @sa https://json.nlohmann.me/api/basic_json/get_to/
  1523. template < typename ValueType,
  1524. detail::enable_if_t <
  1525. !detail::is_basic_json<ValueType>::value&&
  1526. detail::has_from_json<basic_json_t, ValueType>::value,
  1527. int > = 0 >
  1528. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  1529. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  1530. {
  1531. JSONSerializer<ValueType>::from_json(*this, v);
  1532. return v;
  1533. }
  1534. // specialization to allow calling get_to with a basic_json value
  1535. // see https://github.com/nlohmann/json/issues/2175
  1536. template<typename ValueType,
  1537. detail::enable_if_t <
  1538. detail::is_basic_json<ValueType>::value,
  1539. int> = 0>
  1540. ValueType & get_to(ValueType& v) const
  1541. {
  1542. v = *this;
  1543. return v;
  1544. }
  1545. template <
  1546. typename T, std::size_t N,
  1547. typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  1548. detail::enable_if_t <
  1549. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  1550. Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
  1551. noexcept(noexcept(JSONSerializer<Array>::from_json(
  1552. std::declval<const basic_json_t&>(), v)))
  1553. {
  1554. JSONSerializer<Array>::from_json(*this, v);
  1555. return v;
  1556. }
  1557. /// @brief get a reference value (implicit)
  1558. /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
  1559. template<typename ReferenceType, typename std::enable_if<
  1560. std::is_reference<ReferenceType>::value, int>::type = 0>
  1561. ReferenceType get_ref()
  1562. {
  1563. // delegate call to get_ref_impl
  1564. return get_ref_impl<ReferenceType>(*this);
  1565. }
  1566. /// @brief get a reference value (implicit)
  1567. /// @sa https://json.nlohmann.me/api/basic_json/get_ref/
  1568. template < typename ReferenceType, typename std::enable_if <
  1569. std::is_reference<ReferenceType>::value&&
  1570. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  1571. ReferenceType get_ref() const
  1572. {
  1573. // delegate call to get_ref_impl
  1574. return get_ref_impl<ReferenceType>(*this);
  1575. }
  1576. /*!
  1577. @brief get a value (implicit)
  1578. Implicit type conversion between the JSON value and a compatible value.
  1579. The call is realized by calling @ref get() const.
  1580. @tparam ValueType non-pointer type compatible to the JSON value, for
  1581. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  1582. `std::vector` types for JSON arrays. The character type of @ref string_t
  1583. as well as an initializer list of this type is excluded to avoid
  1584. ambiguities as these types implicitly convert to `std::string`.
  1585. @return copy of the JSON value, converted to type @a ValueType
  1586. @throw type_error.302 in case passed type @a ValueType is incompatible
  1587. to the JSON value type (e.g., the JSON value is of type boolean, but a
  1588. string is requested); see example below
  1589. @complexity Linear in the size of the JSON value.
  1590. @liveexample{The example below shows several conversions from JSON values
  1591. to other types. There a few things to note: (1) Floating-point numbers can
  1592. be converted to integers\, (2) A JSON array can be converted to a standard
  1593. `std::vector<short>`\, (3) A JSON object can be converted to C++
  1594. associative containers such as `std::unordered_map<std::string\,
  1595. json>`.,operator__ValueType}
  1596. @since version 1.0.0
  1597. */
  1598. template < typename ValueType, typename std::enable_if <
  1599. detail::conjunction <
  1600. detail::negation<std::is_pointer<ValueType>>,
  1601. detail::negation<std::is_same<ValueType, std::nullptr_t>>,
  1602. detail::negation<std::is_same<ValueType, detail::json_ref<basic_json>>>,
  1603. detail::negation<std::is_same<ValueType, typename string_t::value_type>>,
  1604. detail::negation<detail::is_basic_json<ValueType>>,
  1605. detail::negation<std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>>,
  1606. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  1607. detail::negation<std::is_same<ValueType, std::string_view>>,
  1608. #endif
  1609. #if defined(JSON_HAS_CPP_17)
  1610. detail::negation<std::is_same<ValueType, std::any>>,
  1611. #endif
  1612. detail::is_detected_lazy<detail::get_template_function, const basic_json_t&, ValueType>
  1613. >::value, int >::type = 0 >
  1614. JSON_EXPLICIT operator ValueType() const
  1615. {
  1616. // delegate the call to get<>() const
  1617. return get<ValueType>();
  1618. }
  1619. /// @brief get a binary value
  1620. /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
  1621. binary_t& get_binary()
  1622. {
  1623. if (!is_binary())
  1624. {
  1625. JSON_THROW(type_error::create(302, detail::concat("type must be binary, but is ", type_name()), this));
  1626. }
  1627. return *get_ptr<binary_t*>();
  1628. }
  1629. /// @brief get a binary value
  1630. /// @sa https://json.nlohmann.me/api/basic_json/get_binary/
  1631. const binary_t& get_binary() const
  1632. {
  1633. if (!is_binary())
  1634. {
  1635. JSON_THROW(type_error::create(302, detail::concat("type must be binary, but is ", type_name()), this));
  1636. }
  1637. return *get_ptr<const binary_t*>();
  1638. }
  1639. /// @}
  1640. ////////////////////
  1641. // element access //
  1642. ////////////////////
  1643. /// @name element access
  1644. /// Access to the JSON value.
  1645. /// @{
  1646. /// @brief access specified array element with bounds checking
  1647. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1648. reference at(size_type idx)
  1649. {
  1650. // at only works for arrays
  1651. if (JSON_HEDLEY_LIKELY(is_array()))
  1652. {
  1653. JSON_TRY
  1654. {
  1655. return set_parent(m_data.m_value.array->at(idx));
  1656. }
  1657. JSON_CATCH (std::out_of_range&)
  1658. {
  1659. // create better exception explanation
  1660. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
  1661. }
  1662. }
  1663. else
  1664. {
  1665. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1666. }
  1667. }
  1668. /// @brief access specified array element with bounds checking
  1669. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1670. const_reference at(size_type idx) const
  1671. {
  1672. // at only works for arrays
  1673. if (JSON_HEDLEY_LIKELY(is_array()))
  1674. {
  1675. JSON_TRY
  1676. {
  1677. return m_data.m_value.array->at(idx);
  1678. }
  1679. JSON_CATCH (std::out_of_range&)
  1680. {
  1681. // create better exception explanation
  1682. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
  1683. }
  1684. }
  1685. else
  1686. {
  1687. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1688. }
  1689. }
  1690. /// @brief access specified object element with bounds checking
  1691. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1692. reference at(const typename object_t::key_type& key)
  1693. {
  1694. // at only works for objects
  1695. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1696. {
  1697. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1698. }
  1699. auto it = m_data.m_value.object->find(key);
  1700. if (it == m_data.m_value.object->end())
  1701. {
  1702. JSON_THROW(out_of_range::create(403, detail::concat("key '", key, "' not found"), this));
  1703. }
  1704. return set_parent(it->second);
  1705. }
  1706. /// @brief access specified object element with bounds checking
  1707. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1708. template<class KeyType, detail::enable_if_t<
  1709. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  1710. reference at(KeyType && key)
  1711. {
  1712. // at only works for objects
  1713. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1714. {
  1715. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1716. }
  1717. auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
  1718. if (it == m_data.m_value.object->end())
  1719. {
  1720. JSON_THROW(out_of_range::create(403, detail::concat("key '", string_t(std::forward<KeyType>(key)), "' not found"), this));
  1721. }
  1722. return set_parent(it->second);
  1723. }
  1724. /// @brief access specified object element with bounds checking
  1725. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1726. const_reference at(const typename object_t::key_type& key) const
  1727. {
  1728. // at only works for objects
  1729. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1730. {
  1731. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1732. }
  1733. auto it = m_data.m_value.object->find(key);
  1734. if (it == m_data.m_value.object->end())
  1735. {
  1736. JSON_THROW(out_of_range::create(403, detail::concat("key '", key, "' not found"), this));
  1737. }
  1738. return it->second;
  1739. }
  1740. /// @brief access specified object element with bounds checking
  1741. /// @sa https://json.nlohmann.me/api/basic_json/at/
  1742. template<class KeyType, detail::enable_if_t<
  1743. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  1744. const_reference at(KeyType && key) const
  1745. {
  1746. // at only works for objects
  1747. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  1748. {
  1749. JSON_THROW(type_error::create(304, detail::concat("cannot use at() with ", type_name()), this));
  1750. }
  1751. auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
  1752. if (it == m_data.m_value.object->end())
  1753. {
  1754. JSON_THROW(out_of_range::create(403, detail::concat("key '", string_t(std::forward<KeyType>(key)), "' not found"), this));
  1755. }
  1756. return it->second;
  1757. }
  1758. /// @brief access specified array element
  1759. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1760. reference operator[](size_type idx)
  1761. {
  1762. // implicitly convert null value to an empty array
  1763. if (is_null())
  1764. {
  1765. m_data.m_type = value_t::array;
  1766. m_data.m_value.array = create<array_t>();
  1767. assert_invariant();
  1768. }
  1769. // operator[] only works for arrays
  1770. if (JSON_HEDLEY_LIKELY(is_array()))
  1771. {
  1772. // fill up array with null values if given idx is outside range
  1773. if (idx >= m_data.m_value.array->size())
  1774. {
  1775. #if JSON_DIAGNOSTICS
  1776. // remember array size & capacity before resizing
  1777. const auto old_size = m_data.m_value.array->size();
  1778. const auto old_capacity = m_data.m_value.array->capacity();
  1779. #endif
  1780. m_data.m_value.array->resize(idx + 1);
  1781. #if JSON_DIAGNOSTICS
  1782. if (JSON_HEDLEY_UNLIKELY(m_data.m_value.array->capacity() != old_capacity))
  1783. {
  1784. // capacity has changed: update all parents
  1785. set_parents();
  1786. }
  1787. else
  1788. {
  1789. // set parent for values added above
  1790. set_parents(begin() + static_cast<typename iterator::difference_type>(old_size), static_cast<typename iterator::difference_type>(idx + 1 - old_size));
  1791. }
  1792. #endif
  1793. assert_invariant();
  1794. }
  1795. return m_data.m_value.array->operator[](idx);
  1796. }
  1797. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a numeric argument with ", type_name()), this));
  1798. }
  1799. /// @brief access specified array element
  1800. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1801. const_reference operator[](size_type idx) const
  1802. {
  1803. // const operator[] only works for arrays
  1804. if (JSON_HEDLEY_LIKELY(is_array()))
  1805. {
  1806. return m_data.m_value.array->operator[](idx);
  1807. }
  1808. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a numeric argument with ", type_name()), this));
  1809. }
  1810. /// @brief access specified object element
  1811. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1812. reference operator[](typename object_t::key_type key)
  1813. {
  1814. // implicitly convert null value to an empty object
  1815. if (is_null())
  1816. {
  1817. m_data.m_type = value_t::object;
  1818. m_data.m_value.object = create<object_t>();
  1819. assert_invariant();
  1820. }
  1821. // operator[] only works for objects
  1822. if (JSON_HEDLEY_LIKELY(is_object()))
  1823. {
  1824. auto result = m_data.m_value.object->emplace(std::move(key), nullptr);
  1825. return set_parent(result.first->second);
  1826. }
  1827. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1828. }
  1829. /// @brief access specified object element
  1830. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1831. const_reference operator[](const typename object_t::key_type& key) const
  1832. {
  1833. // const operator[] only works for objects
  1834. if (JSON_HEDLEY_LIKELY(is_object()))
  1835. {
  1836. auto it = m_data.m_value.object->find(key);
  1837. JSON_ASSERT(it != m_data.m_value.object->end());
  1838. return it->second;
  1839. }
  1840. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1841. }
  1842. // these two functions resolve a (const) char * ambiguity affecting Clang and MSVC
  1843. // (they seemingly cannot be constrained to resolve the ambiguity)
  1844. template<typename T>
  1845. reference operator[](T* key)
  1846. {
  1847. return operator[](typename object_t::key_type(key));
  1848. }
  1849. template<typename T>
  1850. const_reference operator[](T* key) const
  1851. {
  1852. return operator[](typename object_t::key_type(key));
  1853. }
  1854. /// @brief access specified object element
  1855. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1856. template<class KeyType, detail::enable_if_t<
  1857. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int > = 0 >
  1858. reference operator[](KeyType && key)
  1859. {
  1860. // implicitly convert null value to an empty object
  1861. if (is_null())
  1862. {
  1863. m_data.m_type = value_t::object;
  1864. m_data.m_value.object = create<object_t>();
  1865. assert_invariant();
  1866. }
  1867. // operator[] only works for objects
  1868. if (JSON_HEDLEY_LIKELY(is_object()))
  1869. {
  1870. auto result = m_data.m_value.object->emplace(std::forward<KeyType>(key), nullptr);
  1871. return set_parent(result.first->second);
  1872. }
  1873. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1874. }
  1875. /// @brief access specified object element
  1876. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  1877. template<class KeyType, detail::enable_if_t<
  1878. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int > = 0 >
  1879. const_reference operator[](KeyType && key) const
  1880. {
  1881. // const operator[] only works for objects
  1882. if (JSON_HEDLEY_LIKELY(is_object()))
  1883. {
  1884. auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
  1885. JSON_ASSERT(it != m_data.m_value.object->end());
  1886. return it->second;
  1887. }
  1888. JSON_THROW(type_error::create(305, detail::concat("cannot use operator[] with a string argument with ", type_name()), this));
  1889. }
  1890. private:
  1891. template<typename KeyType>
  1892. using is_comparable_with_object_key = detail::is_comparable <
  1893. object_comparator_t, const typename object_t::key_type&, KeyType >;
  1894. template<typename ValueType>
  1895. using value_return_type = std::conditional <
  1896. detail::is_c_string_uncvref<ValueType>::value,
  1897. string_t, typename std::decay<ValueType>::type >;
  1898. public:
  1899. /// @brief access specified object element with default value
  1900. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1901. template < class ValueType, detail::enable_if_t <
  1902. !detail::is_transparent<object_comparator_t>::value
  1903. && detail::is_getable<basic_json_t, ValueType>::value
  1904. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1905. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  1906. {
  1907. // value only works for objects
  1908. if (JSON_HEDLEY_LIKELY(is_object()))
  1909. {
  1910. // if key is found, return value and given default value otherwise
  1911. const auto it = find(key);
  1912. if (it != end())
  1913. {
  1914. return it->template get<ValueType>();
  1915. }
  1916. return default_value;
  1917. }
  1918. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1919. }
  1920. /// @brief access specified object element with default value
  1921. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1922. template < class ValueType, class ReturnType = typename value_return_type<ValueType>::type,
  1923. detail::enable_if_t <
  1924. !detail::is_transparent<object_comparator_t>::value
  1925. && detail::is_getable<basic_json_t, ReturnType>::value
  1926. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1927. ReturnType value(const typename object_t::key_type& key, ValueType && default_value) const
  1928. {
  1929. // value only works for objects
  1930. if (JSON_HEDLEY_LIKELY(is_object()))
  1931. {
  1932. // if key is found, return value and given default value otherwise
  1933. const auto it = find(key);
  1934. if (it != end())
  1935. {
  1936. return it->template get<ReturnType>();
  1937. }
  1938. return std::forward<ValueType>(default_value);
  1939. }
  1940. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1941. }
  1942. /// @brief access specified object element with default value
  1943. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1944. template < class ValueType, class KeyType, detail::enable_if_t <
  1945. detail::is_transparent<object_comparator_t>::value
  1946. && !detail::is_json_pointer<KeyType>::value
  1947. && is_comparable_with_object_key<KeyType>::value
  1948. && detail::is_getable<basic_json_t, ValueType>::value
  1949. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1950. ValueType value(KeyType && key, const ValueType& default_value) const
  1951. {
  1952. // value only works for objects
  1953. if (JSON_HEDLEY_LIKELY(is_object()))
  1954. {
  1955. // if key is found, return value and given default value otherwise
  1956. const auto it = find(std::forward<KeyType>(key));
  1957. if (it != end())
  1958. {
  1959. return it->template get<ValueType>();
  1960. }
  1961. return default_value;
  1962. }
  1963. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1964. }
  1965. /// @brief access specified object element via JSON Pointer with default value
  1966. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1967. template < class ValueType, class KeyType, class ReturnType = typename value_return_type<ValueType>::type,
  1968. detail::enable_if_t <
  1969. detail::is_transparent<object_comparator_t>::value
  1970. && !detail::is_json_pointer<KeyType>::value
  1971. && is_comparable_with_object_key<KeyType>::value
  1972. && detail::is_getable<basic_json_t, ReturnType>::value
  1973. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1974. ReturnType value(KeyType && key, ValueType && default_value) const
  1975. {
  1976. // value only works for objects
  1977. if (JSON_HEDLEY_LIKELY(is_object()))
  1978. {
  1979. // if key is found, return value and given default value otherwise
  1980. const auto it = find(std::forward<KeyType>(key));
  1981. if (it != end())
  1982. {
  1983. return it->template get<ReturnType>();
  1984. }
  1985. return std::forward<ValueType>(default_value);
  1986. }
  1987. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  1988. }
  1989. /// @brief access specified object element via JSON Pointer with default value
  1990. /// @sa https://json.nlohmann.me/api/basic_json/value/
  1991. template < class ValueType, detail::enable_if_t <
  1992. detail::is_getable<basic_json_t, ValueType>::value
  1993. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  1994. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  1995. {
  1996. // value only works for objects
  1997. if (JSON_HEDLEY_LIKELY(is_object()))
  1998. {
  1999. // if pointer resolves a value, return it or use default value
  2000. JSON_TRY
  2001. {
  2002. return ptr.get_checked(this).template get<ValueType>();
  2003. }
  2004. JSON_INTERNAL_CATCH (out_of_range&)
  2005. {
  2006. return default_value;
  2007. }
  2008. }
  2009. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  2010. }
  2011. /// @brief access specified object element via JSON Pointer with default value
  2012. /// @sa https://json.nlohmann.me/api/basic_json/value/
  2013. template < class ValueType, class ReturnType = typename value_return_type<ValueType>::type,
  2014. detail::enable_if_t <
  2015. detail::is_getable<basic_json_t, ReturnType>::value
  2016. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  2017. ReturnType value(const json_pointer& ptr, ValueType && default_value) const
  2018. {
  2019. // value only works for objects
  2020. if (JSON_HEDLEY_LIKELY(is_object()))
  2021. {
  2022. // if pointer resolves a value, return it or use default value
  2023. JSON_TRY
  2024. {
  2025. return ptr.get_checked(this).template get<ReturnType>();
  2026. }
  2027. JSON_INTERNAL_CATCH (out_of_range&)
  2028. {
  2029. return std::forward<ValueType>(default_value);
  2030. }
  2031. }
  2032. JSON_THROW(type_error::create(306, detail::concat("cannot use value() with ", type_name()), this));
  2033. }
  2034. template < class ValueType, class BasicJsonType, detail::enable_if_t <
  2035. detail::is_basic_json<BasicJsonType>::value
  2036. && detail::is_getable<basic_json_t, ValueType>::value
  2037. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  2038. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  2039. ValueType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, const ValueType& default_value) const
  2040. {
  2041. return value(ptr.convert(), default_value);
  2042. }
  2043. template < class ValueType, class BasicJsonType, class ReturnType = typename value_return_type<ValueType>::type,
  2044. detail::enable_if_t <
  2045. detail::is_basic_json<BasicJsonType>::value
  2046. && detail::is_getable<basic_json_t, ReturnType>::value
  2047. && !std::is_same<value_t, detail::uncvref_t<ValueType>>::value, int > = 0 >
  2048. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  2049. ReturnType value(const ::nlohmann::json_pointer<BasicJsonType>& ptr, ValueType && default_value) const
  2050. {
  2051. return value(ptr.convert(), std::forward<ValueType>(default_value));
  2052. }
  2053. /// @brief access the first element
  2054. /// @sa https://json.nlohmann.me/api/basic_json/front/
  2055. reference front()
  2056. {
  2057. return *begin();
  2058. }
  2059. /// @brief access the first element
  2060. /// @sa https://json.nlohmann.me/api/basic_json/front/
  2061. const_reference front() const
  2062. {
  2063. return *cbegin();
  2064. }
  2065. /// @brief access the last element
  2066. /// @sa https://json.nlohmann.me/api/basic_json/back/
  2067. reference back()
  2068. {
  2069. auto tmp = end();
  2070. --tmp;
  2071. return *tmp;
  2072. }
  2073. /// @brief access the last element
  2074. /// @sa https://json.nlohmann.me/api/basic_json/back/
  2075. const_reference back() const
  2076. {
  2077. auto tmp = cend();
  2078. --tmp;
  2079. return *tmp;
  2080. }
  2081. /// @brief remove element given an iterator
  2082. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2083. template < class IteratorType, detail::enable_if_t <
  2084. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  2085. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int > = 0 >
  2086. IteratorType erase(IteratorType pos)
  2087. {
  2088. // make sure iterator fits the current value
  2089. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  2090. {
  2091. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2092. }
  2093. IteratorType result = end();
  2094. switch (m_data.m_type)
  2095. {
  2096. case value_t::boolean:
  2097. case value_t::number_float:
  2098. case value_t::number_integer:
  2099. case value_t::number_unsigned:
  2100. case value_t::string:
  2101. case value_t::binary:
  2102. {
  2103. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  2104. {
  2105. JSON_THROW(invalid_iterator::create(205, "iterator out of range", this));
  2106. }
  2107. if (is_string())
  2108. {
  2109. AllocatorType<string_t> alloc;
  2110. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.string);
  2111. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.string, 1);
  2112. m_data.m_value.string = nullptr;
  2113. }
  2114. else if (is_binary())
  2115. {
  2116. AllocatorType<binary_t> alloc;
  2117. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.binary);
  2118. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.binary, 1);
  2119. m_data.m_value.binary = nullptr;
  2120. }
  2121. m_data.m_type = value_t::null;
  2122. assert_invariant();
  2123. break;
  2124. }
  2125. case value_t::object:
  2126. {
  2127. result.m_it.object_iterator = m_data.m_value.object->erase(pos.m_it.object_iterator);
  2128. break;
  2129. }
  2130. case value_t::array:
  2131. {
  2132. result.m_it.array_iterator = m_data.m_value.array->erase(pos.m_it.array_iterator);
  2133. break;
  2134. }
  2135. case value_t::null:
  2136. case value_t::discarded:
  2137. default:
  2138. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2139. }
  2140. return result;
  2141. }
  2142. /// @brief remove elements given an iterator range
  2143. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2144. template < class IteratorType, detail::enable_if_t <
  2145. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  2146. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int > = 0 >
  2147. IteratorType erase(IteratorType first, IteratorType last)
  2148. {
  2149. // make sure iterator fits the current value
  2150. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  2151. {
  2152. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", this));
  2153. }
  2154. IteratorType result = end();
  2155. switch (m_data.m_type)
  2156. {
  2157. case value_t::boolean:
  2158. case value_t::number_float:
  2159. case value_t::number_integer:
  2160. case value_t::number_unsigned:
  2161. case value_t::string:
  2162. case value_t::binary:
  2163. {
  2164. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  2165. || !last.m_it.primitive_iterator.is_end()))
  2166. {
  2167. JSON_THROW(invalid_iterator::create(204, "iterators out of range", this));
  2168. }
  2169. if (is_string())
  2170. {
  2171. AllocatorType<string_t> alloc;
  2172. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.string);
  2173. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.string, 1);
  2174. m_data.m_value.string = nullptr;
  2175. }
  2176. else if (is_binary())
  2177. {
  2178. AllocatorType<binary_t> alloc;
  2179. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_data.m_value.binary);
  2180. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_data.m_value.binary, 1);
  2181. m_data.m_value.binary = nullptr;
  2182. }
  2183. m_data.m_type = value_t::null;
  2184. assert_invariant();
  2185. break;
  2186. }
  2187. case value_t::object:
  2188. {
  2189. result.m_it.object_iterator = m_data.m_value.object->erase(first.m_it.object_iterator,
  2190. last.m_it.object_iterator);
  2191. break;
  2192. }
  2193. case value_t::array:
  2194. {
  2195. result.m_it.array_iterator = m_data.m_value.array->erase(first.m_it.array_iterator,
  2196. last.m_it.array_iterator);
  2197. break;
  2198. }
  2199. case value_t::null:
  2200. case value_t::discarded:
  2201. default:
  2202. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2203. }
  2204. return result;
  2205. }
  2206. private:
  2207. template < typename KeyType, detail::enable_if_t <
  2208. detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int > = 0 >
  2209. size_type erase_internal(KeyType && key)
  2210. {
  2211. // this erase only works for objects
  2212. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2213. {
  2214. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2215. }
  2216. return m_data.m_value.object->erase(std::forward<KeyType>(key));
  2217. }
  2218. template < typename KeyType, detail::enable_if_t <
  2219. !detail::has_erase_with_key_type<basic_json_t, KeyType>::value, int > = 0 >
  2220. size_type erase_internal(KeyType && key)
  2221. {
  2222. // this erase only works for objects
  2223. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2224. {
  2225. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2226. }
  2227. const auto it = m_data.m_value.object->find(std::forward<KeyType>(key));
  2228. if (it != m_data.m_value.object->end())
  2229. {
  2230. m_data.m_value.object->erase(it);
  2231. return 1;
  2232. }
  2233. return 0;
  2234. }
  2235. public:
  2236. /// @brief remove element from a JSON object given a key
  2237. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2238. size_type erase(const typename object_t::key_type& key)
  2239. {
  2240. // the indirection via erase_internal() is added to avoid making this
  2241. // function a template and thus de-rank it during overload resolution
  2242. return erase_internal(key);
  2243. }
  2244. /// @brief remove element from a JSON object given a key
  2245. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2246. template<class KeyType, detail::enable_if_t<
  2247. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2248. size_type erase(KeyType && key)
  2249. {
  2250. return erase_internal(std::forward<KeyType>(key));
  2251. }
  2252. /// @brief remove element from a JSON array given an index
  2253. /// @sa https://json.nlohmann.me/api/basic_json/erase/
  2254. void erase(const size_type idx)
  2255. {
  2256. // this erase only works for arrays
  2257. if (JSON_HEDLEY_LIKELY(is_array()))
  2258. {
  2259. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  2260. {
  2261. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this));
  2262. }
  2263. m_data.m_value.array->erase(m_data.m_value.array->begin() + static_cast<difference_type>(idx));
  2264. }
  2265. else
  2266. {
  2267. JSON_THROW(type_error::create(307, detail::concat("cannot use erase() with ", type_name()), this));
  2268. }
  2269. }
  2270. /// @}
  2271. ////////////
  2272. // lookup //
  2273. ////////////
  2274. /// @name lookup
  2275. /// @{
  2276. /// @brief find an element in a JSON object
  2277. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2278. iterator find(const typename object_t::key_type& key)
  2279. {
  2280. auto result = end();
  2281. if (is_object())
  2282. {
  2283. result.m_it.object_iterator = m_data.m_value.object->find(key);
  2284. }
  2285. return result;
  2286. }
  2287. /// @brief find an element in a JSON object
  2288. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2289. const_iterator find(const typename object_t::key_type& key) const
  2290. {
  2291. auto result = cend();
  2292. if (is_object())
  2293. {
  2294. result.m_it.object_iterator = m_data.m_value.object->find(key);
  2295. }
  2296. return result;
  2297. }
  2298. /// @brief find an element in a JSON object
  2299. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2300. template<class KeyType, detail::enable_if_t<
  2301. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2302. iterator find(KeyType && key)
  2303. {
  2304. auto result = end();
  2305. if (is_object())
  2306. {
  2307. result.m_it.object_iterator = m_data.m_value.object->find(std::forward<KeyType>(key));
  2308. }
  2309. return result;
  2310. }
  2311. /// @brief find an element in a JSON object
  2312. /// @sa https://json.nlohmann.me/api/basic_json/find/
  2313. template<class KeyType, detail::enable_if_t<
  2314. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2315. const_iterator find(KeyType && key) const
  2316. {
  2317. auto result = cend();
  2318. if (is_object())
  2319. {
  2320. result.m_it.object_iterator = m_data.m_value.object->find(std::forward<KeyType>(key));
  2321. }
  2322. return result;
  2323. }
  2324. /// @brief returns the number of occurrences of a key in a JSON object
  2325. /// @sa https://json.nlohmann.me/api/basic_json/count/
  2326. size_type count(const typename object_t::key_type& key) const
  2327. {
  2328. // return 0 for all nonobject types
  2329. return is_object() ? m_data.m_value.object->count(key) : 0;
  2330. }
  2331. /// @brief returns the number of occurrences of a key in a JSON object
  2332. /// @sa https://json.nlohmann.me/api/basic_json/count/
  2333. template<class KeyType, detail::enable_if_t<
  2334. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2335. size_type count(KeyType && key) const
  2336. {
  2337. // return 0 for all nonobject types
  2338. return is_object() ? m_data.m_value.object->count(std::forward<KeyType>(key)) : 0;
  2339. }
  2340. /// @brief check the existence of an element in a JSON object
  2341. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  2342. bool contains(const typename object_t::key_type& key) const
  2343. {
  2344. return is_object() && m_data.m_value.object->find(key) != m_data.m_value.object->end();
  2345. }
  2346. /// @brief check the existence of an element in a JSON object
  2347. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  2348. template<class KeyType, detail::enable_if_t<
  2349. detail::is_usable_as_basic_json_key_type<basic_json_t, KeyType>::value, int> = 0>
  2350. bool contains(KeyType && key) const
  2351. {
  2352. return is_object() && m_data.m_value.object->find(std::forward<KeyType>(key)) != m_data.m_value.object->end();
  2353. }
  2354. /// @brief check the existence of an element in a JSON object given a JSON pointer
  2355. /// @sa https://json.nlohmann.me/api/basic_json/contains/
  2356. bool contains(const json_pointer& ptr) const
  2357. {
  2358. return ptr.contains(this);
  2359. }
  2360. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  2361. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  2362. bool contains(const typename ::nlohmann::json_pointer<BasicJsonType>& ptr) const
  2363. {
  2364. return ptr.contains(this);
  2365. }
  2366. /// @}
  2367. ///////////////
  2368. // iterators //
  2369. ///////////////
  2370. /// @name iterators
  2371. /// @{
  2372. /// @brief returns an iterator to the first element
  2373. /// @sa https://json.nlohmann.me/api/basic_json/begin/
  2374. iterator begin() noexcept
  2375. {
  2376. iterator result(this);
  2377. result.set_begin();
  2378. return result;
  2379. }
  2380. /// @brief returns an iterator to the first element
  2381. /// @sa https://json.nlohmann.me/api/basic_json/begin/
  2382. const_iterator begin() const noexcept
  2383. {
  2384. return cbegin();
  2385. }
  2386. /// @brief returns a const iterator to the first element
  2387. /// @sa https://json.nlohmann.me/api/basic_json/cbegin/
  2388. const_iterator cbegin() const noexcept
  2389. {
  2390. const_iterator result(this);
  2391. result.set_begin();
  2392. return result;
  2393. }
  2394. /// @brief returns an iterator to one past the last element
  2395. /// @sa https://json.nlohmann.me/api/basic_json/end/
  2396. iterator end() noexcept
  2397. {
  2398. iterator result(this);
  2399. result.set_end();
  2400. return result;
  2401. }
  2402. /// @brief returns an iterator to one past the last element
  2403. /// @sa https://json.nlohmann.me/api/basic_json/end/
  2404. const_iterator end() const noexcept
  2405. {
  2406. return cend();
  2407. }
  2408. /// @brief returns an iterator to one past the last element
  2409. /// @sa https://json.nlohmann.me/api/basic_json/cend/
  2410. const_iterator cend() const noexcept
  2411. {
  2412. const_iterator result(this);
  2413. result.set_end();
  2414. return result;
  2415. }
  2416. /// @brief returns an iterator to the reverse-beginning
  2417. /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
  2418. reverse_iterator rbegin() noexcept
  2419. {
  2420. return reverse_iterator(end());
  2421. }
  2422. /// @brief returns an iterator to the reverse-beginning
  2423. /// @sa https://json.nlohmann.me/api/basic_json/rbegin/
  2424. const_reverse_iterator rbegin() const noexcept
  2425. {
  2426. return crbegin();
  2427. }
  2428. /// @brief returns an iterator to the reverse-end
  2429. /// @sa https://json.nlohmann.me/api/basic_json/rend/
  2430. reverse_iterator rend() noexcept
  2431. {
  2432. return reverse_iterator(begin());
  2433. }
  2434. /// @brief returns an iterator to the reverse-end
  2435. /// @sa https://json.nlohmann.me/api/basic_json/rend/
  2436. const_reverse_iterator rend() const noexcept
  2437. {
  2438. return crend();
  2439. }
  2440. /// @brief returns a const reverse iterator to the last element
  2441. /// @sa https://json.nlohmann.me/api/basic_json/crbegin/
  2442. const_reverse_iterator crbegin() const noexcept
  2443. {
  2444. return const_reverse_iterator(cend());
  2445. }
  2446. /// @brief returns a const reverse iterator to one before the first
  2447. /// @sa https://json.nlohmann.me/api/basic_json/crend/
  2448. const_reverse_iterator crend() const noexcept
  2449. {
  2450. return const_reverse_iterator(cbegin());
  2451. }
  2452. public:
  2453. /// @brief wrapper to access iterator member functions in range-based for
  2454. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2455. /// @deprecated This function is deprecated since 3.1.0 and will be removed in
  2456. /// version 4.0.0 of the library. Please use @ref items() instead;
  2457. /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  2458. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  2459. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  2460. {
  2461. return ref.items();
  2462. }
  2463. /// @brief wrapper to access iterator member functions in range-based for
  2464. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2465. /// @deprecated This function is deprecated since 3.1.0 and will be removed in
  2466. /// version 4.0.0 of the library. Please use @ref items() instead;
  2467. /// that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  2468. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  2469. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  2470. {
  2471. return ref.items();
  2472. }
  2473. /// @brief helper to access iterator member functions in range-based for
  2474. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2475. iteration_proxy<iterator> items() noexcept
  2476. {
  2477. return iteration_proxy<iterator>(*this);
  2478. }
  2479. /// @brief helper to access iterator member functions in range-based for
  2480. /// @sa https://json.nlohmann.me/api/basic_json/items/
  2481. iteration_proxy<const_iterator> items() const noexcept
  2482. {
  2483. return iteration_proxy<const_iterator>(*this);
  2484. }
  2485. /// @}
  2486. //////////////
  2487. // capacity //
  2488. //////////////
  2489. /// @name capacity
  2490. /// @{
  2491. /// @brief checks whether the container is empty.
  2492. /// @sa https://json.nlohmann.me/api/basic_json/empty/
  2493. bool empty() const noexcept
  2494. {
  2495. switch (m_data.m_type)
  2496. {
  2497. case value_t::null:
  2498. {
  2499. // null values are empty
  2500. return true;
  2501. }
  2502. case value_t::array:
  2503. {
  2504. // delegate call to array_t::empty()
  2505. return m_data.m_value.array->empty();
  2506. }
  2507. case value_t::object:
  2508. {
  2509. // delegate call to object_t::empty()
  2510. return m_data.m_value.object->empty();
  2511. }
  2512. case value_t::string:
  2513. case value_t::boolean:
  2514. case value_t::number_integer:
  2515. case value_t::number_unsigned:
  2516. case value_t::number_float:
  2517. case value_t::binary:
  2518. case value_t::discarded:
  2519. default:
  2520. {
  2521. // all other types are nonempty
  2522. return false;
  2523. }
  2524. }
  2525. }
  2526. /// @brief returns the number of elements
  2527. /// @sa https://json.nlohmann.me/api/basic_json/size/
  2528. size_type size() const noexcept
  2529. {
  2530. switch (m_data.m_type)
  2531. {
  2532. case value_t::null:
  2533. {
  2534. // null values are empty
  2535. return 0;
  2536. }
  2537. case value_t::array:
  2538. {
  2539. // delegate call to array_t::size()
  2540. return m_data.m_value.array->size();
  2541. }
  2542. case value_t::object:
  2543. {
  2544. // delegate call to object_t::size()
  2545. return m_data.m_value.object->size();
  2546. }
  2547. case value_t::string:
  2548. case value_t::boolean:
  2549. case value_t::number_integer:
  2550. case value_t::number_unsigned:
  2551. case value_t::number_float:
  2552. case value_t::binary:
  2553. case value_t::discarded:
  2554. default:
  2555. {
  2556. // all other types have size 1
  2557. return 1;
  2558. }
  2559. }
  2560. }
  2561. /// @brief returns the maximum possible number of elements
  2562. /// @sa https://json.nlohmann.me/api/basic_json/max_size/
  2563. size_type max_size() const noexcept
  2564. {
  2565. switch (m_data.m_type)
  2566. {
  2567. case value_t::array:
  2568. {
  2569. // delegate call to array_t::max_size()
  2570. return m_data.m_value.array->max_size();
  2571. }
  2572. case value_t::object:
  2573. {
  2574. // delegate call to object_t::max_size()
  2575. return m_data.m_value.object->max_size();
  2576. }
  2577. case value_t::null:
  2578. case value_t::string:
  2579. case value_t::boolean:
  2580. case value_t::number_integer:
  2581. case value_t::number_unsigned:
  2582. case value_t::number_float:
  2583. case value_t::binary:
  2584. case value_t::discarded:
  2585. default:
  2586. {
  2587. // all other types have max_size() == size()
  2588. return size();
  2589. }
  2590. }
  2591. }
  2592. /// @}
  2593. ///////////////
  2594. // modifiers //
  2595. ///////////////
  2596. /// @name modifiers
  2597. /// @{
  2598. /// @brief clears the contents
  2599. /// @sa https://json.nlohmann.me/api/basic_json/clear/
  2600. void clear() noexcept
  2601. {
  2602. switch (m_data.m_type)
  2603. {
  2604. case value_t::number_integer:
  2605. {
  2606. m_data.m_value.number_integer = 0;
  2607. break;
  2608. }
  2609. case value_t::number_unsigned:
  2610. {
  2611. m_data.m_value.number_unsigned = 0;
  2612. break;
  2613. }
  2614. case value_t::number_float:
  2615. {
  2616. m_data.m_value.number_float = 0.0;
  2617. break;
  2618. }
  2619. case value_t::boolean:
  2620. {
  2621. m_data.m_value.boolean = false;
  2622. break;
  2623. }
  2624. case value_t::string:
  2625. {
  2626. m_data.m_value.string->clear();
  2627. break;
  2628. }
  2629. case value_t::binary:
  2630. {
  2631. m_data.m_value.binary->clear();
  2632. break;
  2633. }
  2634. case value_t::array:
  2635. {
  2636. m_data.m_value.array->clear();
  2637. break;
  2638. }
  2639. case value_t::object:
  2640. {
  2641. m_data.m_value.object->clear();
  2642. break;
  2643. }
  2644. case value_t::null:
  2645. case value_t::discarded:
  2646. default:
  2647. break;
  2648. }
  2649. }
  2650. /// @brief add an object to an array
  2651. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2652. void push_back(basic_json&& val)
  2653. {
  2654. // push_back only works for null objects or arrays
  2655. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  2656. {
  2657. JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
  2658. }
  2659. // transform null object into an array
  2660. if (is_null())
  2661. {
  2662. m_data.m_type = value_t::array;
  2663. m_data.m_value = value_t::array;
  2664. assert_invariant();
  2665. }
  2666. // add element to array (move semantics)
  2667. const auto old_capacity = m_data.m_value.array->capacity();
  2668. m_data.m_value.array->push_back(std::move(val));
  2669. set_parent(m_data.m_value.array->back(), old_capacity);
  2670. // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor
  2671. }
  2672. /// @brief add an object to an array
  2673. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2674. reference operator+=(basic_json&& val)
  2675. {
  2676. push_back(std::move(val));
  2677. return *this;
  2678. }
  2679. /// @brief add an object to an array
  2680. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2681. void push_back(const basic_json& val)
  2682. {
  2683. // push_back only works for null objects or arrays
  2684. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  2685. {
  2686. JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
  2687. }
  2688. // transform null object into an array
  2689. if (is_null())
  2690. {
  2691. m_data.m_type = value_t::array;
  2692. m_data.m_value = value_t::array;
  2693. assert_invariant();
  2694. }
  2695. // add element to array
  2696. const auto old_capacity = m_data.m_value.array->capacity();
  2697. m_data.m_value.array->push_back(val);
  2698. set_parent(m_data.m_value.array->back(), old_capacity);
  2699. }
  2700. /// @brief add an object to an array
  2701. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2702. reference operator+=(const basic_json& val)
  2703. {
  2704. push_back(val);
  2705. return *this;
  2706. }
  2707. /// @brief add an object to an object
  2708. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2709. void push_back(const typename object_t::value_type& val)
  2710. {
  2711. // push_back only works for null objects or objects
  2712. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  2713. {
  2714. JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this));
  2715. }
  2716. // transform null object into an object
  2717. if (is_null())
  2718. {
  2719. m_data.m_type = value_t::object;
  2720. m_data.m_value = value_t::object;
  2721. assert_invariant();
  2722. }
  2723. // add element to object
  2724. auto res = m_data.m_value.object->insert(val);
  2725. set_parent(res.first->second);
  2726. }
  2727. /// @brief add an object to an object
  2728. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2729. reference operator+=(const typename object_t::value_type& val)
  2730. {
  2731. push_back(val);
  2732. return *this;
  2733. }
  2734. /// @brief add an object to an object
  2735. /// @sa https://json.nlohmann.me/api/basic_json/push_back/
  2736. void push_back(initializer_list_t init)
  2737. {
  2738. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  2739. {
  2740. basic_json&& key = init.begin()->moved_or_copied();
  2741. push_back(typename object_t::value_type(
  2742. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  2743. }
  2744. else
  2745. {
  2746. push_back(basic_json(init));
  2747. }
  2748. }
  2749. /// @brief add an object to an object
  2750. /// @sa https://json.nlohmann.me/api/basic_json/operator+=/
  2751. reference operator+=(initializer_list_t init)
  2752. {
  2753. push_back(init);
  2754. return *this;
  2755. }
  2756. /// @brief add an object to an array
  2757. /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/
  2758. template<class... Args>
  2759. reference emplace_back(Args&& ... args)
  2760. {
  2761. // emplace_back only works for null objects or arrays
  2762. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  2763. {
  2764. JSON_THROW(type_error::create(311, detail::concat("cannot use emplace_back() with ", type_name()), this));
  2765. }
  2766. // transform null object into an array
  2767. if (is_null())
  2768. {
  2769. m_data.m_type = value_t::array;
  2770. m_data.m_value = value_t::array;
  2771. assert_invariant();
  2772. }
  2773. // add element to array (perfect forwarding)
  2774. const auto old_capacity = m_data.m_value.array->capacity();
  2775. m_data.m_value.array->emplace_back(std::forward<Args>(args)...);
  2776. return set_parent(m_data.m_value.array->back(), old_capacity);
  2777. }
  2778. /// @brief add an object to an object if key does not exist
  2779. /// @sa https://json.nlohmann.me/api/basic_json/emplace/
  2780. template<class... Args>
  2781. std::pair<iterator, bool> emplace(Args&& ... args)
  2782. {
  2783. // emplace only works for null objects or arrays
  2784. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  2785. {
  2786. JSON_THROW(type_error::create(311, detail::concat("cannot use emplace() with ", type_name()), this));
  2787. }
  2788. // transform null object into an object
  2789. if (is_null())
  2790. {
  2791. m_data.m_type = value_t::object;
  2792. m_data.m_value = value_t::object;
  2793. assert_invariant();
  2794. }
  2795. // add element to array (perfect forwarding)
  2796. auto res = m_data.m_value.object->emplace(std::forward<Args>(args)...);
  2797. set_parent(res.first->second);
  2798. // create result iterator and set iterator to the result of emplace
  2799. auto it = begin();
  2800. it.m_it.object_iterator = res.first;
  2801. // return pair of iterator and boolean
  2802. return {it, res.second};
  2803. }
  2804. /// Helper for insertion of an iterator
  2805. /// @note: This uses std::distance to support GCC 4.8,
  2806. /// see https://github.com/nlohmann/json/pull/1257
  2807. template<typename... Args>
  2808. iterator insert_iterator(const_iterator pos, Args&& ... args)
  2809. {
  2810. iterator result(this);
  2811. JSON_ASSERT(m_data.m_value.array != nullptr);
  2812. auto insert_pos = std::distance(m_data.m_value.array->begin(), pos.m_it.array_iterator);
  2813. m_data.m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  2814. result.m_it.array_iterator = m_data.m_value.array->begin() + insert_pos;
  2815. // This could have been written as:
  2816. // result.m_it.array_iterator = m_data.m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  2817. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  2818. set_parents();
  2819. return result;
  2820. }
  2821. /// @brief inserts element into array
  2822. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2823. iterator insert(const_iterator pos, const basic_json& val)
  2824. {
  2825. // insert only works for arrays
  2826. if (JSON_HEDLEY_LIKELY(is_array()))
  2827. {
  2828. // check if iterator pos fits to this JSON value
  2829. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2830. {
  2831. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2832. }
  2833. // insert to array and return iterator
  2834. return insert_iterator(pos, val);
  2835. }
  2836. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2837. }
  2838. /// @brief inserts element into array
  2839. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2840. iterator insert(const_iterator pos, basic_json&& val)
  2841. {
  2842. return insert(pos, val);
  2843. }
  2844. /// @brief inserts copies of element into array
  2845. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2846. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  2847. {
  2848. // insert only works for arrays
  2849. if (JSON_HEDLEY_LIKELY(is_array()))
  2850. {
  2851. // check if iterator pos fits to this JSON value
  2852. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2853. {
  2854. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2855. }
  2856. // insert to array and return iterator
  2857. return insert_iterator(pos, cnt, val);
  2858. }
  2859. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2860. }
  2861. /// @brief inserts range of elements into array
  2862. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2863. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  2864. {
  2865. // insert only works for arrays
  2866. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  2867. {
  2868. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2869. }
  2870. // check if iterator pos fits to this JSON value
  2871. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2872. {
  2873. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2874. }
  2875. // check if range iterators belong to the same JSON object
  2876. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  2877. {
  2878. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
  2879. }
  2880. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  2881. {
  2882. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", this));
  2883. }
  2884. // insert to array and return iterator
  2885. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  2886. }
  2887. /// @brief inserts elements from initializer list into array
  2888. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2889. iterator insert(const_iterator pos, initializer_list_t ilist)
  2890. {
  2891. // insert only works for arrays
  2892. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  2893. {
  2894. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2895. }
  2896. // check if iterator pos fits to this JSON value
  2897. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  2898. {
  2899. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this));
  2900. }
  2901. // insert to array and return iterator
  2902. return insert_iterator(pos, ilist.begin(), ilist.end());
  2903. }
  2904. /// @brief inserts range of elements into object
  2905. /// @sa https://json.nlohmann.me/api/basic_json/insert/
  2906. void insert(const_iterator first, const_iterator last)
  2907. {
  2908. // insert only works for objects
  2909. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2910. {
  2911. JSON_THROW(type_error::create(309, detail::concat("cannot use insert() with ", type_name()), this));
  2912. }
  2913. // check if range iterators belong to the same JSON object
  2914. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  2915. {
  2916. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
  2917. }
  2918. // passed iterators must belong to objects
  2919. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  2920. {
  2921. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", this));
  2922. }
  2923. m_data.m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  2924. }
  2925. /// @brief updates a JSON object from another object, overwriting existing keys
  2926. /// @sa https://json.nlohmann.me/api/basic_json/update/
  2927. void update(const_reference j, bool merge_objects = false)
  2928. {
  2929. update(j.begin(), j.end(), merge_objects);
  2930. }
  2931. /// @brief updates a JSON object from another object, overwriting existing keys
  2932. /// @sa https://json.nlohmann.me/api/basic_json/update/
  2933. void update(const_iterator first, const_iterator last, bool merge_objects = false)
  2934. {
  2935. // implicitly convert null value to an empty object
  2936. if (is_null())
  2937. {
  2938. m_data.m_type = value_t::object;
  2939. m_data.m_value.object = create<object_t>();
  2940. assert_invariant();
  2941. }
  2942. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  2943. {
  2944. JSON_THROW(type_error::create(312, detail::concat("cannot use update() with ", type_name()), this));
  2945. }
  2946. // check if range iterators belong to the same JSON object
  2947. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  2948. {
  2949. JSON_THROW(invalid_iterator::create(210, "iterators do not fit", this));
  2950. }
  2951. // passed iterators must belong to objects
  2952. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  2953. {
  2954. JSON_THROW(type_error::create(312, detail::concat("cannot use update() with ", first.m_object->type_name()), first.m_object));
  2955. }
  2956. for (auto it = first; it != last; ++it)
  2957. {
  2958. if (merge_objects && it.value().is_object())
  2959. {
  2960. auto it2 = m_data.m_value.object->find(it.key());
  2961. if (it2 != m_data.m_value.object->end())
  2962. {
  2963. it2->second.update(it.value(), true);
  2964. continue;
  2965. }
  2966. }
  2967. m_data.m_value.object->operator[](it.key()) = it.value();
  2968. #if JSON_DIAGNOSTICS
  2969. m_data.m_value.object->operator[](it.key()).m_parent = this;
  2970. #endif
  2971. }
  2972. }
  2973. /// @brief exchanges the values
  2974. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  2975. void swap(reference other) noexcept (
  2976. std::is_nothrow_move_constructible<value_t>::value&&
  2977. std::is_nothrow_move_assignable<value_t>::value&&
  2978. std::is_nothrow_move_constructible<json_value>::value&&
  2979. std::is_nothrow_move_assignable<json_value>::value
  2980. )
  2981. {
  2982. std::swap(m_data.m_type, other.m_data.m_type);
  2983. std::swap(m_data.m_value, other.m_data.m_value);
  2984. set_parents();
  2985. other.set_parents();
  2986. assert_invariant();
  2987. }
  2988. /// @brief exchanges the values
  2989. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  2990. friend void swap(reference left, reference right) noexcept (
  2991. std::is_nothrow_move_constructible<value_t>::value&&
  2992. std::is_nothrow_move_assignable<value_t>::value&&
  2993. std::is_nothrow_move_constructible<json_value>::value&&
  2994. std::is_nothrow_move_assignable<json_value>::value
  2995. )
  2996. {
  2997. left.swap(right);
  2998. }
  2999. /// @brief exchanges the values
  3000. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3001. void swap(array_t& other) // NOLINT(bugprone-exception-escape)
  3002. {
  3003. // swap only works for arrays
  3004. if (JSON_HEDLEY_LIKELY(is_array()))
  3005. {
  3006. using std::swap;
  3007. swap(*(m_data.m_value.array), other);
  3008. }
  3009. else
  3010. {
  3011. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(array_t&) with ", type_name()), this));
  3012. }
  3013. }
  3014. /// @brief exchanges the values
  3015. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3016. void swap(object_t& other) // NOLINT(bugprone-exception-escape)
  3017. {
  3018. // swap only works for objects
  3019. if (JSON_HEDLEY_LIKELY(is_object()))
  3020. {
  3021. using std::swap;
  3022. swap(*(m_data.m_value.object), other);
  3023. }
  3024. else
  3025. {
  3026. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(object_t&) with ", type_name()), this));
  3027. }
  3028. }
  3029. /// @brief exchanges the values
  3030. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3031. void swap(string_t& other) // NOLINT(bugprone-exception-escape)
  3032. {
  3033. // swap only works for strings
  3034. if (JSON_HEDLEY_LIKELY(is_string()))
  3035. {
  3036. using std::swap;
  3037. swap(*(m_data.m_value.string), other);
  3038. }
  3039. else
  3040. {
  3041. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(string_t&) with ", type_name()), this));
  3042. }
  3043. }
  3044. /// @brief exchanges the values
  3045. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3046. void swap(binary_t& other) // NOLINT(bugprone-exception-escape)
  3047. {
  3048. // swap only works for strings
  3049. if (JSON_HEDLEY_LIKELY(is_binary()))
  3050. {
  3051. using std::swap;
  3052. swap(*(m_data.m_value.binary), other);
  3053. }
  3054. else
  3055. {
  3056. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(binary_t&) with ", type_name()), this));
  3057. }
  3058. }
  3059. /// @brief exchanges the values
  3060. /// @sa https://json.nlohmann.me/api/basic_json/swap/
  3061. void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape)
  3062. {
  3063. // swap only works for strings
  3064. if (JSON_HEDLEY_LIKELY(is_binary()))
  3065. {
  3066. using std::swap;
  3067. swap(*(m_data.m_value.binary), other);
  3068. }
  3069. else
  3070. {
  3071. JSON_THROW(type_error::create(310, detail::concat("cannot use swap(binary_t::container_type&) with ", type_name()), this));
  3072. }
  3073. }
  3074. /// @}
  3075. //////////////////////////////////////////
  3076. // lexicographical comparison operators //
  3077. //////////////////////////////////////////
  3078. /// @name lexicographical comparison operators
  3079. /// @{
  3080. // note parentheses around operands are necessary; see
  3081. // https://github.com/nlohmann/json/issues/1530
  3082. #define JSON_IMPLEMENT_OPERATOR(op, null_result, unordered_result, default_result) \
  3083. const auto lhs_type = lhs.type(); \
  3084. const auto rhs_type = rhs.type(); \
  3085. \
  3086. if (lhs_type == rhs_type) /* NOLINT(readability/braces) */ \
  3087. { \
  3088. switch (lhs_type) \
  3089. { \
  3090. case value_t::array: \
  3091. return (*lhs.m_data.m_value.array) op (*rhs.m_data.m_value.array); \
  3092. \
  3093. case value_t::object: \
  3094. return (*lhs.m_data.m_value.object) op (*rhs.m_data.m_value.object); \
  3095. \
  3096. case value_t::null: \
  3097. return (null_result); \
  3098. \
  3099. case value_t::string: \
  3100. return (*lhs.m_data.m_value.string) op (*rhs.m_data.m_value.string); \
  3101. \
  3102. case value_t::boolean: \
  3103. return (lhs.m_data.m_value.boolean) op (rhs.m_data.m_value.boolean); \
  3104. \
  3105. case value_t::number_integer: \
  3106. return (lhs.m_data.m_value.number_integer) op (rhs.m_data.m_value.number_integer); \
  3107. \
  3108. case value_t::number_unsigned: \
  3109. return (lhs.m_data.m_value.number_unsigned) op (rhs.m_data.m_value.number_unsigned); \
  3110. \
  3111. case value_t::number_float: \
  3112. return (lhs.m_data.m_value.number_float) op (rhs.m_data.m_value.number_float); \
  3113. \
  3114. case value_t::binary: \
  3115. return (*lhs.m_data.m_value.binary) op (*rhs.m_data.m_value.binary); \
  3116. \
  3117. case value_t::discarded: \
  3118. default: \
  3119. return (unordered_result); \
  3120. } \
  3121. } \
  3122. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) \
  3123. { \
  3124. return static_cast<number_float_t>(lhs.m_data.m_value.number_integer) op rhs.m_data.m_value.number_float; \
  3125. } \
  3126. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) \
  3127. { \
  3128. return lhs.m_data.m_value.number_float op static_cast<number_float_t>(rhs.m_data.m_value.number_integer); \
  3129. } \
  3130. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) \
  3131. { \
  3132. return static_cast<number_float_t>(lhs.m_data.m_value.number_unsigned) op rhs.m_data.m_value.number_float; \
  3133. } \
  3134. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) \
  3135. { \
  3136. return lhs.m_data.m_value.number_float op static_cast<number_float_t>(rhs.m_data.m_value.number_unsigned); \
  3137. } \
  3138. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) \
  3139. { \
  3140. return static_cast<number_integer_t>(lhs.m_data.m_value.number_unsigned) op rhs.m_data.m_value.number_integer; \
  3141. } \
  3142. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) \
  3143. { \
  3144. return lhs.m_data.m_value.number_integer op static_cast<number_integer_t>(rhs.m_data.m_value.number_unsigned); \
  3145. } \
  3146. else if(compares_unordered(lhs, rhs))\
  3147. {\
  3148. return (unordered_result);\
  3149. }\
  3150. \
  3151. return (default_result);
  3152. JSON_PRIVATE_UNLESS_TESTED:
  3153. // returns true if:
  3154. // - any operand is NaN and the other operand is of number type
  3155. // - any operand is discarded
  3156. // in legacy mode, discarded values are considered ordered if
  3157. // an operation is computed as an odd number of inverses of others
  3158. static bool compares_unordered(const_reference lhs, const_reference rhs, bool inverse = false) noexcept
  3159. {
  3160. if ((lhs.is_number_float() && std::isnan(lhs.m_data.m_value.number_float) && rhs.is_number())
  3161. || (rhs.is_number_float() && std::isnan(rhs.m_data.m_value.number_float) && lhs.is_number()))
  3162. {
  3163. return true;
  3164. }
  3165. #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
  3166. return (lhs.is_discarded() || rhs.is_discarded()) && !inverse;
  3167. #else
  3168. static_cast<void>(inverse);
  3169. return lhs.is_discarded() || rhs.is_discarded();
  3170. #endif
  3171. }
  3172. private:
  3173. bool compares_unordered(const_reference rhs, bool inverse = false) const noexcept
  3174. {
  3175. return compares_unordered(*this, rhs, inverse);
  3176. }
  3177. public:
  3178. #if JSON_HAS_THREE_WAY_COMPARISON
  3179. /// @brief comparison: equal
  3180. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3181. bool operator==(const_reference rhs) const noexcept
  3182. {
  3183. #ifdef __GNUC__
  3184. #pragma GCC diagnostic push
  3185. #pragma GCC diagnostic ignored "-Wfloat-equal"
  3186. #endif
  3187. const_reference lhs = *this;
  3188. JSON_IMPLEMENT_OPERATOR( ==, true, false, false)
  3189. #ifdef __GNUC__
  3190. #pragma GCC diagnostic pop
  3191. #endif
  3192. }
  3193. /// @brief comparison: equal
  3194. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3195. template<typename ScalarType>
  3196. requires std::is_scalar_v<ScalarType>
  3197. bool operator==(ScalarType rhs) const noexcept
  3198. {
  3199. return *this == basic_json(rhs);
  3200. }
  3201. /// @brief comparison: not equal
  3202. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3203. bool operator!=(const_reference rhs) const noexcept
  3204. {
  3205. if (compares_unordered(rhs, true))
  3206. {
  3207. return false;
  3208. }
  3209. return !operator==(rhs);
  3210. }
  3211. /// @brief comparison: 3-way
  3212. /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
  3213. std::partial_ordering operator<=>(const_reference rhs) const noexcept // *NOPAD*
  3214. {
  3215. const_reference lhs = *this;
  3216. // default_result is used if we cannot compare values. In that case,
  3217. // we compare types.
  3218. JSON_IMPLEMENT_OPERATOR(<=>, // *NOPAD*
  3219. std::partial_ordering::equivalent,
  3220. std::partial_ordering::unordered,
  3221. lhs_type <=> rhs_type) // *NOPAD*
  3222. }
  3223. /// @brief comparison: 3-way
  3224. /// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
  3225. template<typename ScalarType>
  3226. requires std::is_scalar_v<ScalarType>
  3227. std::partial_ordering operator<=>(ScalarType rhs) const noexcept // *NOPAD*
  3228. {
  3229. return *this <=> basic_json(rhs); // *NOPAD*
  3230. }
  3231. #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
  3232. // all operators that are computed as an odd number of inverses of others
  3233. // need to be overloaded to emulate the legacy comparison behavior
  3234. /// @brief comparison: less than or equal
  3235. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3236. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
  3237. bool operator<=(const_reference rhs) const noexcept
  3238. {
  3239. if (compares_unordered(rhs, true))
  3240. {
  3241. return false;
  3242. }
  3243. return !(rhs < *this);
  3244. }
  3245. /// @brief comparison: less than or equal
  3246. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3247. template<typename ScalarType>
  3248. requires std::is_scalar_v<ScalarType>
  3249. bool operator<=(ScalarType rhs) const noexcept
  3250. {
  3251. return *this <= basic_json(rhs);
  3252. }
  3253. /// @brief comparison: greater than or equal
  3254. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3255. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
  3256. bool operator>=(const_reference rhs) const noexcept
  3257. {
  3258. if (compares_unordered(rhs, true))
  3259. {
  3260. return false;
  3261. }
  3262. return !(*this < rhs);
  3263. }
  3264. /// @brief comparison: greater than or equal
  3265. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3266. template<typename ScalarType>
  3267. requires std::is_scalar_v<ScalarType>
  3268. bool operator>=(ScalarType rhs) const noexcept
  3269. {
  3270. return *this >= basic_json(rhs);
  3271. }
  3272. #endif
  3273. #else
  3274. /// @brief comparison: equal
  3275. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3276. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  3277. {
  3278. #ifdef __GNUC__
  3279. #pragma GCC diagnostic push
  3280. #pragma GCC diagnostic ignored "-Wfloat-equal"
  3281. #endif
  3282. JSON_IMPLEMENT_OPERATOR( ==, true, false, false)
  3283. #ifdef __GNUC__
  3284. #pragma GCC diagnostic pop
  3285. #endif
  3286. }
  3287. /// @brief comparison: equal
  3288. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3289. template<typename ScalarType, typename std::enable_if<
  3290. std::is_scalar<ScalarType>::value, int>::type = 0>
  3291. friend bool operator==(const_reference lhs, ScalarType rhs) noexcept
  3292. {
  3293. return lhs == basic_json(rhs);
  3294. }
  3295. /// @brief comparison: equal
  3296. /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/
  3297. template<typename ScalarType, typename std::enable_if<
  3298. std::is_scalar<ScalarType>::value, int>::type = 0>
  3299. friend bool operator==(ScalarType lhs, const_reference rhs) noexcept
  3300. {
  3301. return basic_json(lhs) == rhs;
  3302. }
  3303. /// @brief comparison: not equal
  3304. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3305. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  3306. {
  3307. if (compares_unordered(lhs, rhs, true))
  3308. {
  3309. return false;
  3310. }
  3311. return !(lhs == rhs);
  3312. }
  3313. /// @brief comparison: not equal
  3314. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3315. template<typename ScalarType, typename std::enable_if<
  3316. std::is_scalar<ScalarType>::value, int>::type = 0>
  3317. friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept
  3318. {
  3319. return lhs != basic_json(rhs);
  3320. }
  3321. /// @brief comparison: not equal
  3322. /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
  3323. template<typename ScalarType, typename std::enable_if<
  3324. std::is_scalar<ScalarType>::value, int>::type = 0>
  3325. friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept
  3326. {
  3327. return basic_json(lhs) != rhs;
  3328. }
  3329. /// @brief comparison: less than
  3330. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  3331. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  3332. {
  3333. // default_result is used if we cannot compare values. In that case,
  3334. // we compare types. Note we have to call the operator explicitly,
  3335. // because MSVC has problems otherwise.
  3336. JSON_IMPLEMENT_OPERATOR( <, false, false, operator<(lhs_type, rhs_type))
  3337. }
  3338. /// @brief comparison: less than
  3339. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  3340. template<typename ScalarType, typename std::enable_if<
  3341. std::is_scalar<ScalarType>::value, int>::type = 0>
  3342. friend bool operator<(const_reference lhs, ScalarType rhs) noexcept
  3343. {
  3344. return lhs < basic_json(rhs);
  3345. }
  3346. /// @brief comparison: less than
  3347. /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/
  3348. template<typename ScalarType, typename std::enable_if<
  3349. std::is_scalar<ScalarType>::value, int>::type = 0>
  3350. friend bool operator<(ScalarType lhs, const_reference rhs) noexcept
  3351. {
  3352. return basic_json(lhs) < rhs;
  3353. }
  3354. /// @brief comparison: less than or equal
  3355. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3356. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  3357. {
  3358. if (compares_unordered(lhs, rhs, true))
  3359. {
  3360. return false;
  3361. }
  3362. return !(rhs < lhs);
  3363. }
  3364. /// @brief comparison: less than or equal
  3365. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3366. template<typename ScalarType, typename std::enable_if<
  3367. std::is_scalar<ScalarType>::value, int>::type = 0>
  3368. friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept
  3369. {
  3370. return lhs <= basic_json(rhs);
  3371. }
  3372. /// @brief comparison: less than or equal
  3373. /// @sa https://json.nlohmann.me/api/basic_json/operator_le/
  3374. template<typename ScalarType, typename std::enable_if<
  3375. std::is_scalar<ScalarType>::value, int>::type = 0>
  3376. friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept
  3377. {
  3378. return basic_json(lhs) <= rhs;
  3379. }
  3380. /// @brief comparison: greater than
  3381. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  3382. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  3383. {
  3384. // double inverse
  3385. if (compares_unordered(lhs, rhs))
  3386. {
  3387. return false;
  3388. }
  3389. return !(lhs <= rhs);
  3390. }
  3391. /// @brief comparison: greater than
  3392. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  3393. template<typename ScalarType, typename std::enable_if<
  3394. std::is_scalar<ScalarType>::value, int>::type = 0>
  3395. friend bool operator>(const_reference lhs, ScalarType rhs) noexcept
  3396. {
  3397. return lhs > basic_json(rhs);
  3398. }
  3399. /// @brief comparison: greater than
  3400. /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/
  3401. template<typename ScalarType, typename std::enable_if<
  3402. std::is_scalar<ScalarType>::value, int>::type = 0>
  3403. friend bool operator>(ScalarType lhs, const_reference rhs) noexcept
  3404. {
  3405. return basic_json(lhs) > rhs;
  3406. }
  3407. /// @brief comparison: greater than or equal
  3408. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3409. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  3410. {
  3411. if (compares_unordered(lhs, rhs, true))
  3412. {
  3413. return false;
  3414. }
  3415. return !(lhs < rhs);
  3416. }
  3417. /// @brief comparison: greater than or equal
  3418. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3419. template<typename ScalarType, typename std::enable_if<
  3420. std::is_scalar<ScalarType>::value, int>::type = 0>
  3421. friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept
  3422. {
  3423. return lhs >= basic_json(rhs);
  3424. }
  3425. /// @brief comparison: greater than or equal
  3426. /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/
  3427. template<typename ScalarType, typename std::enable_if<
  3428. std::is_scalar<ScalarType>::value, int>::type = 0>
  3429. friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept
  3430. {
  3431. return basic_json(lhs) >= rhs;
  3432. }
  3433. #endif
  3434. #undef JSON_IMPLEMENT_OPERATOR
  3435. /// @}
  3436. ///////////////////
  3437. // serialization //
  3438. ///////////////////
  3439. /// @name serialization
  3440. /// @{
  3441. #ifndef JSON_NO_IO
  3442. /// @brief serialize to stream
  3443. /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
  3444. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  3445. {
  3446. // read width member and use it as indentation parameter if nonzero
  3447. const bool pretty_print = o.width() > 0;
  3448. const auto indentation = pretty_print ? o.width() : 0;
  3449. // reset width to 0 for subsequent calls to this stream
  3450. o.width(0);
  3451. // do the actual serialization
  3452. serializer s(detail::output_adapter<char>(o), o.fill());
  3453. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  3454. return o;
  3455. }
  3456. /// @brief serialize to stream
  3457. /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/
  3458. /// @deprecated This function is deprecated since 3.0.0 and will be removed in
  3459. /// version 4.0.0 of the library. Please use
  3460. /// operator<<(std::ostream&, const basic_json&) instead; that is,
  3461. /// replace calls like `j >> o;` with `o << j;`.
  3462. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  3463. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  3464. {
  3465. return o << j;
  3466. }
  3467. #endif // JSON_NO_IO
  3468. /// @}
  3469. /////////////////////
  3470. // deserialization //
  3471. /////////////////////
  3472. /// @name deserialization
  3473. /// @{
  3474. /// @brief deserialize from a compatible input
  3475. /// @sa https://json.nlohmann.me/api/basic_json/parse/
  3476. template<typename InputType>
  3477. JSON_HEDLEY_WARN_UNUSED_RESULT
  3478. static basic_json parse(InputType&& i,
  3479. const parser_callback_t cb = nullptr,
  3480. const bool allow_exceptions = true,
  3481. const bool ignore_comments = false)
  3482. {
  3483. basic_json result;
  3484. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  3485. return result;
  3486. }
  3487. /// @brief deserialize from a pair of character iterators
  3488. /// @sa https://json.nlohmann.me/api/basic_json/parse/
  3489. template<typename IteratorType>
  3490. JSON_HEDLEY_WARN_UNUSED_RESULT
  3491. static basic_json parse(IteratorType first,
  3492. IteratorType last,
  3493. const parser_callback_t cb = nullptr,
  3494. const bool allow_exceptions = true,
  3495. const bool ignore_comments = false)
  3496. {
  3497. basic_json result;
  3498. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  3499. return result;
  3500. }
  3501. JSON_HEDLEY_WARN_UNUSED_RESULT
  3502. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  3503. static basic_json parse(detail::span_input_adapter&& i,
  3504. const parser_callback_t cb = nullptr,
  3505. const bool allow_exceptions = true,
  3506. const bool ignore_comments = false)
  3507. {
  3508. basic_json result;
  3509. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  3510. return result;
  3511. }
  3512. /// @brief check if the input is valid JSON
  3513. /// @sa https://json.nlohmann.me/api/basic_json/accept/
  3514. template<typename InputType>
  3515. static bool accept(InputType&& i,
  3516. const bool ignore_comments = false)
  3517. {
  3518. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  3519. }
  3520. /// @brief check if the input is valid JSON
  3521. /// @sa https://json.nlohmann.me/api/basic_json/accept/
  3522. template<typename IteratorType>
  3523. static bool accept(IteratorType first, IteratorType last,
  3524. const bool ignore_comments = false)
  3525. {
  3526. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  3527. }
  3528. JSON_HEDLEY_WARN_UNUSED_RESULT
  3529. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  3530. static bool accept(detail::span_input_adapter&& i,
  3531. const bool ignore_comments = false)
  3532. {
  3533. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  3534. }
  3535. /// @brief generate SAX events
  3536. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  3537. template <typename InputType, typename SAX>
  3538. JSON_HEDLEY_NON_NULL(2)
  3539. static bool sax_parse(InputType&& i, SAX* sax,
  3540. input_format_t format = input_format_t::json,
  3541. const bool strict = true,
  3542. const bool ignore_comments = false)
  3543. {
  3544. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3545. return format == input_format_t::json
  3546. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  3547. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format).sax_parse(format, sax, strict);
  3548. }
  3549. /// @brief generate SAX events
  3550. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  3551. template<class IteratorType, class SAX>
  3552. JSON_HEDLEY_NON_NULL(3)
  3553. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  3554. input_format_t format = input_format_t::json,
  3555. const bool strict = true,
  3556. const bool ignore_comments = false)
  3557. {
  3558. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3559. return format == input_format_t::json
  3560. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  3561. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format).sax_parse(format, sax, strict);
  3562. }
  3563. /// @brief generate SAX events
  3564. /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/
  3565. /// @deprecated This function is deprecated since 3.8.0 and will be removed in
  3566. /// version 4.0.0 of the library. Please use
  3567. /// sax_parse(ptr, ptr + len) instead.
  3568. template <typename SAX>
  3569. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  3570. JSON_HEDLEY_NON_NULL(2)
  3571. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  3572. input_format_t format = input_format_t::json,
  3573. const bool strict = true,
  3574. const bool ignore_comments = false)
  3575. {
  3576. auto ia = i.get();
  3577. return format == input_format_t::json
  3578. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3579. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  3580. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3581. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia), format).sax_parse(format, sax, strict);
  3582. }
  3583. #ifndef JSON_NO_IO
  3584. /// @brief deserialize from stream
  3585. /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
  3586. /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in
  3587. /// version 4.0.0 of the library. Please use
  3588. /// operator>>(std::istream&, basic_json&) instead; that is,
  3589. /// replace calls like `j << i;` with `i >> j;`.
  3590. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  3591. friend std::istream& operator<<(basic_json& j, std::istream& i)
  3592. {
  3593. return operator>>(i, j);
  3594. }
  3595. /// @brief deserialize from stream
  3596. /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
  3597. friend std::istream& operator>>(std::istream& i, basic_json& j)
  3598. {
  3599. parser(detail::input_adapter(i)).parse(false, j);
  3600. return i;
  3601. }
  3602. #endif // JSON_NO_IO
  3603. /// @}
  3604. ///////////////////////////
  3605. // convenience functions //
  3606. ///////////////////////////
  3607. /// @brief return the type as string
  3608. /// @sa https://json.nlohmann.me/api/basic_json/type_name/
  3609. JSON_HEDLEY_RETURNS_NON_NULL
  3610. const char* type_name() const noexcept
  3611. {
  3612. switch (m_data.m_type)
  3613. {
  3614. case value_t::null:
  3615. return "null";
  3616. case value_t::object:
  3617. return "object";
  3618. case value_t::array:
  3619. return "array";
  3620. case value_t::string:
  3621. return "string";
  3622. case value_t::boolean:
  3623. return "boolean";
  3624. case value_t::binary:
  3625. return "binary";
  3626. case value_t::discarded:
  3627. return "discarded";
  3628. case value_t::number_integer:
  3629. case value_t::number_unsigned:
  3630. case value_t::number_float:
  3631. default:
  3632. return "number";
  3633. }
  3634. }
  3635. JSON_PRIVATE_UNLESS_TESTED:
  3636. //////////////////////
  3637. // member variables //
  3638. //////////////////////
  3639. struct data
  3640. {
  3641. /// the type of the current element
  3642. value_t m_type = value_t::null;
  3643. /// the value of the current element
  3644. json_value m_value = {};
  3645. data(const value_t v)
  3646. : m_type(v), m_value(v)
  3647. {
  3648. }
  3649. data(size_type cnt, const basic_json& val)
  3650. : m_type(value_t::array)
  3651. {
  3652. m_value.array = create<array_t>(cnt, val);
  3653. }
  3654. data() noexcept = default;
  3655. data(data&&) noexcept = default;
  3656. data(const data&) noexcept = delete;
  3657. data& operator=(data&&) noexcept = delete;
  3658. data& operator=(const data&) noexcept = delete;
  3659. ~data() noexcept
  3660. {
  3661. m_value.destroy(m_type);
  3662. }
  3663. };
  3664. data m_data = {};
  3665. #if JSON_DIAGNOSTICS
  3666. /// a pointer to a parent value (for debugging purposes)
  3667. basic_json* m_parent = nullptr;
  3668. #endif
  3669. //////////////////////////////////////////
  3670. // binary serialization/deserialization //
  3671. //////////////////////////////////////////
  3672. /// @name binary serialization/deserialization support
  3673. /// @{
  3674. public:
  3675. /// @brief create a CBOR serialization of a given JSON value
  3676. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  3677. static std::vector<std::uint8_t> to_cbor(const basic_json& j)
  3678. {
  3679. std::vector<std::uint8_t> result;
  3680. to_cbor(j, result);
  3681. return result;
  3682. }
  3683. /// @brief create a CBOR serialization of a given JSON value
  3684. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  3685. static void to_cbor(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  3686. {
  3687. binary_writer<std::uint8_t>(o).write_cbor(j);
  3688. }
  3689. /// @brief create a CBOR serialization of a given JSON value
  3690. /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/
  3691. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  3692. {
  3693. binary_writer<char>(o).write_cbor(j);
  3694. }
  3695. /// @brief create a MessagePack serialization of a given JSON value
  3696. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  3697. static std::vector<std::uint8_t> to_msgpack(const basic_json& j)
  3698. {
  3699. std::vector<std::uint8_t> result;
  3700. to_msgpack(j, result);
  3701. return result;
  3702. }
  3703. /// @brief create a MessagePack serialization of a given JSON value
  3704. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  3705. static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  3706. {
  3707. binary_writer<std::uint8_t>(o).write_msgpack(j);
  3708. }
  3709. /// @brief create a MessagePack serialization of a given JSON value
  3710. /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/
  3711. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  3712. {
  3713. binary_writer<char>(o).write_msgpack(j);
  3714. }
  3715. /// @brief create a UBJSON serialization of a given JSON value
  3716. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  3717. static std::vector<std::uint8_t> to_ubjson(const basic_json& j,
  3718. const bool use_size = false,
  3719. const bool use_type = false)
  3720. {
  3721. std::vector<std::uint8_t> result;
  3722. to_ubjson(j, result, use_size, use_type);
  3723. return result;
  3724. }
  3725. /// @brief create a UBJSON serialization of a given JSON value
  3726. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  3727. static void to_ubjson(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  3728. const bool use_size = false, const bool use_type = false)
  3729. {
  3730. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type);
  3731. }
  3732. /// @brief create a UBJSON serialization of a given JSON value
  3733. /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/
  3734. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  3735. const bool use_size = false, const bool use_type = false)
  3736. {
  3737. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  3738. }
  3739. /// @brief create a BJData serialization of a given JSON value
  3740. /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
  3741. static std::vector<std::uint8_t> to_bjdata(const basic_json& j,
  3742. const bool use_size = false,
  3743. const bool use_type = false)
  3744. {
  3745. std::vector<std::uint8_t> result;
  3746. to_bjdata(j, result, use_size, use_type);
  3747. return result;
  3748. }
  3749. /// @brief create a BJData serialization of a given JSON value
  3750. /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
  3751. static void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,
  3752. const bool use_size = false, const bool use_type = false)
  3753. {
  3754. binary_writer<std::uint8_t>(o).write_ubjson(j, use_size, use_type, true, true);
  3755. }
  3756. /// @brief create a BJData serialization of a given JSON value
  3757. /// @sa https://json.nlohmann.me/api/basic_json/to_bjdata/
  3758. static void to_bjdata(const basic_json& j, detail::output_adapter<char> o,
  3759. const bool use_size = false, const bool use_type = false)
  3760. {
  3761. binary_writer<char>(o).write_ubjson(j, use_size, use_type, true, true);
  3762. }
  3763. /// @brief create a BSON serialization of a given JSON value
  3764. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  3765. static std::vector<std::uint8_t> to_bson(const basic_json& j)
  3766. {
  3767. std::vector<std::uint8_t> result;
  3768. to_bson(j, result);
  3769. return result;
  3770. }
  3771. /// @brief create a BSON serialization of a given JSON value
  3772. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  3773. static void to_bson(const basic_json& j, detail::output_adapter<std::uint8_t> o)
  3774. {
  3775. binary_writer<std::uint8_t>(o).write_bson(j);
  3776. }
  3777. /// @brief create a BSON serialization of a given JSON value
  3778. /// @sa https://json.nlohmann.me/api/basic_json/to_bson/
  3779. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  3780. {
  3781. binary_writer<char>(o).write_bson(j);
  3782. }
  3783. /// @brief create a JSON value from an input in CBOR format
  3784. /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
  3785. template<typename InputType>
  3786. JSON_HEDLEY_WARN_UNUSED_RESULT
  3787. static basic_json from_cbor(InputType&& i,
  3788. const bool strict = true,
  3789. const bool allow_exceptions = true,
  3790. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3791. {
  3792. basic_json result;
  3793. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3794. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3795. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  3796. return res ? result : basic_json(value_t::discarded);
  3797. }
  3798. /// @brief create a JSON value from an input in CBOR format
  3799. /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/
  3800. template<typename IteratorType>
  3801. JSON_HEDLEY_WARN_UNUSED_RESULT
  3802. static basic_json from_cbor(IteratorType first, IteratorType last,
  3803. const bool strict = true,
  3804. const bool allow_exceptions = true,
  3805. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3806. {
  3807. basic_json result;
  3808. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3809. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3810. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  3811. return res ? result : basic_json(value_t::discarded);
  3812. }
  3813. template<typename T>
  3814. JSON_HEDLEY_WARN_UNUSED_RESULT
  3815. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  3816. static basic_json from_cbor(const T* ptr, std::size_t len,
  3817. const bool strict = true,
  3818. const bool allow_exceptions = true,
  3819. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3820. {
  3821. return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler);
  3822. }
  3823. JSON_HEDLEY_WARN_UNUSED_RESULT
  3824. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  3825. static basic_json from_cbor(detail::span_input_adapter&& i,
  3826. const bool strict = true,
  3827. const bool allow_exceptions = true,
  3828. const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)
  3829. {
  3830. basic_json result;
  3831. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3832. auto ia = i.get();
  3833. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3834. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler);
  3835. return res ? result : basic_json(value_t::discarded);
  3836. }
  3837. /// @brief create a JSON value from an input in MessagePack format
  3838. /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
  3839. template<typename InputType>
  3840. JSON_HEDLEY_WARN_UNUSED_RESULT
  3841. static basic_json from_msgpack(InputType&& i,
  3842. const bool strict = true,
  3843. const bool allow_exceptions = true)
  3844. {
  3845. basic_json result;
  3846. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3847. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3848. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict);
  3849. return res ? result : basic_json(value_t::discarded);
  3850. }
  3851. /// @brief create a JSON value from an input in MessagePack format
  3852. /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/
  3853. template<typename IteratorType>
  3854. JSON_HEDLEY_WARN_UNUSED_RESULT
  3855. static basic_json from_msgpack(IteratorType first, IteratorType last,
  3856. const bool strict = true,
  3857. const bool allow_exceptions = true)
  3858. {
  3859. basic_json result;
  3860. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3861. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3862. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict);
  3863. return res ? result : basic_json(value_t::discarded);
  3864. }
  3865. template<typename T>
  3866. JSON_HEDLEY_WARN_UNUSED_RESULT
  3867. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  3868. static basic_json from_msgpack(const T* ptr, std::size_t len,
  3869. const bool strict = true,
  3870. const bool allow_exceptions = true)
  3871. {
  3872. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  3873. }
  3874. JSON_HEDLEY_WARN_UNUSED_RESULT
  3875. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  3876. static basic_json from_msgpack(detail::span_input_adapter&& i,
  3877. const bool strict = true,
  3878. const bool allow_exceptions = true)
  3879. {
  3880. basic_json result;
  3881. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3882. auto ia = i.get();
  3883. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3884. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict);
  3885. return res ? result : basic_json(value_t::discarded);
  3886. }
  3887. /// @brief create a JSON value from an input in UBJSON format
  3888. /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
  3889. template<typename InputType>
  3890. JSON_HEDLEY_WARN_UNUSED_RESULT
  3891. static basic_json from_ubjson(InputType&& i,
  3892. const bool strict = true,
  3893. const bool allow_exceptions = true)
  3894. {
  3895. basic_json result;
  3896. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3897. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3898. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict);
  3899. return res ? result : basic_json(value_t::discarded);
  3900. }
  3901. /// @brief create a JSON value from an input in UBJSON format
  3902. /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/
  3903. template<typename IteratorType>
  3904. JSON_HEDLEY_WARN_UNUSED_RESULT
  3905. static basic_json from_ubjson(IteratorType first, IteratorType last,
  3906. const bool strict = true,
  3907. const bool allow_exceptions = true)
  3908. {
  3909. basic_json result;
  3910. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3911. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3912. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict);
  3913. return res ? result : basic_json(value_t::discarded);
  3914. }
  3915. template<typename T>
  3916. JSON_HEDLEY_WARN_UNUSED_RESULT
  3917. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  3918. static basic_json from_ubjson(const T* ptr, std::size_t len,
  3919. const bool strict = true,
  3920. const bool allow_exceptions = true)
  3921. {
  3922. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  3923. }
  3924. JSON_HEDLEY_WARN_UNUSED_RESULT
  3925. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  3926. static basic_json from_ubjson(detail::span_input_adapter&& i,
  3927. const bool strict = true,
  3928. const bool allow_exceptions = true)
  3929. {
  3930. basic_json result;
  3931. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3932. auto ia = i.get();
  3933. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  3934. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict);
  3935. return res ? result : basic_json(value_t::discarded);
  3936. }
  3937. /// @brief create a JSON value from an input in BJData format
  3938. /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/
  3939. template<typename InputType>
  3940. JSON_HEDLEY_WARN_UNUSED_RESULT
  3941. static basic_json from_bjdata(InputType&& i,
  3942. const bool strict = true,
  3943. const bool allow_exceptions = true)
  3944. {
  3945. basic_json result;
  3946. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3947. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3948. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict);
  3949. return res ? result : basic_json(value_t::discarded);
  3950. }
  3951. /// @brief create a JSON value from an input in BJData format
  3952. /// @sa https://json.nlohmann.me/api/basic_json/from_bjdata/
  3953. template<typename IteratorType>
  3954. JSON_HEDLEY_WARN_UNUSED_RESULT
  3955. static basic_json from_bjdata(IteratorType first, IteratorType last,
  3956. const bool strict = true,
  3957. const bool allow_exceptions = true)
  3958. {
  3959. basic_json result;
  3960. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3961. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3962. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict);
  3963. return res ? result : basic_json(value_t::discarded);
  3964. }
  3965. /// @brief create a JSON value from an input in BSON format
  3966. /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
  3967. template<typename InputType>
  3968. JSON_HEDLEY_WARN_UNUSED_RESULT
  3969. static basic_json from_bson(InputType&& i,
  3970. const bool strict = true,
  3971. const bool allow_exceptions = true)
  3972. {
  3973. basic_json result;
  3974. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3975. auto ia = detail::input_adapter(std::forward<InputType>(i));
  3976. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict);
  3977. return res ? result : basic_json(value_t::discarded);
  3978. }
  3979. /// @brief create a JSON value from an input in BSON format
  3980. /// @sa https://json.nlohmann.me/api/basic_json/from_bson/
  3981. template<typename IteratorType>
  3982. JSON_HEDLEY_WARN_UNUSED_RESULT
  3983. static basic_json from_bson(IteratorType first, IteratorType last,
  3984. const bool strict = true,
  3985. const bool allow_exceptions = true)
  3986. {
  3987. basic_json result;
  3988. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  3989. auto ia = detail::input_adapter(std::move(first), std::move(last));
  3990. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict);
  3991. return res ? result : basic_json(value_t::discarded);
  3992. }
  3993. template<typename T>
  3994. JSON_HEDLEY_WARN_UNUSED_RESULT
  3995. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  3996. static basic_json from_bson(const T* ptr, std::size_t len,
  3997. const bool strict = true,
  3998. const bool allow_exceptions = true)
  3999. {
  4000. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  4001. }
  4002. JSON_HEDLEY_WARN_UNUSED_RESULT
  4003. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  4004. static basic_json from_bson(detail::span_input_adapter&& i,
  4005. const bool strict = true,
  4006. const bool allow_exceptions = true)
  4007. {
  4008. basic_json result;
  4009. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  4010. auto ia = i.get();
  4011. // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
  4012. const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict);
  4013. return res ? result : basic_json(value_t::discarded);
  4014. }
  4015. /// @}
  4016. //////////////////////////
  4017. // JSON Pointer support //
  4018. //////////////////////////
  4019. /// @name JSON Pointer functions
  4020. /// @{
  4021. /// @brief access specified element via JSON Pointer
  4022. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  4023. reference operator[](const json_pointer& ptr)
  4024. {
  4025. return ptr.get_unchecked(this);
  4026. }
  4027. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4028. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4029. reference operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr)
  4030. {
  4031. return ptr.get_unchecked(this);
  4032. }
  4033. /// @brief access specified element via JSON Pointer
  4034. /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/
  4035. const_reference operator[](const json_pointer& ptr) const
  4036. {
  4037. return ptr.get_unchecked(this);
  4038. }
  4039. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4040. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4041. const_reference operator[](const ::nlohmann::json_pointer<BasicJsonType>& ptr) const
  4042. {
  4043. return ptr.get_unchecked(this);
  4044. }
  4045. /// @brief access specified element via JSON Pointer
  4046. /// @sa https://json.nlohmann.me/api/basic_json/at/
  4047. reference at(const json_pointer& ptr)
  4048. {
  4049. return ptr.get_checked(this);
  4050. }
  4051. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4052. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4053. reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr)
  4054. {
  4055. return ptr.get_checked(this);
  4056. }
  4057. /// @brief access specified element via JSON Pointer
  4058. /// @sa https://json.nlohmann.me/api/basic_json/at/
  4059. const_reference at(const json_pointer& ptr) const
  4060. {
  4061. return ptr.get_checked(this);
  4062. }
  4063. template<typename BasicJsonType, detail::enable_if_t<detail::is_basic_json<BasicJsonType>::value, int> = 0>
  4064. JSON_HEDLEY_DEPRECATED_FOR(3.11.0, basic_json::json_pointer or nlohmann::json_pointer<basic_json::string_t>) // NOLINT(readability/alt_tokens)
  4065. const_reference at(const ::nlohmann::json_pointer<BasicJsonType>& ptr) const
  4066. {
  4067. return ptr.get_checked(this);
  4068. }
  4069. /// @brief return flattened JSON value
  4070. /// @sa https://json.nlohmann.me/api/basic_json/flatten/
  4071. basic_json flatten() const
  4072. {
  4073. basic_json result(value_t::object);
  4074. json_pointer::flatten("", *this, result);
  4075. return result;
  4076. }
  4077. /// @brief unflatten a previously flattened JSON value
  4078. /// @sa https://json.nlohmann.me/api/basic_json/unflatten/
  4079. basic_json unflatten() const
  4080. {
  4081. return json_pointer::unflatten(*this);
  4082. }
  4083. /// @}
  4084. //////////////////////////
  4085. // JSON Patch functions //
  4086. //////////////////////////
  4087. /// @name JSON Patch functions
  4088. /// @{
  4089. /// @brief applies a JSON patch in-place without copying the object
  4090. /// @sa https://json.nlohmann.me/api/basic_json/patch/
  4091. void patch_inplace(const basic_json& json_patch)
  4092. {
  4093. basic_json& result = *this;
  4094. // the valid JSON Patch operations
  4095. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  4096. const auto get_op = [](const std::string & op)
  4097. {
  4098. if (op == "add")
  4099. {
  4100. return patch_operations::add;
  4101. }
  4102. if (op == "remove")
  4103. {
  4104. return patch_operations::remove;
  4105. }
  4106. if (op == "replace")
  4107. {
  4108. return patch_operations::replace;
  4109. }
  4110. if (op == "move")
  4111. {
  4112. return patch_operations::move;
  4113. }
  4114. if (op == "copy")
  4115. {
  4116. return patch_operations::copy;
  4117. }
  4118. if (op == "test")
  4119. {
  4120. return patch_operations::test;
  4121. }
  4122. return patch_operations::invalid;
  4123. };
  4124. // wrapper for "add" operation; add value at ptr
  4125. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  4126. {
  4127. // adding to the root of the target document means replacing it
  4128. if (ptr.empty())
  4129. {
  4130. result = val;
  4131. return;
  4132. }
  4133. // make sure the top element of the pointer exists
  4134. json_pointer const top_pointer = ptr.top();
  4135. if (top_pointer != ptr)
  4136. {
  4137. result.at(top_pointer);
  4138. }
  4139. // get reference to parent of JSON pointer ptr
  4140. const auto last_path = ptr.back();
  4141. ptr.pop_back();
  4142. // parent must exist when performing patch add per RFC6902 specs
  4143. basic_json& parent = result.at(ptr);
  4144. switch (parent.m_data.m_type)
  4145. {
  4146. case value_t::null:
  4147. case value_t::object:
  4148. {
  4149. // use operator[] to add value
  4150. parent[last_path] = val;
  4151. break;
  4152. }
  4153. case value_t::array:
  4154. {
  4155. if (last_path == "-")
  4156. {
  4157. // special case: append to back
  4158. parent.push_back(val);
  4159. }
  4160. else
  4161. {
  4162. const auto idx = json_pointer::template array_index<basic_json_t>(last_path);
  4163. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  4164. {
  4165. // avoid undefined behavior
  4166. JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), &parent));
  4167. }
  4168. // default case: insert add offset
  4169. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  4170. }
  4171. break;
  4172. }
  4173. // if there exists a parent it cannot be primitive
  4174. case value_t::string: // LCOV_EXCL_LINE
  4175. case value_t::boolean: // LCOV_EXCL_LINE
  4176. case value_t::number_integer: // LCOV_EXCL_LINE
  4177. case value_t::number_unsigned: // LCOV_EXCL_LINE
  4178. case value_t::number_float: // LCOV_EXCL_LINE
  4179. case value_t::binary: // LCOV_EXCL_LINE
  4180. case value_t::discarded: // LCOV_EXCL_LINE
  4181. default: // LCOV_EXCL_LINE
  4182. JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE
  4183. }
  4184. };
  4185. // wrapper for "remove" operation; remove value at ptr
  4186. const auto operation_remove = [this, &result](json_pointer & ptr)
  4187. {
  4188. // get reference to parent of JSON pointer ptr
  4189. const auto last_path = ptr.back();
  4190. ptr.pop_back();
  4191. basic_json& parent = result.at(ptr);
  4192. // remove child
  4193. if (parent.is_object())
  4194. {
  4195. // perform range check
  4196. auto it = parent.find(last_path);
  4197. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  4198. {
  4199. parent.erase(it);
  4200. }
  4201. else
  4202. {
  4203. JSON_THROW(out_of_range::create(403, detail::concat("key '", last_path, "' not found"), this));
  4204. }
  4205. }
  4206. else if (parent.is_array())
  4207. {
  4208. // note erase performs range check
  4209. parent.erase(json_pointer::template array_index<basic_json_t>(last_path));
  4210. }
  4211. };
  4212. // type check: top level value must be an array
  4213. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  4214. {
  4215. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", &json_patch));
  4216. }
  4217. // iterate and apply the operations
  4218. for (const auto& val : json_patch)
  4219. {
  4220. // wrapper to get a value for an operation
  4221. const auto get_value = [&val](const std::string & op,
  4222. const std::string & member,
  4223. bool string_type) -> basic_json &
  4224. {
  4225. // find value
  4226. auto it = val.m_data.m_value.object->find(member);
  4227. // context-sensitive error message
  4228. const auto error_msg = (op == "op") ? "operation" : detail::concat("operation '", op, '\'');
  4229. // check if desired value is present
  4230. if (JSON_HEDLEY_UNLIKELY(it == val.m_data.m_value.object->end()))
  4231. {
  4232. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  4233. JSON_THROW(parse_error::create(105, 0, detail::concat(error_msg, " must have member '", member, "'"), &val));
  4234. }
  4235. // check if result is of type string
  4236. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  4237. {
  4238. // NOLINTNEXTLINE(performance-inefficient-string-concatenation)
  4239. JSON_THROW(parse_error::create(105, 0, detail::concat(error_msg, " must have string member '", member, "'"), &val));
  4240. }
  4241. // no error: return value
  4242. return it->second;
  4243. };
  4244. // type check: every element of the array must be an object
  4245. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  4246. {
  4247. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", &val));
  4248. }
  4249. // collect mandatory members
  4250. const auto op = get_value("op", "op", true).template get<std::string>();
  4251. const auto path = get_value(op, "path", true).template get<std::string>();
  4252. json_pointer ptr(path);
  4253. switch (get_op(op))
  4254. {
  4255. case patch_operations::add:
  4256. {
  4257. operation_add(ptr, get_value("add", "value", false));
  4258. break;
  4259. }
  4260. case patch_operations::remove:
  4261. {
  4262. operation_remove(ptr);
  4263. break;
  4264. }
  4265. case patch_operations::replace:
  4266. {
  4267. // the "path" location must exist - use at()
  4268. result.at(ptr) = get_value("replace", "value", false);
  4269. break;
  4270. }
  4271. case patch_operations::move:
  4272. {
  4273. const auto from_path = get_value("move", "from", true).template get<std::string>();
  4274. json_pointer from_ptr(from_path);
  4275. // the "from" location must exist - use at()
  4276. basic_json const v = result.at(from_ptr);
  4277. // The move operation is functionally identical to a
  4278. // "remove" operation on the "from" location, followed
  4279. // immediately by an "add" operation at the target
  4280. // location with the value that was just removed.
  4281. operation_remove(from_ptr);
  4282. operation_add(ptr, v);
  4283. break;
  4284. }
  4285. case patch_operations::copy:
  4286. {
  4287. const auto from_path = get_value("copy", "from", true).template get<std::string>();
  4288. const json_pointer from_ptr(from_path);
  4289. // the "from" location must exist - use at()
  4290. basic_json const v = result.at(from_ptr);
  4291. // The copy is functionally identical to an "add"
  4292. // operation at the target location using the value
  4293. // specified in the "from" member.
  4294. operation_add(ptr, v);
  4295. break;
  4296. }
  4297. case patch_operations::test:
  4298. {
  4299. bool success = false;
  4300. JSON_TRY
  4301. {
  4302. // check if "value" matches the one at "path"
  4303. // the "path" location must exist - use at()
  4304. success = (result.at(ptr) == get_value("test", "value", false));
  4305. }
  4306. JSON_INTERNAL_CATCH (out_of_range&)
  4307. {
  4308. // ignore out of range errors: success remains false
  4309. }
  4310. // throw an exception if test fails
  4311. if (JSON_HEDLEY_UNLIKELY(!success))
  4312. {
  4313. JSON_THROW(other_error::create(501, detail::concat("unsuccessful: ", val.dump()), &val));
  4314. }
  4315. break;
  4316. }
  4317. case patch_operations::invalid:
  4318. default:
  4319. {
  4320. // op must be "add", "remove", "replace", "move", "copy", or
  4321. // "test"
  4322. JSON_THROW(parse_error::create(105, 0, detail::concat("operation value '", op, "' is invalid"), &val));
  4323. }
  4324. }
  4325. }
  4326. }
  4327. /// @brief applies a JSON patch to a copy of the current object
  4328. /// @sa https://json.nlohmann.me/api/basic_json/patch/
  4329. basic_json patch(const basic_json& json_patch) const
  4330. {
  4331. basic_json result = *this;
  4332. result.patch_inplace(json_patch);
  4333. return result;
  4334. }
  4335. /// @brief creates a diff as a JSON patch
  4336. /// @sa https://json.nlohmann.me/api/basic_json/diff/
  4337. JSON_HEDLEY_WARN_UNUSED_RESULT
  4338. static basic_json diff(const basic_json& source, const basic_json& target,
  4339. const std::string& path = "")
  4340. {
  4341. // the patch
  4342. basic_json result(value_t::array);
  4343. // if the values are the same, return empty patch
  4344. if (source == target)
  4345. {
  4346. return result;
  4347. }
  4348. if (source.type() != target.type())
  4349. {
  4350. // different types: replace value
  4351. result.push_back(
  4352. {
  4353. {"op", "replace"}, {"path", path}, {"value", target}
  4354. });
  4355. return result;
  4356. }
  4357. switch (source.type())
  4358. {
  4359. case value_t::array:
  4360. {
  4361. // first pass: traverse common elements
  4362. std::size_t i = 0;
  4363. while (i < source.size() && i < target.size())
  4364. {
  4365. // recursive call to compare array values at index i
  4366. auto temp_diff = diff(source[i], target[i], detail::concat(path, '/', std::to_string(i)));
  4367. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  4368. ++i;
  4369. }
  4370. // We now reached the end of at least one array
  4371. // in a second pass, traverse the remaining elements
  4372. // remove my remaining elements
  4373. const auto end_index = static_cast<difference_type>(result.size());
  4374. while (i < source.size())
  4375. {
  4376. // add operations in reverse order to avoid invalid
  4377. // indices
  4378. result.insert(result.begin() + end_index, object(
  4379. {
  4380. {"op", "remove"},
  4381. {"path", detail::concat(path, '/', std::to_string(i))}
  4382. }));
  4383. ++i;
  4384. }
  4385. // add other remaining elements
  4386. while (i < target.size())
  4387. {
  4388. result.push_back(
  4389. {
  4390. {"op", "add"},
  4391. {"path", detail::concat(path, "/-")},
  4392. {"value", target[i]}
  4393. });
  4394. ++i;
  4395. }
  4396. break;
  4397. }
  4398. case value_t::object:
  4399. {
  4400. // first pass: traverse this object's elements
  4401. for (auto it = source.cbegin(); it != source.cend(); ++it)
  4402. {
  4403. // escape the key name to be used in a JSON patch
  4404. const auto path_key = detail::concat(path, '/', detail::escape(it.key()));
  4405. if (target.find(it.key()) != target.end())
  4406. {
  4407. // recursive call to compare object values at key it
  4408. auto temp_diff = diff(it.value(), target[it.key()], path_key);
  4409. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  4410. }
  4411. else
  4412. {
  4413. // found a key that is not in o -> remove it
  4414. result.push_back(object(
  4415. {
  4416. {"op", "remove"}, {"path", path_key}
  4417. }));
  4418. }
  4419. }
  4420. // second pass: traverse other object's elements
  4421. for (auto it = target.cbegin(); it != target.cend(); ++it)
  4422. {
  4423. if (source.find(it.key()) == source.end())
  4424. {
  4425. // found a key that is not in this -> add it
  4426. const auto path_key = detail::concat(path, '/', detail::escape(it.key()));
  4427. result.push_back(
  4428. {
  4429. {"op", "add"}, {"path", path_key},
  4430. {"value", it.value()}
  4431. });
  4432. }
  4433. }
  4434. break;
  4435. }
  4436. case value_t::null:
  4437. case value_t::string:
  4438. case value_t::boolean:
  4439. case value_t::number_integer:
  4440. case value_t::number_unsigned:
  4441. case value_t::number_float:
  4442. case value_t::binary:
  4443. case value_t::discarded:
  4444. default:
  4445. {
  4446. // both primitive type: replace value
  4447. result.push_back(
  4448. {
  4449. {"op", "replace"}, {"path", path}, {"value", target}
  4450. });
  4451. break;
  4452. }
  4453. }
  4454. return result;
  4455. }
  4456. /// @}
  4457. ////////////////////////////////
  4458. // JSON Merge Patch functions //
  4459. ////////////////////////////////
  4460. /// @name JSON Merge Patch functions
  4461. /// @{
  4462. /// @brief applies a JSON Merge Patch
  4463. /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/
  4464. void merge_patch(const basic_json& apply_patch)
  4465. {
  4466. if (apply_patch.is_object())
  4467. {
  4468. if (!is_object())
  4469. {
  4470. *this = object();
  4471. }
  4472. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  4473. {
  4474. if (it.value().is_null())
  4475. {
  4476. erase(it.key());
  4477. }
  4478. else
  4479. {
  4480. operator[](it.key()).merge_patch(it.value());
  4481. }
  4482. }
  4483. }
  4484. else
  4485. {
  4486. *this = apply_patch;
  4487. }
  4488. }
  4489. /// @}
  4490. };
  4491. /// @brief user-defined to_string function for JSON values
  4492. /// @sa https://json.nlohmann.me/api/basic_json/to_string/
  4493. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  4494. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  4495. {
  4496. return j.dump();
  4497. }
  4498. inline namespace literals
  4499. {
  4500. inline namespace json_literals
  4501. {
  4502. /// @brief user-defined string literal for JSON values
  4503. /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/
  4504. JSON_HEDLEY_NON_NULL(1)
  4505. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  4506. {
  4507. return nlohmann::json::parse(s, s + n);
  4508. }
  4509. /// @brief user-defined string literal for JSON pointer
  4510. /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/
  4511. JSON_HEDLEY_NON_NULL(1)
  4512. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  4513. {
  4514. return nlohmann::json::json_pointer(std::string(s, n));
  4515. }
  4516. } // namespace json_literals
  4517. } // namespace literals
  4518. NLOHMANN_JSON_NAMESPACE_END
  4519. ///////////////////////
  4520. // nonmember support //
  4521. ///////////////////////
  4522. namespace std // NOLINT(cert-dcl58-cpp)
  4523. {
  4524. /// @brief hash value for JSON objects
  4525. /// @sa https://json.nlohmann.me/api/basic_json/std_hash/
  4526. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  4527. struct hash<nlohmann::NLOHMANN_BASIC_JSON_TPL> // NOLINT(cert-dcl58-cpp)
  4528. {
  4529. std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const
  4530. {
  4531. return nlohmann::detail::hash(j);
  4532. }
  4533. };
  4534. // specialization for std::less<value_t>
  4535. template<>
  4536. struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679
  4537. {
  4538. /*!
  4539. @brief compare two value_t enum values
  4540. @since version 3.0.0
  4541. */
  4542. bool operator()(::nlohmann::detail::value_t lhs,
  4543. ::nlohmann::detail::value_t rhs) const noexcept
  4544. {
  4545. #if JSON_HAS_THREE_WAY_COMPARISON
  4546. return std::is_lt(lhs <=> rhs); // *NOPAD*
  4547. #else
  4548. return ::nlohmann::detail::operator<(lhs, rhs);
  4549. #endif
  4550. }
  4551. };
  4552. // C++20 prohibit function specialization in the std namespace.
  4553. #ifndef JSON_HAS_CPP_20
  4554. /// @brief exchanges the values of two JSON objects
  4555. /// @sa https://json.nlohmann.me/api/basic_json/std_swap/
  4556. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  4557. inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name, cert-dcl58-cpp)
  4558. is_nothrow_move_constructible<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value&& // NOLINT(misc-redundant-expression)
  4559. is_nothrow_move_assignable<nlohmann::NLOHMANN_BASIC_JSON_TPL>::value)
  4560. {
  4561. j1.swap(j2);
  4562. }
  4563. #endif
  4564. } // namespace std
  4565. #if JSON_USE_GLOBAL_UDLS
  4566. using nlohmann::literals::json_literals::operator "" _json; // NOLINT(misc-unused-using-decls,google-global-names-in-headers)
  4567. using nlohmann::literals::json_literals::operator "" _json_pointer; //NOLINT(misc-unused-using-decls,google-global-names-in-headers)
  4568. #endif
  4569. #include <nlohmann/detail/macro_unscope.hpp>
  4570. #endif // INCLUDE_NLOHMANN_JSON_HPP_