From 59a9fcee0d5c09c9beb565393b98d6a80ea4a36e Mon Sep 17 00:00:00 2001 From: Mr_Goldberg Date: Wed, 17 Jul 2019 13:25:35 -0400 Subject: [PATCH] Some cleanups. Load items json only if there's an inventory request. Launch callbacks only when loading is done. Copy over original unformatted json.hpp --- README.md | 12 - Readme_release.txt | 8 + dll/item_db_loader.cpp | 4 +- dll/steam_client.cpp | 6 +- dll/steam_inventory.h | 228 +- json/json.hpp | 34503 +++++++++++++++++++-------------------- 6 files changed, 17345 insertions(+), 17416 deletions(-) diff --git a/README.md b/README.md index bd22dc7..eec7959 100644 --- a/README.md +++ b/README.md @@ -16,18 +16,6 @@ If your game has an original steam_api(64).dll or libsteam_api.so older than may For more information see: [The Release Readme](Readme_release.txt) -## How to add items to your steam inventory - -Create a folder named steam_settings right beside steam_api.dll if there isn't one already. In that folder, create a file named items.json which will contain every item you want to have in your game. - -An example can be found in steam_settings.EXAMPLE that works with Killing Floor 2. - -The items.json syntax is simple, you SHOULD validate your .json file before trying to run your game or you won't have any item in your inventory. Just look for "online json validator" on your web brower to valide your file. - -You can use https://steamdb.info/ to list items and attributes they have and put them into your .json. - -Keep in mind that some item are not valid to have in your inventory. For example, in PayDay2 all items below item_id 50000 will make your game crash. - ## Download Binaries You can download the latest git builds for Linux and Windows on [the Gitlab pages website](https://mr_goldberg.gitlab.io/goldberg_emulator/) and the stable releases in the [release section](https://gitlab.com/Mr_Goldberg/goldberg_emulator/releases) of this repo. diff --git a/Readme_release.txt b/Readme_release.txt index 47b12ad..296d844 100644 --- a/Readme_release.txt +++ b/Readme_release.txt @@ -65,6 +65,14 @@ If you want to set custom ips (or domains) which the emulator will send broadcas If the custom ips/domains are specific for one game only you can put the custom_broadcasts.txt in the steam_settings\ folder. An example is provided in steam_settings.EXAMPLE\custom_broadcasts.EXAMPLE.txt +Items or Inventory: +Create a folder named steam_settings right beside steam_api.dll if there isn't one already. In that folder, create a file named items.json which will contain every item you want to have in your game. +An example can be found in steam_settings.EXAMPLE that works with Killing Floor 2. +The items.json syntax is simple, you SHOULD validate your .json file before trying to run your game or you won't have any item in your inventory. Just look for "online json validator" on your web brower to valide your file. +You can use https://steamdb.info/ to list items and attributes they have and put them into your .json. +Keep in mind that some item are not valid to have in your inventory. For example, in PayDay2 all items below item_id 50000 will make your game crash. + + Support for CPY steam_api(64).dll cracks: See the build in the experimental folder. diff --git a/dll/item_db_loader.cpp b/dll/item_db_loader.cpp index 4e27e55..ee59105 100644 --- a/dll/item_db_loader.cpp +++ b/dll/item_db_loader.cpp @@ -53,8 +53,10 @@ void read_items_db(std::string items_db, std::mapsize()); *is_loadedb = true; } \ No newline at end of file diff --git a/dll/steam_client.cpp b/dll/steam_client.cpp index 429be66..c68d022 100644 --- a/dll/steam_client.cpp +++ b/dll/steam_client.cpp @@ -291,6 +291,8 @@ Steam_Client::Steam_Client() } } + std::string items_db_file_path = (Local_Storage::get_game_settings_path() + "items.json"); + network = new Networking(settings_server->get_local_steam_id(), appid, port, &custom_broadcasts); callback_results_client = new SteamCallResults(); @@ -318,7 +320,7 @@ Steam_Client::Steam_Client() steam_music = new Steam_Music(callbacks_client); steam_musicremote = new Steam_MusicRemote(); steam_HTMLsurface = new Steam_HTMLsurface(settings_client, network, callback_results_client, callbacks_client); - steam_inventory = new Steam_Inventory(settings_client, callback_results_client, callbacks_client); + steam_inventory = new Steam_Inventory(settings_client, callback_results_client, callbacks_client, run_every_runcb, items_db_file_path); steam_video = new Steam_Video(); steam_parental = new Steam_Parental(); steam_networking_sockets = new Steam_Networking_Sockets(settings_client, network, callback_results_client, callbacks_client, run_every_runcb); @@ -335,7 +337,7 @@ Steam_Client::Steam_Client() steam_gameserverstats = new Steam_GameServerStats(settings_server, network, callback_results_server, callbacks_server); steam_gameserver_networking = new Steam_Networking(settings_server, network, callbacks_server, run_every_runcb); steam_gameserver_http = new Steam_HTTP(settings_server, network, callback_results_server, callbacks_server); - steam_gameserver_inventory = new Steam_Inventory(settings_server, callback_results_server, callbacks_server); + steam_gameserver_inventory = new Steam_Inventory(settings_server, callback_results_server, callbacks_server, run_every_runcb, items_db_file_path); steam_gameserver_ugc = new Steam_UGC(settings_server, callback_results_server, callbacks_server); steam_gameserver_apps = new Steam_Apps(settings_server, callback_results_server); steam_gameserver_networking_sockets = new Steam_Networking_Sockets(settings_server, network, callback_results_server, callbacks_server, run_every_runcb); diff --git a/dll/steam_inventory.h b/dll/steam_inventory.h index 1aedef9..5c6cf00 100644 --- a/dll/steam_inventory.h +++ b/dll/steam_inventory.h @@ -20,6 +20,8 @@ struct Steam_Inventory_Requests { double timeout = 0.1; + bool done = false; + bool full_query; SteamInventoryResult_t inventory_result; std::chrono::system_clock::time_point time_created; @@ -27,7 +29,7 @@ struct Steam_Inventory_Requests { std::vector instance_ids; bool result_done() { - return std::chrono::duration_cast>(std::chrono::system_clock::now() - time_created).count() > timeout; + return done; } uint32 timestamp() { @@ -43,30 +45,30 @@ class Steam_Inventory : class Settings *settings; class SteamCallResults *callback_results; class SteamCallBacks *callbacks; + class RunEveryRunCB *run_every_runcb; std::vector inventory_requests; - static std::once_flag items_loading; - static std::atomic_bool items_loaded; - static std::map> items; + std::map> items; // Like typedefs using item_iterator = std::map>::iterator; using attr_iterator = std::map::iterator; - // Set this to false when we have cached everything, - // reset to true if something changed in the item db. - // Could use inotify on linux - // Could use FindFirstChangeNotificationA + WaitForSingleObject + FindNextChangeNotification on Windows to monitor the db file - // Or find a server somewhere to hold the data for us then cache on local settings. - bool need_load_definitions = true; + std::atomic_bool items_loaded; + std::string items_db_file; + std::once_flag load_items_flag; + bool call_definition_update; + bool definition_update_called; + bool full_update_called; -struct Steam_Inventory_Requests* new_inventory_result(const SteamItemInstanceID_t* pInstanceIDs = NULL, uint32 unCountInstanceIDs = 0) +struct Steam_Inventory_Requests* new_inventory_result(bool full_query=true, const SteamItemInstanceID_t* pInstanceIDs = NULL, uint32 unCountInstanceIDs = 0) { static SteamInventoryResult_t result; ++result; struct Steam_Inventory_Requests request; request.inventory_result = result; + request.full_query = full_query; if (pInstanceIDs && unCountInstanceIDs) { for (int i = 0; i < unCountInstanceIDs; ++i) request.instance_ids.push_back(pInstanceIDs[i]); @@ -89,19 +91,34 @@ struct Steam_Inventory_Requests *get_inventory_result(SteamInventoryResult_t res public: -Steam_Inventory(class Settings *settings, class SteamCallResults *callback_results, class SteamCallBacks *callbacks) +static void run_every_runcb_cb(void *object) { - std::call_once(items_loading, [&]() - { - std::string items_db_file(Local_Storage::get_game_settings_path() + "items.json"); - PRINT_DEBUG("Items file path: %s\n", items_db_file.c_str()); - std::thread items_load_thread(read_items_db, items_db_file, &items, &items_loaded); - items_load_thread.detach(); - }); + PRINT_DEBUG("Steam_Inventory::run_every_runcb\n"); + + Steam_Inventory *obj = (Steam_Inventory *)object; + obj->RunCallbacks(); +} + +Steam_Inventory(class Settings *settings, class SteamCallResults *callback_results, class SteamCallBacks *callbacks, class RunEveryRunCB *run_every_runcb, std::string items_db_file_path) +{ + items_db_file = items_db_file_path; + PRINT_DEBUG("Items file path: %s\n", items_db_file.c_str()); + items_loaded = false; this->settings = settings; this->callbacks = callbacks; this->callback_results = callback_results; + this->run_every_runcb = run_every_runcb; + this->run_every_runcb->add(&Steam_Inventory::run_every_runcb_cb, this); + + call_definition_update = false; + definition_update_called = false; + full_update_called = false; +} + +~Steam_Inventory() +{ + this->run_every_runcb->remove(&Steam_Inventory::run_every_runcb_cb, this); } // INVENTORY ASYNC RESULT MANAGEMENT @@ -147,16 +164,29 @@ bool GetResultItems( SteamInventoryResult_t resultHandle, if (pOutItemsArray != nullptr) { uint32 max_items = *punOutItemsArraySize; - // We end if we reached the end of items or the end of buffer - for( auto i = items.begin(); i != items.end() && max_items; ++i, --max_items ) - { - pOutItemsArray->m_iDefinition = i->first; - pOutItemsArray->m_itemId = i->first; - pOutItemsArray->m_unQuantity = 1; - pOutItemsArray->m_unFlags = k_ESteamItemNoTrade; - ++pOutItemsArray; + + if (request->full_query) { + // We end if we reached the end of items or the end of buffer + for( auto i = items.begin(); i != items.end() && max_items; ++i, --max_items ) + { + pOutItemsArray->m_iDefinition = i->first; + pOutItemsArray->m_itemId = i->first; + pOutItemsArray->m_unQuantity = 1; + pOutItemsArray->m_unFlags = k_ESteamItemNoTrade; + ++pOutItemsArray; + } + *punOutItemsArraySize = std::min(*punOutItemsArraySize, static_cast(items.size())); + } else { + for (auto &itemid : request->instance_ids) { + if (!max_items) break; + pOutItemsArray->m_iDefinition = itemid; + pOutItemsArray->m_itemId = itemid; + pOutItemsArray->m_unQuantity = 1; + pOutItemsArray->m_unFlags = k_ESteamItemNoTrade; + ++pOutItemsArray; + --max_items; + } } - *punOutItemsArraySize = std::min(*punOutItemsArraySize, static_cast(items.size())); } else if (punOutItemsArraySize != nullptr) { @@ -248,48 +278,10 @@ bool GetAllItems( SteamInventoryResult_t *pResultHandle ) std::lock_guard lock(global_mutex); struct Steam_Inventory_Requests* request = new_inventory_result(); - // Can't call LoadItemDefinitions because it sends a SteamInventoryResultReady_t. - if( need_load_definitions ) - { - if (items_loaded) - { - need_load_definitions = false; - SteamInventoryDefinitionUpdate_t data = {}; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); - } - } + if (!definition_update_called) call_definition_update = true; - if (!need_load_definitions) - { - { - // SteamInventoryFullUpdate_t callbacks are triggered when GetAllItems - // successfully returns a result which is newer / fresher than the last - // known result. - //TODO: should this always be returned for each get all item calls? - struct SteamInventoryFullUpdate_t data; - data.m_handle = request->inventory_result; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), request->timeout); - } - { - struct SteamInventoryResultReady_t data; - data.m_handle = request->inventory_result; - data.m_result = k_EResultOK; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), request->timeout); - } - - if (pResultHandle != nullptr) - *pResultHandle = request->inventory_result; - } - else - { - struct SteamInventoryResultReady_t data; - data.m_handle = request->inventory_result; - data.m_result = k_EResultPending; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), request->timeout); - - if (pResultHandle != nullptr) - *pResultHandle = request->inventory_result; - } + if (pResultHandle != nullptr) + *pResultHandle = request->inventory_result; return true; } @@ -309,14 +301,7 @@ bool GetItemsByID( SteamInventoryResult_t *pResultHandle, STEAM_ARRAY_COUNT( unC PRINT_DEBUG("GetItemsByID\n"); std::lock_guard lock(global_mutex); if (pResultHandle) { - struct Steam_Inventory_Requests *request = new_inventory_result(pInstanceIDs, unCountInstanceIDs); - { - struct SteamInventoryResultReady_t data; - data.m_handle = request->inventory_result; - data.m_result = k_EResultOK; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), request->timeout); - } - + struct Steam_Inventory_Requests *request = new_inventory_result(false, pInstanceIDs, unCountInstanceIDs); *pResultHandle = request->inventory_result; return true; } @@ -393,14 +378,7 @@ bool DeserializeResult( SteamInventoryResult_t *pOutResultHandle, STEAM_BUFFER_C std::lock_guard lock(global_mutex); //TODO if (pOutResultHandle) { - struct Steam_Inventory_Requests *request = new_inventory_result(); - { - struct SteamInventoryResultReady_t data; - data.m_handle = request->inventory_result; - data.m_result = k_EResultOK; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data), request->timeout); - } - + struct Steam_Inventory_Requests *request = new_inventory_result(false); *pOutResultHandle = request->inventory_result; return true; } @@ -551,32 +529,12 @@ STEAM_METHOD_DESC(LoadItemDefinitions triggers the automatic load and refresh of bool LoadItemDefinitions() { PRINT_DEBUG("LoadItemDefinitions\n"); - - if (need_load_definitions) - { - if (!items_loaded) - { - SteamInventoryResultReady_t data; - data.m_result = k_EResultPending; - data.m_handle = new_inventory_result()->inventory_result; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); - } - else - { - need_load_definitions = false; - { - SteamInventoryDefinitionUpdate_t data = {}; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); - } - { - SteamInventoryResultReady_t data = {}; - data.m_result = k_EResultOK; - data.m_handle = new_inventory_result()->inventory_result; - callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); - } - } + if (!definition_update_called) { + call_definition_update = true; } + //real steam launches a SteamInventoryResultReady_t which is why I create a new inventory result + new_inventory_result(false); return true; } @@ -816,5 +774,53 @@ bool SubmitUpdateProperties( SteamInventoryUpdateHandle_t handle, SteamInventory { PRINT_DEBUG("SubmitUpdateProperties\n"); } - -}; \ No newline at end of file + +void RunCallbacks() +{ + if (call_definition_update || inventory_requests.size()) { + std::call_once(load_items_flag, [&]() { + std::thread items_load_thread(read_items_db, items_db_file, &items, &items_loaded); + items_load_thread.detach(); + }); + } + + if (items_loaded) { + if (call_definition_update) { + //call this callback even when 0 items? + SteamInventoryDefinitionUpdate_t data = {}; + callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); + call_definition_update = false; + definition_update_called = true; + } + + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + + for (auto & r : inventory_requests) { + if (!r.done && std::chrono::duration_cast>(now - r.time_created).count() > r.timeout) { + if (r.full_query) { + if (!full_update_called) { + // SteamInventoryFullUpdate_t callbacks are triggered when GetAllItems + // successfully returns a result which is newer / fresher than the last + // known result. + //TODO: should this always be returned for each get all item calls? + struct SteamInventoryFullUpdate_t data; + data.m_handle = r.inventory_result; + callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); + full_update_called = true; + } + } + + { + struct SteamInventoryResultReady_t data; + data.m_handle = r.inventory_result; + data.m_result = k_EResultOK; + callbacks->addCBResult(data.k_iCallback, &data, sizeof(data)); + } + + r.done = true; + } + } + } +} + +}; diff --git a/json/json.hpp b/json/json.hpp index e0a2645..5003a4f 100644 --- a/json/json.hpp +++ b/json/json.hpp @@ -83,369 +83,369 @@ SOFTWARE. namespace nlohmann { - namespace detail +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const { - /// struct to capture the start position of the current token - struct position_t - { - /// the total number of characters read - std::size_t chars_read_total = 0; - /// the number of characters read in the current line - std::size_t chars_read_current_line = 0; - /// the number of lines read - std::size_t lines_read = 0; + return chars_read_total; + } +}; - /// conversion to size_t to preserve SAX interface - constexpr operator size_t() const - { - return chars_read_total; - } - }; - - } // namespace detail +} // namespace detail } // namespace nlohmann namespace nlohmann { - namespace detail +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/*! +@brief general exception of the @ref basic_json class + +This class is an extension of `std::exception` objects with a member @a id for +exception ids. It is used as the base class for all exceptions thrown by the +@ref basic_json class. This class can hence be used as "wildcard" to catch +exceptions. + +Subclasses: +- @ref parse_error for exceptions indicating a parse error +- @ref invalid_iterator for exceptions indicating errors with iterators +- @ref type_error for exceptions indicating executing a member function with + a wrong type +- @ref out_of_range for exceptions indicating access out of the defined range +- @ref other_error for exceptions indicating other library errors + +@internal +@note To have nothrow-copy-constructible exceptions, we internally use + `std::runtime_error` which can cope with arbitrary-length error messages. + Intermediate strings are built with static functions and then passed to + the actual constructor. +@endinternal + +@liveexample{The following code shows how arbitrary library exceptions can be +caught.,exception} + +@since version 3.0.0 +*/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + const char* what() const noexcept override { - //////////////// - // exceptions // - //////////////// + return m.what(); + } - /*! - @brief general exception of the @ref basic_json class + /// the id of the exception + const int id; - This class is an extension of `std::exception` objects with a member @a id for - exception ids. It is used as the base class for all exceptions thrown by the - @ref basic_json class. This class can hence be used as "wildcard" to catch - exceptions. + protected: + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} - Subclasses: - - @ref parse_error for exceptions indicating a parse error - - @ref invalid_iterator for exceptions indicating errors with iterators - - @ref type_error for exceptions indicating executing a member function with - a wrong type - - @ref out_of_range for exceptions indicating access out of the defined range - - @ref other_error for exceptions indicating other library errors + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } - @internal - @note To have nothrow-copy-constructible exceptions, we internally use - `std::runtime_error` which can cope with arbitrary-length error messages. - Intermediate strings are built with static functions and then passed to - the actual constructor. - @endinternal + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; - @liveexample{The following code shows how arbitrary library exceptions can be - caught.,exception} +/*! +@brief exception indicating a parse error - @since version 3.0.0 - */ - class exception : public std::exception - { - public: - /// returns the explanatory string - const char* what() const noexcept override - { - return m.what(); - } +This exception is thrown by the library when a parse error occurs. Parse errors +can occur during the deserialization of JSON text, CBOR, MessagePack, as well +as when using JSON Patch. - /// the id of the exception - const int id; +Member @a byte holds the byte index of the last read character in the input +file. - protected: - exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} +Exceptions have ids 1xx. - static std::string name(const std::string& ename, int id_) - { - return "[json.exception." + ename + "." + std::to_string(id_) + "] "; - } +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. +json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. +json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. +json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. +json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. +json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. +json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. +json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. +json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. +json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. +json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. +json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). - private: - /// an exception object as storage for error messages - std::runtime_error m; - }; +@note For an input with n bytes, 1 is the index of the first character and n+1 + is the index of the terminating null byte or the end of file. This also + holds true when reading a byte vector (CBOR or MessagePack). - /*! - @brief exception indicating a parse error +@liveexample{The following code shows how a `parse_error` exception can be +caught.,parse_error} - This exception is thrown by the library when a parse error occurs. Parse errors - can occur during the deserialization of JSON text, CBOR, MessagePack, as well - as when using JSON Patch. +@sa - @ref exception for the base class of the library exceptions +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors - Member @a byte holds the byte index of the last read character in the input - file. +@since version 3.0.0 +*/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + static parse_error create(int id_, const position_t& pos, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + what_arg; + return parse_error(id_, pos.chars_read_total, w.c_str()); + } - Exceptions have ids 1xx. + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + what_arg; + return parse_error(id_, byte_, w.c_str()); + } - name / id | example message | description - ------------------------------ | --------------- | ------------------------- - json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. - json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. - json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. - json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. - json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. - json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. - json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. - json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. - json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. - json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. - json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. - json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. - json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). + /*! + @brief byte index of the parse error - @note For an input with n bytes, 1 is the index of the first character and n+1 - is the index of the terminating null byte or the end of file. This also - holds true when reading a byte vector (CBOR or MessagePack). + The byte index of the last read character in the input file. - @liveexample{The following code shows how a `parse_error` exception can be - caught.,parse_error} + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; - @sa - @ref exception for the base class of the library exceptions - @sa - @ref invalid_iterator for exceptions indicating errors with iterators - @sa - @ref type_error for exceptions indicating executing a member function with - a wrong type - @sa - @ref out_of_range for exceptions indicating access out of the defined range - @sa - @ref other_error for exceptions indicating other library errors + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} - @since version 3.0.0 - */ - class parse_error : public exception - { - public: - /*! - @brief create a parse error exception - @param[in] id_ the id of the exception - @param[in] pos the position where the error occurred (or with - chars_read_total=0 if the position cannot be - determined) - @param[in] what_arg the explanatory string - @return parse_error object - */ - static parse_error create(int id_, const position_t& pos, const std::string& what_arg) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - position_string(pos) + ": " + what_arg; - return parse_error(id_, pos.chars_read_total, w.c_str()); - } + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; - static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + - ": " + what_arg; - return parse_error(id_, byte_, w.c_str()); - } +/*! +@brief exception indicating errors with iterators - /*! - @brief byte index of the parse error +This exception is thrown if iterators passed to a library function do not match +the expected semantics. - The byte index of the last read character in the input file. +Exceptions have ids 2xx. - @note For an input with n bytes, 1 is the index of the first character and - n+1 is the index of the terminating null byte or the end of file. - This also holds true when reading a byte vector (CBOR or MessagePack). - */ - const std::size_t byte; +name / id | example message | description +----------------------------------- | --------------- | ------------------------- +json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. +json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. +json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. +json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. +json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. +json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. +json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. +json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. +json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. +json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). - private: - parse_error(int id_, std::size_t byte_, const char* what_arg) - : exception(id_, what_arg), byte(byte_) {} +@liveexample{The following code shows how an `invalid_iterator` exception can be +caught.,invalid_iterator} - static std::string position_string(const position_t& pos) - { - return " at line " + std::to_string(pos.lines_read + 1) + - ", column " + std::to_string(pos.chars_read_current_line); - } - }; +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors - /*! - @brief exception indicating errors with iterators +@since version 3.0.0 +*/ +class invalid_iterator : public exception +{ + public: + static invalid_iterator create(int id_, const std::string& what_arg) + { + std::string w = exception::name("invalid_iterator", id_) + what_arg; + return invalid_iterator(id_, w.c_str()); + } - This exception is thrown if iterators passed to a library function do not match - the expected semantics. + private: + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; - Exceptions have ids 2xx. +/*! +@brief exception indicating executing a member function with a wrong type - name / id | example message | description - ----------------------------------- | --------------- | ------------------------- - json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. - json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. - json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. - json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. - json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. - json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. - json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. - json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. - json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. - json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. - json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. - json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. - json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. - json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). +This exception is thrown in case of a type error; that is, a library function is +executed on a JSON value whose type does not match the expected semantics. - @liveexample{The following code shows how an `invalid_iterator` exception can be - caught.,invalid_iterator} +Exceptions have ids 3xx. - @sa - @ref exception for the base class of the library exceptions - @sa - @ref parse_error for exceptions indicating a parse error - @sa - @ref type_error for exceptions indicating executing a member function with - a wrong type - @sa - @ref out_of_range for exceptions indicating access out of the defined range - @sa - @ref other_error for exceptions indicating other library errors +name / id | example message | description +----------------------------- | --------------- | ------------------------- +json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. +json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. +json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. +json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. +json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. +json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. +json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. +json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. +json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. +json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. +json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. +json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. +json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. +json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. +json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. +json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | +json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | - @since version 3.0.0 - */ - class invalid_iterator : public exception - { - public: - static invalid_iterator create(int id_, const std::string& what_arg) - { - std::string w = exception::name("invalid_iterator", id_) + what_arg; - return invalid_iterator(id_, w.c_str()); - } +@liveexample{The following code shows how a `type_error` exception can be +caught.,type_error} - private: - invalid_iterator(int id_, const char* what_arg) - : exception(id_, what_arg) {} - }; +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors - /*! - @brief exception indicating executing a member function with a wrong type +@since version 3.0.0 +*/ +class type_error : public exception +{ + public: + static type_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("type_error", id_) + what_arg; + return type_error(id_, w.c_str()); + } - This exception is thrown in case of a type error; that is, a library function is - executed on a JSON value whose type does not match the expected semantics. + private: + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; - Exceptions have ids 3xx. +/*! +@brief exception indicating access out of the defined range - name / id | example message | description - ----------------------------- | --------------- | ------------------------- - json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. - json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. - json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. - json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. - json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. - json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. - json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. - json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. - json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. - json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. - json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. - json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. - json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. - json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. - json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. - json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | - json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | +This exception is thrown in case a library function is called on an input +parameter that exceeds the expected range, for instance in case of array +indices or nonexisting object keys. - @liveexample{The following code shows how a `type_error` exception can be - caught.,type_error} +Exceptions have ids 4xx. - @sa - @ref exception for the base class of the library exceptions - @sa - @ref parse_error for exceptions indicating a parse error - @sa - @ref invalid_iterator for exceptions indicating errors with iterators - @sa - @ref out_of_range for exceptions indicating access out of the defined range - @sa - @ref other_error for exceptions indicating other library errors +name / id | example message | description +------------------------------- | --------------- | ------------------------- +json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. +json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. +json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. +json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. +json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. +json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. +json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | +json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | +json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | - @since version 3.0.0 - */ - class type_error : public exception - { - public: - static type_error create(int id_, const std::string& what_arg) - { - std::string w = exception::name("type_error", id_) + what_arg; - return type_error(id_, w.c_str()); - } +@liveexample{The following code shows how an `out_of_range` exception can be +caught.,out_of_range} - private: - type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} - }; +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref other_error for exceptions indicating other library errors - /*! - @brief exception indicating access out of the defined range +@since version 3.0.0 +*/ +class out_of_range : public exception +{ + public: + static out_of_range create(int id_, const std::string& what_arg) + { + std::string w = exception::name("out_of_range", id_) + what_arg; + return out_of_range(id_, w.c_str()); + } - This exception is thrown in case a library function is called on an input - parameter that exceeds the expected range, for instance in case of array - indices or nonexisting object keys. + private: + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; - Exceptions have ids 4xx. +/*! +@brief exception indicating other library errors - name / id | example message | description - ------------------------------- | --------------- | ------------------------- - json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. - json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. - json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. - json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. - json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. - json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. - json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | - json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | - json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | +This exception is thrown in case of errors that cannot be classified with the +other exception types. - @liveexample{The following code shows how an `out_of_range` exception can be - caught.,out_of_range} +Exceptions have ids 5xx. - @sa - @ref exception for the base class of the library exceptions - @sa - @ref parse_error for exceptions indicating a parse error - @sa - @ref invalid_iterator for exceptions indicating errors with iterators - @sa - @ref type_error for exceptions indicating executing a member function with - a wrong type - @sa - @ref other_error for exceptions indicating other library errors +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. - @since version 3.0.0 - */ - class out_of_range : public exception - { - public: - static out_of_range create(int id_, const std::string& what_arg) - { - std::string w = exception::name("out_of_range", id_) + what_arg; - return out_of_range(id_, w.c_str()); - } +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range - private: - out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} - }; +@liveexample{The following code shows how an `other_error` exception can be +caught.,other_error} - /*! - @brief exception indicating other library errors +@since version 3.0.0 +*/ +class other_error : public exception +{ + public: + static other_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("other_error", id_) + what_arg; + return other_error(id_, w.c_str()); + } - This exception is thrown in case of errors that cannot be classified with the - other exception types. - - Exceptions have ids 5xx. - - name / id | example message | description - ------------------------------ | --------------- | ------------------------- - json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. - - @sa - @ref exception for the base class of the library exceptions - @sa - @ref parse_error for exceptions indicating a parse error - @sa - @ref invalid_iterator for exceptions indicating errors with iterators - @sa - @ref type_error for exceptions indicating executing a member function with - a wrong type - @sa - @ref out_of_range for exceptions indicating access out of the defined range - - @liveexample{The following code shows how an `other_error` exception can be - caught.,other_error} - - @since version 3.0.0 - */ - class other_error : public exception - { - public: - static other_error create(int id_, const std::string& what_arg) - { - std::string w = exception::name("other_error", id_) + what_arg; - return other_error(id_, w.c_str()); - } - - private: - other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} - }; - } // namespace detail + private: + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; +} // namespace detail } // namespace nlohmann // #include @@ -458,104 +458,100 @@ namespace nlohmann // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) -#if defined(__clang__) -#if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 -#error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" -#endif -#elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) -#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 -#error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" -#endif -#endif -#endif - -// C++ language standard detection -#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 -#define JSON_HAS_CPP_17 -#define JSON_HAS_CPP_14 -#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) -#define JSON_HAS_CPP_14 + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdocumentation" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow for portable deprecation warnings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) -#define JSON_DEPRECATED __attribute__((deprecated)) + #define JSON_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) -#define JSON_DEPRECATED __declspec(deprecated) + #define JSON_DEPRECATED __declspec(deprecated) #else -#define JSON_DEPRECATED + #define JSON_DEPRECATED #endif // allow for portable nodiscard warnings #if defined(__has_cpp_attribute) -#if __has_cpp_attribute(nodiscard) -#if defined(__clang__) && !defined(JSON_HAS_CPP_17) // issue #1535 -#define JSON_NODISCARD + #if __has_cpp_attribute(nodiscard) + #define JSON_NODISCARD [[nodiscard]] + #elif __has_cpp_attribute(gnu::warn_unused_result) + #define JSON_NODISCARD [[gnu::warn_unused_result]] + #else + #define JSON_NODISCARD + #endif #else -#define JSON_NODISCARD [[nodiscard]] -#endif -#elif __has_cpp_attribute(gnu::warn_unused_result) -#define JSON_NODISCARD [[gnu::warn_unused_result]] -#else -#define JSON_NODISCARD -#endif -#else -#define JSON_NODISCARD + #define JSON_NODISCARD #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) -#define JSON_THROW(exception) throw exception -#define JSON_TRY try -#define JSON_CATCH(exception) catch(exception) -#define JSON_INTERNAL_CATCH(exception) catch(exception) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) #else -#include -#define JSON_THROW(exception) std::abort() -#define JSON_TRY if(true) -#define JSON_CATCH(exception) if(false) -#define JSON_INTERNAL_CATCH(exception) if(false) + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) -#undef JSON_THROW -#define JSON_THROW JSON_THROW_USER + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) -#undef JSON_TRY -#define JSON_TRY JSON_TRY_USER + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) -#undef JSON_CATCH -#define JSON_CATCH JSON_CATCH_USER -#undef JSON_INTERNAL_CATCH -#define JSON_INTERNAL_CATCH JSON_CATCH_USER + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) -#undef JSON_INTERNAL_CATCH -#define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // manual branch prediction #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) -#define JSON_LIKELY(x) __builtin_expect(x, 1) -#define JSON_UNLIKELY(x) __builtin_expect(x, 0) + #define JSON_LIKELY(x) __builtin_expect(x, 1) + #define JSON_UNLIKELY(x) __builtin_expect(x, 0) #else -#define JSON_LIKELY(x) x -#define JSON_UNLIKELY(x) x + #define JSON_LIKELY(x) x + #define JSON_UNLIKELY(x) x +#endif + +// C++ language standard detection +#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 +#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 #endif /*! @@ -614,60 +610,60 @@ namespace nlohmann namespace nlohmann { - namespace detail +namespace detail +{ +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +template +using uncvref_t = typename std::remove_cv::type>::type; + +// implementation of C++14 index_sequence and affiliates +// source: https://stackoverflow.com/a/32223343 +template +struct index_sequence +{ + using type = index_sequence; + using value_type = std::size_t; + static constexpr std::size_t size() noexcept { - // alias templates to reduce boilerplate - template - using enable_if_t = typename std::enable_if::type; + return sizeof...(Ints); + } +}; - template - using uncvref_t = typename std::remove_cv::type>::type; +template +struct merge_and_renumber; - // implementation of C++14 index_sequence and affiliates - // source: https://stackoverflow.com/a/32223343 - template - struct index_sequence - { - using type = index_sequence; - using value_type = std::size_t; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } - }; +template +struct merge_and_renumber, index_sequence> + : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; - template - struct merge_and_renumber; +template +struct make_index_sequence + : merge_and_renumber < typename make_index_sequence < N / 2 >::type, + typename make_index_sequence < N - N / 2 >::type > {}; - template - struct merge_and_renumber, index_sequence> - : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; +template<> struct make_index_sequence<0> : index_sequence<> {}; +template<> struct make_index_sequence<1> : index_sequence<0> {}; - template - struct make_index_sequence - : merge_and_renumber < typename make_index_sequence < N / 2 >::type, - typename make_index_sequence < N - N / 2 >::type > {}; +template +using index_sequence_for = make_index_sequence; - template<> struct make_index_sequence<0> : index_sequence<> {}; - template<> struct make_index_sequence<1> : index_sequence<0> {}; +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; - template - using index_sequence_for = make_index_sequence; +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; - // dispatch utility (taken from ranges-v3) - template struct priority_tag : priority_tag < N - 1 > {}; - template<> struct priority_tag<0> {}; - - // taken from ranges-v3 - template - struct static_const - { - static constexpr T value{}; - }; - - template - constexpr T static_const::value; - } // namespace detail +template +constexpr T static_const::value; +} // namespace detail } // namespace nlohmann // #include @@ -688,14 +684,14 @@ namespace nlohmann namespace nlohmann { - namespace detail - { - template struct make_void - { - using type = void; - }; - template using void_t = typename make_void::type; - } // namespace detail +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail } // namespace nlohmann // #include @@ -703,47 +699,47 @@ namespace nlohmann namespace nlohmann { - namespace detail - { - template - struct iterator_types {}; +namespace detail +{ +template +struct iterator_types {}; - template - struct iterator_types < - It, - void_t> - { - using difference_type = typename It::difference_type; - using value_type = typename It::value_type; - using pointer = typename It::pointer; - using reference = typename It::reference; - using iterator_category = typename It::iterator_category; - }; +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; - // This is required as some compilers implement std::iterator_traits in a way that - // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. - template - struct iterator_traits - { - }; +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; - template - struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> : iterator_types - { - }; +{ +}; - template - struct iterator_traits::value>> - { - using iterator_category = std::random_access_iterator_tag; - using value_type = T; - using difference_type = ptrdiff_t; - using pointer = T *; - using reference = T &; - }; - } // namespace detail +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail } // namespace nlohmann // #include @@ -761,54 +757,54 @@ namespace nlohmann // http://en.cppreference.com/w/cpp/experimental/is_detected namespace nlohmann { - namespace detail - { - struct nonesuch - { - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; - }; +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; - template class Op, - class... Args> - struct detector - { - using value_t = std::false_type; - using type = Default; - }; +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; - template class Op, class... Args> - struct detector>, Op, Args...> - { - using value_t = std::true_type; - using type = Op; - }; +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; - template