diff --git a/App.cpp b/App.cpp index 1a0a567..134d6ad 100644 --- a/App.cpp +++ b/App.cpp @@ -3,7 +3,6 @@ * All rights reserved. Distributed under the terms of the MIT license. */ - #include "App.h" #include "MainWindow.h" @@ -13,42 +12,29 @@ #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Application" -const char* kApplicationSignature = "application/x-vnd.SLema-DumBer"; +const char *kApplicationSignature = "application/x-vnd.SLema-DumBer"; - -App::App() - : - BApplication(kApplicationSignature) -{ - MainWindow* mainWindow = new MainWindow(); - mainWindow->Show(); +App::App() : BApplication(kApplicationSignature) { + MainWindow *mainWindow = new MainWindow(); + mainWindow->Show(); } +App::~App() {} -App::~App() -{ +void App::AboutRequested() { + BAboutWindow *about = new BAboutWindow(B_TRANSLATE_SYSTEM_NAME("DumBer"), + kApplicationSignature); + about->AddDescription(B_TRANSLATE("about_body")); + about->AddCopyright(2024, "Santiago Lema"); + about->AddText("e-mail me at haiku@lema.org"); + about->AddText("or ping me on the fediverse on @santi@go.lema.org"); + + about->Show(); } - -void -App::AboutRequested() -{ - BAboutWindow* about - = new BAboutWindow(B_TRANSLATE_SYSTEM_NAME("DumBer"), kApplicationSignature); - about->AddDescription(B_TRANSLATE("about_body")); - about->AddCopyright(2024, "Santiago Lema"); - about->AddText("e-mail me at haiku@lema.org"); - about->AddText("or ping me on the fediverse on @santi@go.lema.org"); - - about->Show(); -} - - -int -main() -{ - App* app = new App(); - app->Run(); - delete app; - return 0; +int main() { + App *app = new App(); + app->Run(); + delete app; + return 0; } diff --git a/BUILD.bazel b/BUILD.bazel new file mode 100644 index 0000000..d289e98 --- /dev/null +++ b/BUILD.bazel @@ -0,0 +1,54 @@ +cc_library( + name = "json", + hdrs = [ + "include/nlohmann/adl_serializer.hpp", + "include/nlohmann/byte_container_with_subtype.hpp", + "include/nlohmann/detail/abi_macros.hpp", + "include/nlohmann/detail/conversions/from_json.hpp", + "include/nlohmann/detail/conversions/to_chars.hpp", + "include/nlohmann/detail/conversions/to_json.hpp", + "include/nlohmann/detail/exceptions.hpp", + "include/nlohmann/detail/hash.hpp", + "include/nlohmann/detail/input/binary_reader.hpp", + "include/nlohmann/detail/input/input_adapters.hpp", + "include/nlohmann/detail/input/json_sax.hpp", + "include/nlohmann/detail/input/lexer.hpp", + "include/nlohmann/detail/input/parser.hpp", + "include/nlohmann/detail/input/position_t.hpp", + "include/nlohmann/detail/iterators/internal_iterator.hpp", + "include/nlohmann/detail/iterators/iter_impl.hpp", + "include/nlohmann/detail/iterators/iteration_proxy.hpp", + "include/nlohmann/detail/iterators/iterator_traits.hpp", + "include/nlohmann/detail/iterators/json_reverse_iterator.hpp", + "include/nlohmann/detail/iterators/primitive_iterator.hpp", + "include/nlohmann/detail/json_custom_base_class.hpp", + "include/nlohmann/detail/json_pointer.hpp", + "include/nlohmann/detail/json_ref.hpp", + "include/nlohmann/detail/macro_scope.hpp", + "include/nlohmann/detail/macro_unscope.hpp", + "include/nlohmann/detail/meta/call_std/begin.hpp", + "include/nlohmann/detail/meta/call_std/end.hpp", + "include/nlohmann/detail/meta/cpp_future.hpp", + "include/nlohmann/detail/meta/detected.hpp", + "include/nlohmann/detail/meta/identity_tag.hpp", + "include/nlohmann/detail/meta/is_sax.hpp", + "include/nlohmann/detail/meta/std_fs.hpp", + "include/nlohmann/detail/meta/type_traits.hpp", + "include/nlohmann/detail/meta/void_t.hpp", + "include/nlohmann/detail/output/binary_writer.hpp", + "include/nlohmann/detail/output/output_adapters.hpp", + "include/nlohmann/detail/output/serializer.hpp", + "include/nlohmann/detail/string_concat.hpp", + "include/nlohmann/detail/string_escape.hpp", + "include/nlohmann/detail/string_utils.hpp", + "include/nlohmann/detail/value_t.hpp", + "include/nlohmann/json.hpp", + "include/nlohmann/json_fwd.hpp", + "include/nlohmann/ordered_map.hpp", + "include/nlohmann/thirdparty/hedley/hedley.hpp", + "include/nlohmann/thirdparty/hedley/hedley_undef.hpp", + ], + includes = ["include"], + visibility = ["//visibility:public"], + alwayslink = True, +) diff --git a/DumBer b/DumBer index 622ebd3..aecf04a 100755 Binary files a/DumBer and b/DumBer differ diff --git a/LICENSE.MIT b/LICENSE.MIT new file mode 100644 index 0000000..a1dacc8 --- /dev/null +++ b/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2025 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MainWindow.cpp b/MainWindow.cpp index 3b91d83..0029971 100644 --- a/MainWindow.cpp +++ b/MainWindow.cpp @@ -15,27 +15,25 @@ #include #include #include +#include #include #include -#include #include #include -#include -#include #include +#include +#include #include + #include - -#include - -#include "json.hpp" - -// #include - +#include #include +#include "include/json.hpp" + +using json = nlohmann::json; using namespace BPrivate::Network; #undef B_TRANSLATION_CONTEXT @@ -59,7 +57,6 @@ MainWindow::MainWindow() _inputField = new BTextControl("", "What is the matrix ?", new BMessage(kQuestionChanged)); - _progress = new BStatusBar("prog"); _progress->SetMaxValue(100); _progress->SetTo(0); @@ -87,9 +84,8 @@ MainWindow::MainWindow() _inputField->SetExplicitMinSize(BSize(B_SIZE_UNSET, askH)); _inputField->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, askH * 6)); - - _apiKey = ReadOpenAIKey(); - printf("key is: %s", _apiKey.String()); + _apiKey = ReadOpenAIKey(); + printf("key is: %s", _apiKey.String()); BButton *sendButton = new BButton("send", B_TRANSLATE("Send"), new BMessage(kSendPrompt), @@ -99,9 +95,10 @@ MainWindow::MainWindow() _answerView->MakeEditable(false); // Disable editing _answerView->MakeSelectable(true); // Enable text selection _answerView->SetWordWrap(true); - + BScrollView *scrollView = - new BScrollView("scroll_view", _answerView, B_FOLLOW_ALL | B_WILL_DRAW ,0 , false, true); // horizontal and vertical scrollbars + new BScrollView("scroll_view", _answerView, B_FOLLOW_ALL | B_WILL_DRAW, 0, + false, true); // horizontal and vertical scrollbars BLayoutBuilder::Group<>(this, B_VERTICAL, 0) @@ -198,7 +195,16 @@ void MainWindow::MessageReceived(BMessage *message) { // that the request is done. BHttpBody body = _lastResult->Body(); if (body.text.has_value()) - _answerView->SetText(body.text.value()); + { + + json parsed = json::parse(body.text.value().String()); + + std::string content = parsed["choices"][0]["message"]["content"]; + _answerView->SetText(content.c_str()); + + // _answerView->SetText(body.text.value()); + + } else _answerView->SetText("nuthin'"); } @@ -263,56 +269,31 @@ void MainWindow::sendQuery() { BHttpRequest request = BHttpRequest(url); request.SetMethod(BHttpMethod::Post); - // if the API key file contains a new line bhttpfields will crash with invalid content - // .end() requires include algorithm + // if the API key file contains a new line bhttpfields will crash with invalid + // content .end() requires include algorithm std::string key = _apiKey.String(); key.erase(std::remove(key.begin(), key.end(), '\n'), key.end()); key.erase(std::remove(key.begin(), key.end(), '\r'), key.end()); - - std::string bearer = std::string("Bearer ")+std::string(key); + + std::string bearer = std::string("Bearer ") + std::string(key); BHttpFields fields = BHttpFields(); - fields.AddField("Authorization", bearer ); -// fields.AddField("Content-Type", "application/json"); //NO, this will crash, we set it in request + fields.AddField("Authorization", bearer); + // fields.AddField("Content-Type", "application/json"); //NO, this will + // crash, we set it in request request.SetFields(fields); + json bodyJson = { + {"model", "gpt-3.5-turbo"}, + {"messages", {{{"role", "user"}, {"content", _inputField->Text()}}}}}; -nlohmann::json bodyJson = { - { "model", "gpt-3.5-turbo" }, - { "messages", { - { - { "role", "user" }, - { "content", "What is the capital of France?" } - } - }} -}; - - -std::string body = bodyJson.dump(); - -BString mime = BString("application/json"); -//request.SetRequestBody(body.c_str(),mime); - - -// 2. Wrap it in BMemoryIO -auto memoryIO = std::make_unique( - body.c_str(), // pointer to data - body.size() // size of data -); - -// 3. Set the request body with mime type -request.SetRequestBody(std::move(memoryIO), "application/json", body.size()); - -//curl https://api.openai.com/v1/chat/completions \ - // -H "Authorization: Bearer YOUR_API_KEY" \ - // -H "Content-Type: application/json" \ - // -d '{ - // "model": "gpt-3.5-turbo", - // "messages": [{"role": "user", "content": "What is the capital of France?"}] - // }' - + std::string body = bodyJson.dump(); + BString mime = BString("application/json"); + // request.SetRequestBody(body.c_str(),mime); + auto memoryIO = std::make_unique(body.c_str(), body.size()); + request.SetRequestBody(std::move(memoryIO), "application/json", body.size()); printf("Sending Prompt to server: %s\n", url.UrlString().String()); _lastResult = _sharedSession.Execute(std::move(request), nullptr, this); @@ -360,33 +341,32 @@ BMenuBar *MainWindow::_BuildMenu() { } - BString MainWindow::ReadOpenAIKey() { - // /boot/home/config/openai_key - // or ~/.config/openai_key on linux - - BPath configPath; - if (find_directory(B_USER_SETTINGS_DIRECTORY, &configPath) != B_OK) - return "error: couldn't find config directory"; + // /boot/home/config/openai_key + // or ~/.config/openai_key on linux - configPath.Append("openai_key"); + BPath configPath; + if (find_directory(B_USER_SETTINGS_DIRECTORY, &configPath) != B_OK) + return "error: couldn't find config directory"; - BFile file(configPath.Path(), B_READ_ONLY); - - printf("full path:%s\n",configPath.Path()); - if (file.InitCheck() != B_OK) - return "error: couldn't open key file "; + configPath.Append("openai_key"); - off_t size; - file.GetSize(&size); - - char* buffer = new char[size + 1]; - file.Read(buffer, size); - buffer[size] = '\0'; // null-terminate + BFile file(configPath.Path(), B_READ_ONLY); - BString result(buffer); - delete[] buffer; + printf("full path:%s\n", configPath.Path()); + if (file.InitCheck() != B_OK) + return "error: couldn't open key file "; - return result; + off_t size; + file.GetSize(&size); + + char *buffer = new char[size + 1]; + file.Read(buffer, size); + buffer[size] = '\0'; // null-terminate + + BString result(buffer); + delete[] buffer; + + return result; } diff --git a/Makefile b/Makefile index 72da370..0f51cdf 100644 --- a/Makefile +++ b/Makefile @@ -71,7 +71,7 @@ LIBPATHS = # "#include
". Directories that contain the files in SRCS are # NOT auto-included here. #SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/netservices2) -SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/netservices2) +SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/netservices2) ./include # Additional paths paths to look for local headers. These use the form # #include "header". Directories that contain the files in SRCS are diff --git a/json.hpp b/include/json.hpp similarity index 98% rename from json.hpp rename to include/json.hpp index 31590ff..82d69f7 100644 --- a/json.hpp +++ b/include/json.hpp @@ -173,6 +173,9 @@ #include // forward_list #include // inserter, front_inserter, end #include // map +#ifdef JSON_HAS_CPP_17 + #include // optional +#endif #include // string #include // tuple, make_tuple #include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible @@ -2394,7 +2397,7 @@ JSON_HEDLEY_DIAGNOSTIC_POP #endif // C++ language standard detection -// if the user manually specified the used C++ version, this is skipped +// if the user manually specified the used c++ version this is skipped #if !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) #if (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) #define JSON_HAS_CPP_23 @@ -2491,7 +2494,7 @@ JSON_HEDLEY_DIAGNOSTIC_POP #endif #ifndef JSON_HAS_RANGES - // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has a syntax error + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 #define JSON_HAS_RANGES 0 #elif defined(__cpp_lib_ranges) @@ -2568,7 +2571,7 @@ JSON_HEDLEY_DIAGNOSTIC_POP #define JSON_ASSERT(x) assert(x) #endif -// allow accessing some private functions (needed by the test suite) +// allow to access some private functions (needed by the test suite) #if defined(JSON_TESTS_PRIVATE) #define JSON_PRIVATE_UNLESS_TESTED public #else @@ -3096,10 +3099,10 @@ inline void replace_substring(StringType& s, const StringType& f, const StringType& t) { JSON_ASSERT(!f.empty()); - for (auto pos = s.find(f); // find the first occurrence of f + for (auto pos = s.find(f); // find first occurrence of f pos != StringType::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and - pos = s.find(f, pos + t.size())) // find the next occurrence of f + pos = s.find(f, pos + t.size())) // find next occurrence of f {} } @@ -3126,7 +3129,7 @@ inline StringType escape(StringType s) * Note the order of escaping "~1" to "/" and "~0" to "~" is important. */ template -inline void unescape(StringType& s) +static void unescape(StringType& s) { replace_substring(s, StringType{"~1"}, StringType{"/"}); replace_substring(s, StringType{"~0"}, StringType{"~"}); @@ -3367,9 +3370,7 @@ NLOHMANN_JSON_NAMESPACE_END #include // tuple #include // false_type, is_constructible, is_integral, is_same, true_type #include // declval -#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L - #include // byte -#endif + // #include // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ @@ -3579,12 +3580,12 @@ namespace detail // Note to maintainers: // -// Every trait in this file expects a non-CV-qualified type. +// Every trait in this file expects a non CV-qualified type. // The only exceptions are in the 'aliases for detected' section -// (i.e., those of the form: decltype(T::member_function(std::declval()))) +// (i.e. those of the form: decltype(T::member_function(std::declval()))) // // In this case, T has to be properly CV-qualified to constraint the function arguments -// (e.g., to_json(BasicJsonType&, const T&)) +// (e.g. to_json(BasicJsonType&, const T&)) template struct is_basic_json : std::false_type {}; @@ -3592,7 +3593,7 @@ NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json : std::true_type {}; // used by exceptions create() member functions -// true_type for the pointer to possibly cv-qualified basic_json or std::nullptr_t +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t // false_type otherwise template struct is_basic_json_context : @@ -3778,30 +3779,6 @@ struct char_traits : std::char_traits } }; -#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L -template<> -struct char_traits : std::char_traits -{ - using char_type = std::byte; - using int_type = uint64_t; - - static int_type to_int_type(char_type c) noexcept - { - return static_cast(std::to_integer(c)); - } - - static char_type to_char_type(int_type i) noexcept - { - return std::byte(static_cast(i)); - } - - static constexpr int_type eof() noexcept - { - return static_cast(std::char_traits::eof()); - } -}; -#endif - /////////////////// // is_ functions // /////////////////// @@ -3818,7 +3795,7 @@ template struct negation : std::integral_constant < bool, !B::value > { // Reimplementation of is_constructible and is_default_constructible, due to them being broken for // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). -// This causes compile errors in e.g., Clang 3.5 or GCC 4.9. +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. template struct is_default_constructible : std::is_default_constructible {}; @@ -3898,7 +3875,7 @@ using range_value_t = value_type_t>>; // The following implementation of is_complete_type is taken from // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ -// and is written by Xiang Fan who agreed to use it in this library. +// and is written by Xiang Fan who agreed to using it in this library. template struct is_complete_type : std::false_type {}; @@ -4135,7 +4112,7 @@ decltype(std::declval()(std::declval(), std::declval())) template using detect_is_transparent = typename T::is_transparent; -// type trait to check if KeyType can be used as an object key (without a BasicJsonType) +// type trait to check if KeyType can be used as object key (without a BasicJsonType) // see is_usable_as_basic_json_key_type below template> @@ -4149,7 +4126,7 @@ using is_usable_as_key_type = typename std::conditional < std::true_type, std::false_type >::type; -// type trait to check if KeyType can be used as an object key +// type trait to check if KeyType can be used as object key // true if: // - KeyType is comparable with BasicJsonType::object_t::key_type // - if ExcludeObjectKeyType is true, KeyType is not BasicJsonType::object_t::key_type @@ -4513,7 +4490,7 @@ NLOHMANN_JSON_NAMESPACE_END // emitted in every translation unit. This issue cannot be fixed with a // header-only library as there is no implementation file to move these // functions to. As a result, we suppress this warning here to avoid client -// code stumbling over this. See https://github.com/nlohmann/json/issues/4087 +// code to stumble over this. See https://github.com/nlohmann/json/issues/4087 // for a discussion. #if defined(__clang__) #pragma clang diagnostic push @@ -4840,15 +4817,6 @@ NLOHMANN_JSON_NAMESPACE_END // #include -// include after macro_scope.hpp -#ifdef JSON_HAS_CPP_17 - #include // optional -#endif - -#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM - #include // u8string_view -#endif - NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { @@ -4864,6 +4832,7 @@ inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n) } #ifdef JSON_HAS_CPP_17 +#ifndef JSON_USE_IMPLICIT_CONVERSIONS template void from_json(const BasicJsonType& j, std::optional& opt) { @@ -4876,6 +4845,8 @@ void from_json(const BasicJsonType& j, std::optional& opt) opt.emplace(j.template get()); } } + +#endif // JSON_USE_IMPLICIT_CONVERSIONS #endif // JSON_HAS_CPP_17 // overloads for basic_json template parameters @@ -5209,7 +5180,7 @@ inline void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) } // overload for arithmetic types, not chosen for basic_json template arguments -// (BooleanType, etc.); note: Is it really necessary to provide explicit +// (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template < typename BasicJsonType, typename ArithmeticType, @@ -5354,10 +5325,7 @@ inline void from_json(const BasicJsonType& j, std_fs::path& p) JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j)); } const auto& s = *j.template get_ptr(); - // Checking for C++20 standard or later can be insufficient in case the - // library support for char8_t is either incomplete or was disabled - // altogether. Use the __cpp_lib_char8_t feature test instead. -#if defined(__cpp_lib_char8_t) && (__cpp_lib_char8_t >= 201907L) +#ifdef JSON_HAS_CPP_20 p = std_fs::path(std::u8string_view(reinterpret_cast(s.data()), s.size())); #else p = std_fs::u8path(s); // accepts UTF-8 encoded std::string in C++17, deprecated in C++20 @@ -5412,8 +5380,7 @@ NLOHMANN_JSON_NAMESPACE_END #include // copy #include // begin, end -#include // allocator_traits -#include // basic_string, char_traits +#include // string #include // tuple, get #include // is_same, is_constructible, is_floating_point, is_enum, underlying_type #include // move, forward, declval, pair @@ -5947,7 +5914,7 @@ struct external_constructor #ifdef JSON_HAS_CPP_17 template::value, int> = 0> -void to_json(BasicJsonType& j, const std::optional& opt) noexcept +void to_json(BasicJsonType& j, const std::optional& opt) { if (opt.has_value()) { @@ -6120,21 +6087,15 @@ inline void to_json(BasicJsonType& j, const T& t) } #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM -#if defined(__cpp_lib_char8_t) -template -inline void to_json(BasicJsonType& j, const std::basic_string& s) -{ - using OtherAllocator = typename std::allocator_traits::template rebind_alloc; - j = std::basic_string, OtherAllocator>(s.begin(), s.end(), s.get_allocator()); -} -#endif - template inline void to_json(BasicJsonType& j, const std_fs::path& p) { - // Returns either a std::string or a std::u8string depending whether library - // support for char8_t is enabled. - j = p.u8string(); +#ifdef JSON_HAS_CPP_20 + const std::u8string s = p.u8string(); + j = std::string(s.begin(), s.end()); +#else + j = p.u8string(); // returns std::string in C++17 +#endif } #endif @@ -6595,7 +6556,7 @@ class input_stream_adapter : is(&i), sb(i.rdbuf()) {} - // deleted because of pointer members + // delete because of pointer members input_stream_adapter(const input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&&) = delete; @@ -6609,7 +6570,7 @@ class input_stream_adapter // std::istream/std::streambuf use std::char_traits::to_int_type, to // ensure that std::char_traits::eof() and the character 0xFF do not - // end up as the same value, e.g., 0xFFFFFFFF. + // end up as the same value, e.g. 0xFFFFFFFF. std::char_traits::int_type get_character() { auto res = sb->sbumpc(); @@ -6831,7 +6792,7 @@ class wide_string_input_adapter typename std::char_traits::int_type get_character() noexcept { - // check if the buffer needs to be filled + // check if buffer needs to be filled if (utf8_bytes_index == utf8_bytes_filled) { fill_buffer(); @@ -7188,7 +7149,7 @@ class lexer : public lexer_base , decimal_point_char(static_cast(get_decimal_point())) {} - // deleted because of pointer members + // delete because of pointer members lexer(const lexer&) = delete; lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) lexer& operator=(lexer&) = delete; @@ -7323,10 +7284,10 @@ class lexer : public lexer_base while (true) { - // get the next character + // get next character switch (get()) { - // end of file while parsing the string + // end of file while parsing string case char_traits::eof(): { error_message = "invalid string: missing closing quote"; @@ -7412,7 +7373,7 @@ class lexer : public lexer_base (static_cast(codepoint1) << 10u) // low surrogate occupies the least significant 15 bits + static_cast(codepoint2) - // there is still the 0xD800, 0xDC00, and 0x10000 noise + // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result, so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00u); @@ -7438,7 +7399,7 @@ class lexer : public lexer_base } } - // the result of the above calculation yields a proper codepoint + // result of the above calculation yields a proper codepoint JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); // translate codepoint into bytes @@ -7889,7 +7850,7 @@ class lexer : public lexer_base break; } - // the remaining bytes (80..C1 and F5..FF) are ill-formed + // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; @@ -8034,7 +7995,7 @@ class lexer : public lexer_base reset(); // the type of the parsed number; initially set to unsigned; will be - // changed if minus sign, decimal point, or exponent is read + // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number @@ -8406,7 +8367,7 @@ scan_number_done: if (next_unget) { - // only reset the next_unget variable and work with current + // just reset the next_unget variable and work with current next_unget = false; } else @@ -8585,7 +8546,7 @@ scan_number_done: return token_type::parse_error; } - // read the next character and ignore whitespace + // read next character and ignore whitespace skip_whitespace(); // ignore comments @@ -8949,7 +8910,7 @@ class json_sax_dom_parser JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(ref_stack.back()->is_object()); - // add null at the given key and store the reference for later + // add null at given key and store the reference for later object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val)); return true; } @@ -9265,11 +9226,11 @@ class json_sax_dom_callback_parser { BasicJsonType k = BasicJsonType(val); - // check callback for the key + // check callback for key const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); key_keep_stack.push_back(keep); - // add discarded value at the given key and store the reference for later + // add discarded value at given key and store the reference for later if (keep && ref_stack.back()) { object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val) = discarded); @@ -9868,7 +9829,7 @@ enum class cbor_tag_handler_t @note from https://stackoverflow.com/a/1001328/266378 */ -inline bool little_endianness(int num = 1) noexcept +static inline bool little_endianness(int num = 1) noexcept { return *reinterpret_cast(&num) == 1; } @@ -10149,7 +10110,7 @@ class binary_reader return get_number(input_format_t::bson, value) && sax->number_unsigned(value); } - default: // anything else is not supported (yet) + default: // anything else not supported (yet) { std::array cr{{}}; static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) @@ -10546,7 +10507,7 @@ class binary_reader case 0xD2: case 0xD3: case 0xD4: - case 0xD8: // tagged item (1 byte follows) + case 0xD8: // tagged item (1 bytes follow) case 0xD9: // tagged item (2 bytes follow) case 0xDA: // tagged item (4 bytes follow) case 0xDB: // tagged item (8 bytes follow) @@ -10598,7 +10559,7 @@ class binary_reader case cbor_tag_handler_t::store: { binary_t b; - // use binary subtype and store in a binary container + // use binary subtype and store in binary container switch (current) { case 0xD8: @@ -10667,7 +10628,7 @@ class binary_reader const auto byte1 = static_cast(byte1_raw); const auto byte2 = static_cast(byte2_raw); - // Code from RFC 7049, Appendix D, Figure 3: + // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very @@ -11974,7 +11935,7 @@ class binary_reader { break; } - if (is_ndarray) // ndarray dimensional vector can only contain integers and cannot embed another array + if (is_ndarray) // ndarray dimensional vector can only contain integers, and can not embed another array { return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, "ndarray dimensional vector is not allowed", "size"), nullptr)); } @@ -12007,16 +11968,8 @@ class binary_reader result = 1; for (auto i : dim) { - // Pre-multiplication overflow check: if i > 0 and result > SIZE_MAX/i, then result*i would overflow. - // This check must happen before multiplication since overflow detection after the fact is unreliable - // as modular arithmetic can produce any value, not just 0 or SIZE_MAX. - if (JSON_HEDLEY_UNLIKELY(i > 0 && result > (std::numeric_limits::max)() / i)) - { - return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, "excessive ndarray size caused overflow", "size"), nullptr)); - } result *= i; - // Additional post-multiplication check to catch any edge cases the pre-check might miss - if (result == 0 || result == npos) + if (result == 0 || result == npos) // because dim elements shall not have zeros, result = 0 means overflow happened; it also can't be npos as it is used to initialize size in get_ubjson_size_type() { return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, "excessive ndarray size caused overflow", "size"), nullptr)); } @@ -12232,7 +12185,7 @@ class binary_reader const auto byte1 = static_cast(byte1_raw); const auto byte2 = static_cast(byte2_raw); - // Code from RFC 7049, Appendix D, Figure 3: + // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very @@ -12520,7 +12473,7 @@ class binary_reader bool get_ubjson_high_precision_number() { - // get the size of the following number string + // get size of following number string std::size_t size{}; bool no_ndarray = true; auto res = get_ubjson_size_value(size, no_ndarray); @@ -12618,7 +12571,7 @@ class binary_reader chars_read += new_chars_read; if (JSON_HEDLEY_UNLIKELY(new_chars_read < sizeof(T))) { - // in case of failure, advance position by 1 to report the failing location + // in case of failure, advance position by 1 to report failing location ++chars_read; sax->parse_error(chars_read, "", parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), nullptr)); return false; @@ -12649,22 +12602,17 @@ class binary_reader { return; } - else if constexpr(std::is_integral_v) + if constexpr(std::is_integral_v) { number = std::byteswap(number); return; } - else +#endif + auto* ptr = reinterpret_cast(&number); + for (std::size_t i = 0; i < sz / 2; ++i) { -#endif - auto* ptr = reinterpret_cast(&number); - for (std::size_t i = 0; i < sz / 2; ++i) - { - std::swap(ptr[i], ptr[sz - i - 1]); - } -#ifdef __cpp_lib_byteswap + std::swap(ptr[i], ptr[sz - i - 1]); } -#endif } /* @@ -13016,7 +12964,7 @@ class parser exception_message(token_type::end_of_input, "value"), nullptr)); } - // in case of an error, return a discarded value + // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; @@ -13043,7 +12991,7 @@ class parser parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr)); } - // in case of an error, return a discarded value + // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; @@ -13246,7 +13194,7 @@ class parser case token_type::parse_error: { - // using "uninitialized" to avoid an "expected" message + // using "uninitialized" to avoid "expected" message return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), nullptr)); @@ -13466,9 +13414,9 @@ namespace detail @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, -string). Its only purpose is to allow the iterator/const_iterator classes +string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by -a `difference_type` variable. Value begin_value (`0`) models the begin and +a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t @@ -13633,7 +13581,7 @@ NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { -// forward declare to be able to friend it later on +// forward declare, to be able to friend it later on template class iteration_proxy; template class iteration_proxy_value; @@ -14841,7 +14789,7 @@ class json_pointer { if (reference_token == "0") { - // start a new array if the reference token is 0 + // start a new array if reference token is 0 result = &result->operator[](0); } else @@ -14870,7 +14818,7 @@ class json_pointer The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as - a single value; that is, with an empty list of reference tokens. + single value; that is, with an empty list of reference tokens. */ case detail::value_t::string: case detail::value_t::boolean: @@ -14914,7 +14862,7 @@ class json_pointer // convert null values to arrays or objects before continuing if (ptr->is_null()) { - // check if the reference token is a number + // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const unsigned char x) @@ -14922,7 +14870,7 @@ class json_pointer return std::isdigit(x); }); - // change value to an array for numbers or "-" or to object otherwise + // change value to array for numbers or "-" or to object otherwise *ptr = (nums || reference_token == "-") ? detail::value_t::array : detail::value_t::object; @@ -15165,7 +15113,7 @@ class json_pointer { if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) { - // the first char should be between '1' and '9' + // first char should be between '1' and '9' return false; } for (std::size_t i = 1; i < reference_token.size(); i++) @@ -15229,7 +15177,7 @@ class json_pointer return result; } - // check if a nonempty reference string begins with slash + // check if nonempty reference string begins with slash if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, detail::concat("JSON pointer must be empty or begin with '/' - was: '", reference_string, "'"), nullptr)); @@ -15303,7 +15251,7 @@ class json_pointer } else { - // iterate array and use index as a reference string + // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_data.m_value.array->size(); ++i) { flatten(detail::concat(reference_string, '/', std::to_string(i)), @@ -15341,7 +15289,7 @@ class json_pointer case detail::value_t::discarded: default: { - // add a primitive value with its reference string + // add primitive value with its reference string result[reference_string] = value; break; } @@ -15377,17 +15325,17 @@ class json_pointer JSON_THROW(detail::type_error::create(315, "values in object must be primitive", &element.second)); } - // Assign the value to the reference pointed to by JSON pointer. Note - // that if the JSON pointer is "" (i.e., points to the whole value), - // function get_and_create returns a reference to the result itself. - // An assignment will then create a primitive value. + // assign value to reference pointed to by JSON pointer; Note that if + // the JSON pointer is "" (i.e., points to the whole value), function + // get_and_create returns a reference to result itself. An assignment + // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } - // can't use the conversion operator because of ambiguity + // can't use conversion operator because of ambiguity json_pointer convert() const& { json_pointer result; @@ -15482,7 +15430,7 @@ class json_pointer }; #if !JSON_HAS_THREE_WAY_COMPARISON -// functions cannot be defined inside the class due to ODR violations +// functions cannot be defined inside class due to ODR violations template inline bool operator==(const json_pointer& lhs, const json_pointer& rhs) noexcept @@ -16765,9 +16713,9 @@ class binary_writer if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) { JSON_THROW(out_of_range::create(409, concat("BSON key cannot contain code point U+0000 (at byte ", std::to_string(it), ")"), &j)); + static_cast(j); } - static_cast(j); return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; } @@ -17344,7 +17292,7 @@ class binary_writer { return 'L'; } - // anything else is treated as a high-precision number + // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } @@ -17382,7 +17330,7 @@ class binary_writer { return 'M'; } - // anything else is treated as a high-precision number + // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } @@ -17548,11 +17496,11 @@ class binary_writer template void write_number(const NumberType n, const bool OutputIsLittleEndian = false) { - // step 1: write the number to an array of length NumberType + // step 1: write number to array of length NumberType std::array vec{}; std::memcpy(vec.data(), &n, sizeof(NumberType)); - // step 2: write the array to output (with possible reordering) + // step 2: write array to output (with possible reordering) if (is_little_endian != OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary @@ -17802,7 +17750,7 @@ struct diyfp // f * 2^e // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. - // Effectively, we only need to add the highest bit in p_lo to p_hi (and + // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up @@ -17892,7 +17840,7 @@ boundaries compute_boundaries(FloatType value) // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // - // Determine v- and v+, the floating-point predecessor and successor of v, + // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) @@ -18047,7 +17995,7 @@ inline cached_power get_cached_power_for_binary_exponent(int e) // (A smaller distance gamma-alpha would require a larger table.) // NB: - // Actually, this function returns c, such that -60 <= e_c + e + 64 <= -34. + // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; @@ -18359,8 +18307,8 @@ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, decimal_exponent += n; - // We may now just stop. But instead, it looks as if the buffer - // could be decremented to bring V closer to w. + // We may now just stop. But instead look if the buffer could be + // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit @@ -18767,7 +18715,7 @@ char* to_chars(char* first, const char* last, FloatType value) // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. - // len is the length of the buffer, i.e., the number of decimal digits. + // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); @@ -18848,7 +18796,7 @@ class serializer , error_handler(error_handler_) {} - // deleted because of pointer members + // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; serializer(serializer&&) = delete; @@ -19346,7 +19294,7 @@ class serializer break; } - default: // decode found yet incomplete multibyte code point + default: // decode found yet incomplete multi-byte code point { if (!ensure_ascii) { @@ -19535,7 +19483,7 @@ class serializer // jump to the end to generate the string from backward, // so we later avoid reversing the result - buffer_ptr += static_cast(n_chars); + buffer_ptr += n_chars; // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu // See: https://www.youtube.com/watch?v=o4-CwDo2zpg @@ -19600,7 +19548,7 @@ class serializer void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) { - // get the number of digits for a float -> text -> float round-trip + // get number of digits for a float -> text -> float round-trip static constexpr auto d = std::numeric_limits::max_digits10; // the actual conversion @@ -19609,10 +19557,10 @@ class serializer // negative value indicates an error JSON_ASSERT(len > 0); - // check if the buffer was large enough + // check if buffer was large enough JSON_ASSERT(static_cast(len) < number_buffer.size()); - // erase thousands separators + // erase thousands separator if (thousands_sep != '\0') { // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 @@ -19720,8 +19668,8 @@ class serializer * Helper function for dump_integer * * This function takes a negative signed integer and returns its absolute - * value as an unsigned integer. The plus/minus shuffling is necessary as we - * cannot directly remove the sign of an arbitrary signed integer as the + * value as unsigned integer. The plus/minus shuffling is necessary as we can + * not directly remove the sign of an arbitrary signed integer as the * absolute values of INT_MIN and INT_MAX are usually not the same. See * #1708 for details. */ @@ -19995,7 +19943,7 @@ template , // Since we cannot move const Keys, we re-construct them in place. // We start at first and re-construct (viz. copy) the elements from - // the back of the vector. Example for the first iteration: + // the back of the vector. Example for first iteration: // ,--------. // v | destroy e and re-construct with h @@ -20629,7 +20577,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec (t == value_t::binary && binary == nullptr) ) { - //not initialized (e.g., due to exception in the ctor) + //not initialized (e.g. due to exception in the ctor) return; } if (t == value_t::array || t == value_t::object) @@ -20654,7 +20602,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec while (!stack.empty()) { - // move the last item to a local variable to be processed + // move the last item to local variable to be processed basic_json current_item(std::move(stack.back())); stack.pop_back(); @@ -20676,7 +20624,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec current_item.m_data.m_value.object->clear(); } - // it's now safe that current_item gets destructed + // it's now safe that current_item get destructed // since it doesn't have any children } } @@ -20984,20 +20932,20 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec { // The cast is to ensure op[size_type] is called, bearing in mind size_type may not be int; // (many string types can be constructed from 0 via its null-pointer guise, so we get a - // broken call to op[key_type], the wrong semantics, and a 4804 warning on Windows) + // broken call to op[key_type], the wrong semantics and a 4804 warning on Windows) return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[static_cast(0)].is_string(); }); // adjust type if type deduction is not wanted if (!type_deduction) { - // if an array is wanted, do not create an object though possible + // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } - // if an object is wanted but impossible, throw an exception + // if object is wanted but impossible, throw an exception if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list", nullptr)); @@ -21006,7 +20954,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec if (is_an_object) { - // the initializer list is a list of pairs -> create an object + // the initializer list is a list of pairs -> create object m_data.m_type = value_t::object; m_data.m_value = value_t::object; @@ -21020,7 +20968,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec } else { - // the initializer list describes an array -> create an array + // the initializer list describes an array -> create array m_data.m_type = value_t::array; m_data.m_value.array = create(init.begin(), init.end()); } @@ -21108,16 +21056,16 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec JSON_ASSERT(first.m_object != nullptr); JSON_ASSERT(last.m_object != nullptr); - // make sure the iterator fits the current value + // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", nullptr)); } - // copy type from the first iterator + // copy type from first iterator m_data.m_type = first.m_object->m_data.m_type; - // check if the iterator range is complete for primitive values + // check if iterator range is complete for primitive values switch (m_data.m_type) { case value_t::boolean: @@ -21297,7 +21245,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec , end_position(other.end_position) // cppcheck-suppress[accessForwarded] TODO check #endif { - // check that the passed value is valid + // check that passed value is valid other.assert_invariant(false); // cppcheck-suppress[accessForwarded] // invalidate payload @@ -21323,7 +21271,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec std::is_nothrow_move_assignable::value ) { - // check that the passed value is valid + // check that passed value is valid other.assert_invariant(); using std::swap; @@ -22039,7 +21987,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec } JSON_CATCH (std::out_of_range&) { - // create a better exception explanation + // create better exception explanation JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this)); } // cppcheck-suppress[missingReturn] } @@ -22062,7 +22010,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec } JSON_CATCH (std::out_of_range&) { - // create a better exception explanation + // create better exception explanation JSON_THROW(out_of_range::create(401, detail::concat("array index ", std::to_string(idx), " is out of range"), this)); } // cppcheck-suppress[missingReturn] } @@ -22152,7 +22100,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ reference operator[](size_type idx) { - // implicitly convert a null value to an empty array + // implicitly convert null value to an empty array if (is_null()) { m_data.m_type = value_t::array; @@ -22163,7 +22111,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { - // fill up the array with null values if given idx is outside the range + // fill up array with null values if given idx is outside range if (idx >= m_data.m_value.array->size()) { #if JSON_DIAGNOSTICS @@ -22211,7 +22159,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ reference operator[](typename object_t::key_type key) // NOLINT(performance-unnecessary-value-param) { - // implicitly convert a null value to an empty object + // implicitly convert null value to an empty object if (is_null()) { m_data.m_type = value_t::object; @@ -22264,7 +22212,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec detail::is_usable_as_basic_json_key_type::value, int > = 0 > reference operator[](KeyType && key) { - // implicitly convert a null value to an empty object + // implicitly convert null value to an empty object if (is_null()) { m_data.m_type = value_t::object; @@ -22321,7 +22269,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // value only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { - // If 'key' is found, return its value. Otherwise, return `default_value'. + // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { @@ -22346,7 +22294,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // value only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { - // If 'key' is found, return its value. Otherwise, return `default_value'. + // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { @@ -22372,7 +22320,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // value only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { - // If 'key' is found, return its value. Otherwise, return `default_value'. + // if key is found, return value and given default value otherwise const auto it = find(std::forward(key)); if (it != end()) { @@ -22399,7 +22347,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // value only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { - // If 'key' is found, return its value. Otherwise, return `default_value'. + // if key is found, return value and given default value otherwise const auto it = find(std::forward(key)); if (it != end()) { @@ -22422,8 +22370,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // value only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { - // If the pointer resolves to a value, return it. Otherwise, return - // 'default_value'. + // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this).template get(); @@ -22448,8 +22395,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // value only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { - // If the pointer resolves to a value, return it. Otherwise, return - // 'default_value'. + // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this).template get(); @@ -22523,7 +22469,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec std::is_same::value, int > = 0 > IteratorType erase(IteratorType pos) // NOLINT(performance-unnecessary-value-param) { - // make sure the iterator fits the current value + // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", this)); @@ -22593,7 +22539,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec std::is_same::value, int > = 0 > IteratorType erase(IteratorType first, IteratorType last) // NOLINT(performance-unnecessary-value-param) { - // make sure the iterator fits the current value + // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", this)); @@ -23188,7 +23134,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this)); } - // transform a null object into an array + // transform null object into an array if (is_null()) { m_data.m_type = value_t::array; @@ -23196,7 +23142,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec assert_invariant(); } - // add the element to the array (move semantics) + // add element to array (move semantics) const auto old_capacity = m_data.m_value.array->capacity(); m_data.m_value.array->push_back(std::move(val)); set_parent(m_data.m_value.array->back(), old_capacity); @@ -23221,7 +23167,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this)); } - // transform a null object into an array + // transform null object into an array if (is_null()) { m_data.m_type = value_t::array; @@ -23229,7 +23175,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec assert_invariant(); } - // add the element to the array + // add element to array const auto old_capacity = m_data.m_value.array->capacity(); m_data.m_value.array->push_back(val); set_parent(m_data.m_value.array->back(), old_capacity); @@ -23253,7 +23199,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec JSON_THROW(type_error::create(308, detail::concat("cannot use push_back() with ", type_name()), this)); } - // transform a null object into an object + // transform null object into an object if (is_null()) { m_data.m_type = value_t::object; @@ -23261,7 +23207,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec assert_invariant(); } - // add the element to the object + // add element to object auto res = m_data.m_value.object->insert(val); set_parent(res.first->second); } @@ -23309,7 +23255,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec JSON_THROW(type_error::create(311, detail::concat("cannot use emplace_back() with ", type_name()), this)); } - // transform a null object into an array + // transform null object into an array if (is_null()) { m_data.m_type = value_t::array; @@ -23317,7 +23263,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec assert_invariant(); } - // add the element to the array (perfect forwarding) + // add element to array (perfect forwarding) const auto old_capacity = m_data.m_value.array->capacity(); m_data.m_value.array->emplace_back(std::forward(args)...); return set_parent(m_data.m_value.array->back(), old_capacity); @@ -23334,7 +23280,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec JSON_THROW(type_error::create(311, detail::concat("cannot use emplace() with ", type_name()), this)); } - // transform a null object into an object + // transform null object into an object if (is_null()) { m_data.m_type = value_t::object; @@ -23342,11 +23288,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec assert_invariant(); } - // add the element to the array (perfect forwarding) + // add element to array (perfect forwarding) auto res = m_data.m_value.object->emplace(std::forward(args)...); set_parent(res.first->second); - // create a result iterator and set iterator to the result of emplace + // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; @@ -23510,7 +23456,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec /// @sa https://json.nlohmann.me/api/basic_json/update/ void update(const_iterator first, const_iterator last, bool merge_objects = false) // NOLINT(performance-unnecessary-value-param) { - // implicitly convert a null value to an empty object + // implicitly convert null value to an empty object if (is_null()) { m_data.m_type = value_t::object; @@ -24070,7 +24016,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { - // read width member and use it as the indentation parameter if nonzero + // read width member and use it as indentation parameter if nonzero const bool pretty_print = o.width() > 0; const auto indentation = pretty_print ? o.width() : 0; @@ -24865,7 +24811,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec result.at(top_pointer); } - // get reference to the parent of the JSON pointer ptr + // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); // parent must exist when performing patch add per RFC6902 specs @@ -24903,7 +24849,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec break; } - // if there exists a parent, it cannot be primitive + // if there exists a parent it cannot be primitive case value_t::string: // LCOV_EXCL_LINE case value_t::boolean: // LCOV_EXCL_LINE case value_t::number_integer: // LCOV_EXCL_LINE @@ -24919,7 +24865,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [this, & result](json_pointer & ptr) { - // get reference to the parent of the JSON pointer ptr + // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result.at(ptr); @@ -24965,14 +24911,14 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : detail::concat("operation '", op, '\''); // NOLINT(bugprone-unused-local-non-trivial-variable) - // check if the desired value is present + // check if desired value is present if (JSON_HEDLEY_UNLIKELY(it == val.m_data.m_value.object->end())) { // NOLINTNEXTLINE(performance-inefficient-string-concatenation) JSON_THROW(parse_error::create(105, 0, detail::concat(error_msg, " must have member '", member, "'"), &val)); } - // check if the result is of type string + // check if result is of type string if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) { // NOLINTNEXTLINE(performance-inefficient-string-concatenation) @@ -25061,7 +25007,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // ignore out of range errors: success remains false } - // throw an exception if the test fails + // throw an exception if test fails if (JSON_HEDLEY_UNLIKELY(!success)) { JSON_THROW(other_error::create(501, detail::concat("unsuccessful: ", val.dump()), &val)); @@ -25099,7 +25045,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec // the patch basic_json result(value_t::array); - // if the values are the same, return an empty patch + // if the values are the same, return empty patch if (source == target) { return result; @@ -25213,7 +25159,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec case value_t::discarded: default: { - // both primitive types: replace value + // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..a2d6e31 --- /dev/null +++ b/meson.build @@ -0,0 +1,24 @@ +project('nlohmann_json', + 'cpp', + version : '3.12.0', + license : 'MIT', +) + +nlohmann_json_dep = declare_dependency( + include_directories: include_directories('single_include') +) + +nlohmann_json_multiple_headers = declare_dependency( + include_directories: include_directories('include') +) + +if not meson.is_subproject() +install_headers('single_include/nlohmann/json.hpp', subdir: 'nlohmann') +install_headers('single_include/nlohmann/json_fwd.hpp', subdir: 'nlohmann') + +pkgc = import('pkgconfig') +pkgc.generate(name: 'nlohmann_json', + version: meson.project_version(), + description: 'JSON for Modern C++' +) +endif