From 0b68fd46fb33d3cf81889c26b560f1051d34234d Mon Sep 17 00:00:00 2001 From: Huang-Ming Huang Date: Mon, 11 Feb 2019 14:10:38 -0600 Subject: [PATCH 01/59] Some cmake improvements --- CMakeLists.txt | 8 ++++++-- README.md | 2 +- cmake_command | 2 +- examples/CMakeLists.txt | 11 +++++++---- tests/CMakeLists.txt | 22 ++++++++++++++-------- 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 390fa77..e4d6793 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,9 +10,13 @@ SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall" ) include_directories (include) -#find_package(OpenSSL REQUIRED) +find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) -link_directories(${OPENSSL_LIBRARIES}) + +find_package(GTest REQUIRED) +include_directories(${GTEST_INCLUDE_DIRS}) + +enable_testing() # Recurse into the "Hello" and "Demo" subdirectories. This does not actually # cause another cmake executable to run. The same process will walk through diff --git a/README.md b/README.md index 451c952..7c21a03 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ This is a header only library, so you can just add it to your include path and s For example one can run cmake like: ``` -cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j/ -DOPENSSL_LIBRARIES=/usr/local/Cellar/openssl/1.0.2j/lib/ -DOPENSSL_INCLUDE_DIR=/usr/local/Cellar/openssl/1.0.2j/include/ +cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j -DGTEST_ROOT=$HOME/googletest ``` ## Parameters diff --git a/cmake_command b/cmake_command index 8fc16f6..507352d 100644 --- a/cmake_command +++ b/cmake_command @@ -1 +1 @@ -cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j/ -DOPENSSL_LIBRARIES=/usr/local/Cellar/openssl/1.0.2j/lib/ -DOPENSSL_INCLUDE_DIR=/usr/local/Cellar/openssl/1.0.2j/include/ +cmake -DOPENSSL_ROOT_DIR=/usr/local/Cellar/openssl/1.0.2j -DGTEST_ROOT=$HOME/googletest \ No newline at end of file diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 281e87e..9180a01 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,15 +1,18 @@ include_directories(${OPENSSL_INCLUDE_DIR}) -link_directories(${OPENSSL_LIBRARIES}) SET(CERT_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/rsa_256") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DCERT_ROOT_DIR=\"\\\"${CERT_ROOT_DIR}\\\"\"") add_executable(simple_ex1 simple_ex1.cc) -target_link_libraries(simple_ex1 ssl crypto gtest) +target_link_libraries(simple_ex1 ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME simple_ex1 COMMAND ./simple_ex1 WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(simple_ex2 simple_ex2.cc) -target_link_libraries(simple_ex2 ssl crypto gtest) +target_link_libraries(simple_ex2 ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME simple_ex2 COMMAND ./simple_ex2 WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(simple_ex3_rsa simple_ex3_rsa.cc) -target_link_libraries(simple_ex3_rsa ssl crypto gtest) +target_link_libraries(simple_ex3_rsa ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME simple_ex3_rsa COMMAND ./simple_ex3_rsa WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c52e256..1ee5201 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,27 +1,33 @@ include_directories(${OPENSSL_INCLUDE_DIR}) -link_directories(${OPENSSL_LIBRARIES}) SET(CERT_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/certs") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DCERT_ROOT_DIR=\"\\\"${CERT_ROOT_DIR}\\\"\"") add_executable(test_jwt_object test_jwt_object.cc) -target_link_libraries(test_jwt_object ssl crypto gtest) +target_link_libraries(test_jwt_object ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_object COMMAND ./test_jwt_object WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_encode test_jwt_encode.cc) -target_link_libraries(test_jwt_encode ssl crypto gtest) +target_link_libraries(test_jwt_encode ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_encode COMMAND ./test_jwt_encode WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_decode test_jwt_decode.cc) -target_link_libraries(test_jwt_decode ssl crypto gtest) +target_link_libraries(test_jwt_decode ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_decode COMMAND ./test_jwt_decode WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_decode_verifiy test_jwt_decode_verifiy.cc) -target_link_libraries(test_jwt_decode_verifiy ssl crypto gtest) +target_link_libraries(test_jwt_decode_verifiy ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_decode_verifiy COMMAND ./test_jwt_decode_verifiy WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_decode_verifiy_with_exception test_jwt_decode_verifiy_with_exception.cc) -target_link_libraries(test_jwt_decode_verifiy_with_exception ssl crypto gtest) +target_link_libraries(test_jwt_decode_verifiy_with_exception ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_decode_verifiy_with_exception COMMAND ./test_jwt_decode_verifiy_with_exception WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_rsa test_jwt_rsa.cc) -target_link_libraries(test_jwt_rsa ssl crypto gtest) +target_link_libraries(test_jwt_rsa ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES} ) +add_test(NAME test_jwt_rsa COMMAND ./test_jwt_rsa WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_executable(test_jwt_es test_jwt_es.cc) -target_link_libraries(test_jwt_es ssl crypto gtest) +target_link_libraries(test_jwt_es ${OPENSSL_LIBRARIES} ${GTEST_LIBRARIES}) +add_test(NAME test_jwt_es COMMAND ./test_jwt_es WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) From 74b7b344c6d2ff97a752bbdc8247a82529801832 Mon Sep 17 00:00:00 2001 From: Huang-Ming Huang Date: Sat, 16 Feb 2019 15:36:12 -0600 Subject: [PATCH 02/59] Add api to supply secret based on decoded payload --- include/jwt/impl/jwt.ipp | 14 ++++++++++++-- include/jwt/jwt.hpp | 5 ++++- include/jwt/parameters.hpp | 16 ++++++++++++++++ tests/test_jwt_es.cc | 9 +++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 5e17936..197a614 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -544,6 +544,14 @@ void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret jwt_object::set_decode_params(dparams, std::forward(args)...); } +template +void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret_function_param&& s, Rest&&... args) +{ + dparams.secret = s.get(*dparams.payload_ptr); + dparams.has_secret = true; + jwt_object::set_decode_params(dparams, std::forward(args)...); +} + template void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args) { @@ -650,10 +658,11 @@ jwt_object decode(const jwt::string_view enc_str, //Validate JTI bool validate_jti = false; + const jwt_payload* payload_ptr = 0; }; decode_params dparams{}; - jwt_object::set_decode_params(dparams, std::forward(args)...); + //Signature must have atleast 2 dots auto dot_cnt = std::count_if(std::begin(enc_str), std::end(enc_str), @@ -695,7 +704,8 @@ jwt_object decode(const jwt::string_view enc_str, return obj; } obj.payload(std::move(payload)); - + dparams.payload_ptr = & obj.payload(); + jwt_object::set_decode_params(dparams, std::forward(args)...); if (dparams.verify) { try { ec = obj.verify(dparams, algos); diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index c96edcb..36dac5f 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -82,7 +82,7 @@ inline jwt::string_view type_to_str(SCOPED_ENUM type typ) case type::JWT: return "JWT"; default: assert (0 && "Unknown type"); }; - + __builtin_unreachable(); assert (0 && "Code not reached"); } @@ -1121,6 +1121,9 @@ class jwt_object template static void set_decode_params(DecodeParams& dparams, params::detail::secret_param s, Rest&&... args); + template + static void set_decode_params(DecodeParams& dparams, params::detail::secret_function_param&& s, Rest&&... args); + template static void set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args); diff --git a/include/jwt/parameters.hpp b/include/jwt/parameters.hpp index b444e6e..9b94171 100644 --- a/include/jwt/parameters.hpp +++ b/include/jwt/parameters.hpp @@ -84,6 +84,15 @@ struct secret_param string_view secret_; }; +template +struct secret_function_param +{ + T get() const { return fun_; } + template + std::string get(U&& u) const { return fun_(u);} + T fun_; +}; + /** * Parameter for providing the algorithm to use. * The parameter can accept either the string representation @@ -297,6 +306,13 @@ inline detail::secret_param secret(const string_view sv) return { sv }; } +template +inline std::enable_if_t::value, detail::secret_function_param> +secret(T&& fun) +{ + return detail::secret_function_param{ fun }; +} + /** */ inline detail::algorithm_param algorithm(const string_view sv) diff --git a/tests/test_jwt_es.cc b/tests/test_jwt_es.cc index 9064d2d..085cfd1 100644 --- a/tests/test_jwt_es.cc +++ b/tests/test_jwt_es.cc @@ -136,6 +136,15 @@ TEST (ESAlgo, ES384EncodingDecodingValidTest) EXPECT_EQ (dec_obj.header().algo(), jwt::algorithm::ES384); EXPECT_TRUE (dec_obj.has_claim("exp")); EXPECT_TRUE (obj.payload().has_claim_with_value("exp", 4682665886)); + + std::map keystore{{"arun.muralidharan", key}}; + + auto l = [&keystore](const jwt::jwt_payload& payload){ + auto iss = payload.get_claim_value("iss"); + return keystore[iss]; + }; + auto dec_obj2 = jwt::decode(enc_str, algorithms({"es384"}), verify(true), secret(l)); + EXPECT_EQ (dec_obj2.header().algo(), jwt::algorithm::ES384); } int main(int argc, char* argv[]) { From ff21be29478d379e9aeb9d9c3ffef6bc9f864848 Mon Sep 17 00:00:00 2001 From: Matt Powley Date: Thu, 21 Mar 2019 12:31:02 +0000 Subject: [PATCH 03/59] '__builtin_unreachable' is not available on Windows Replaced with macro that inserts Windows equivalent --- include/jwt/algorithm.hpp | 5 ++-- include/jwt/assertions.hpp | 51 ++++++++++++++++++++++++++++++++++++++ include/jwt/jwt.hpp | 9 ++++--- 3 files changed, 59 insertions(+), 6 deletions(-) create mode 100644 include/jwt/assertions.hpp diff --git a/include/jwt/algorithm.hpp b/include/jwt/algorithm.hpp index 9abe20c..eba497b 100644 --- a/include/jwt/algorithm.hpp +++ b/include/jwt/algorithm.hpp @@ -43,6 +43,7 @@ SOFTWARE. #include #include +#include "jwt/assertions.hpp" #include "jwt/exceptions.hpp" #include "jwt/string_view.hpp" #include "jwt/error_codes.hpp" @@ -239,7 +240,7 @@ inline jwt::string_view alg_to_str(SCOPED_ENUM algorithm alg) noexcept default: assert (0 && "Unknown Algorithm"); }; return "UNKN"; - assert (0 && "Code not reached"); + JWT_NOT_REACHED("Code not reached"); } /** @@ -263,7 +264,7 @@ inline SCOPED_ENUM algorithm str_to_alg(const jwt::string_view alg) noexcept return algorithm::UNKN; - assert (0 && "Code not reached"); + JWT_NOT_REACHED("Code not reached"); } /** diff --git a/include/jwt/assertions.hpp b/include/jwt/assertions.hpp new file mode 100644 index 0000000..1fa0fd1 --- /dev/null +++ b/include/jwt/assertions.hpp @@ -0,0 +1,51 @@ +/* +Copyright (c) 2017 Arun Muralidharan + +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. + */ + +#ifndef CPP_JWT_ASSERTIONS_HPP +#define CPP_JWT_ASSERTIONS_HPP + +#include + +namespace jwt { + +#if defined(__clang__) +# define JWT_NOT_REACHED_MARKER() __builtin_unreachable() +#elif defined(__GNUC__) +# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) +# define JWT_NOT_REACHED_MARKER() __builtin_unreachable() +# endif +#elif defined(_MSC_VER) +# define JWT_NOT_REACHED_MARKER() __assume(0) +#endif + +#if defined(DEBUG) +# define JWT_NOT_REACHED(reason) do { \ + assert (0 && reason); \ + JWT_NOT_REACHED_MARKER(); \ + } while (0) +#else +# define JWT_NOT_REACHED(reason) JWT_NOT_REACHED_MARKER() +#endif + +} // END namespace jwt + +#endif diff --git a/include/jwt/jwt.hpp b/include/jwt/jwt.hpp index 36dac5f..7cc0ecc 100644 --- a/include/jwt/jwt.hpp +++ b/include/jwt/jwt.hpp @@ -31,6 +31,7 @@ SOFTWARE. #include #include +#include "jwt/assertions.hpp" #include "jwt/base64.hpp" #include "jwt/config.hpp" #include "jwt/algorithm.hpp" @@ -67,7 +68,7 @@ inline enum type str_to_type(const jwt::string_view typ) noexcept if (!strcasecmp(typ.data(), "jwt")) return type::JWT; else if(!strcasecmp(typ.data(), "none")) return type::NONE; - assert (0 && "Code not reached"); + JWT_NOT_REACHED("Code not reached"); return type::NONE; } @@ -82,8 +83,8 @@ inline jwt::string_view type_to_str(SCOPED_ENUM type typ) case type::JWT: return "JWT"; default: assert (0 && "Unknown type"); }; - __builtin_unreachable(); - assert (0 && "Code not reached"); + + JWT_NOT_REACHED("Code not reached"); } @@ -125,8 +126,8 @@ inline jwt::string_view reg_claims_to_str(SCOPED_ENUM registered_claims claim) n case registered_claims::jti: return "jti"; default: assert (0 && "Not a registered claim"); }; + JWT_NOT_REACHED("Code not reached"); return ""; - assert (0 && "Code not reached"); } /** From 31df3b8bd4f11f0d7470b2aeca9bcf4ffa491163 Mon Sep 17 00:00:00 2001 From: leoTlr Date: Thu, 4 Apr 2019 00:24:25 +0200 Subject: [PATCH 04/59] compile with -Wextra --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e4d6793..07810da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ cmake_minimum_required (VERSION 2.8.11) project (cpp-jwt) #SET (CMAKE_CXX_COMPILER /usr/local/bin/g++) -SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall" ) +SET( CMAKE_CXX_FLAGS "-std=c++14 -Wall -Wextra" ) include_directories (include) From a3a0d9c0ec9f30887aa06157b6b1804d0c6098c7 Mon Sep 17 00:00:00 2001 From: leoTlr Date: Thu, 4 Apr 2019 00:26:54 +0200 Subject: [PATCH 05/59] prevent -Wunused-parameter warning with gcc 8.2.1 --- include/jwt/impl/jwt.ipp | 1 + 1 file changed, 1 insertion(+) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 197a614..01b0881 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -607,6 +607,7 @@ void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::valida template void jwt_object::set_decode_params(DecodeParams& dparams) { + (void) dparams; // prevent -Wunused-parameter with gcc return; } From 4234eea1bf9e7929a508aea2839f5f7fbb579bc1 Mon Sep 17 00:00:00 2001 From: leoTlr Date: Thu, 4 Apr 2019 00:27:39 +0200 Subject: [PATCH 06/59] prevent -Wimplicit-fallthrough= warning with gcc 8.2.1 --- include/jwt/base64.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/jwt/base64.hpp b/include/jwt/base64.hpp index 226c1f0..4cb28d7 100644 --- a/include/jwt/base64.hpp +++ b/include/jwt/base64.hpp @@ -229,16 +229,16 @@ inline std::string base64_decode(const char* in, size_t len) const auto fourth = dmap.at(in[3]); result[i + 2] = (third << 6) | fourth; bytes_wr++; - //FALLTHROUGH } + //FALLTHROUGH case 3: { const auto second = dmap.at(in[1]); const auto third = dmap.at(in[2]); result[i + 1] = (second << 4) | (third >> 2); bytes_wr++; - //FALLTHROUGH } + //FALLTHROUGH case 2: { const auto first = dmap.at(in[0]); From 602ec562e0b839127087e099383f0af2ca422317 Mon Sep 17 00:00:00 2001 From: Olcay Cabbas Date: Fri, 3 May 2019 09:08:21 +0300 Subject: [PATCH 07/59] Fix for error setw is not defined --- include/jwt/impl/jwt.ipp | 1 + 1 file changed, 1 insertion(+) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 01b0881..1797f4c 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -26,6 +26,7 @@ SOFTWARE. #include "jwt/config.hpp" #include "jwt/detail/meta.hpp" #include +#include namespace jwt { From 1e9667ae0d139a9eb741e30fd17c31373764c0ed Mon Sep 17 00:00:00 2001 From: Arun M Date: Fri, 31 May 2019 00:45:35 +0530 Subject: [PATCH 08/59] update nlohmann json library --- include/jwt/impl/jwt.ipp | 1 + include/jwt/json/json.hpp | 19614 +++++++++++++++++++++++++----------- 2 files changed, 13476 insertions(+), 6139 deletions(-) diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 01b0881..1797f4c 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -26,6 +26,7 @@ SOFTWARE. #include "jwt/config.hpp" #include "jwt/detail/meta.hpp" #include +#include namespace jwt { diff --git a/include/jwt/json/json.hpp b/include/jwt/json/json.hpp index d153e7a..c173f4e 100644 --- a/include/jwt/json/json.hpp +++ b/include/jwt/json/json.hpp @@ -1,18 +1,23 @@ /* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 2.1.1 +| | |__ | | | | | | version 3.6.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json + Licensed under the MIT License . -Copyright (c) 2013-2017 Niels Lohmann . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2019 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 @@ -22,143 +27,87 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef NLOHMANN_JSON_HPP -#define NLOHMANN_JSON_HPP +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ -#include // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform -#include // array +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 6 +#define NLOHMANN_JSON_VERSION_PATCH 1 + +#include // all_of, find, for_each #include // assert #include // and, not, or -#include // lconv, localeconv -#include // isfinite, labs, ldexp, signbit #include // nullptr_t, ptrdiff_t, size_t -#include // int64_t, uint64_t -#include // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull -#include // memcpy, strlen -#include // forward_list -#include // function, hash, less +#include // hash, less #include // initializer_list -#include // hex -#include // istream, ostream -#include // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator -#include // numeric_limits -#include // locale -#include // map -#include // addressof, allocator, allocator_traits, unique_ptr +#include // istream, ostream +#include // random_access_iterator_tag +#include // unique_ptr #include // accumulate -#include // stringstream -#include // getline, stoi, string, to_string -#include // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type -#include // declval, forward, make_pair, move, pair, swap -#include // valarray +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap #include // vector -// exclude unsupported compilers -#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__) < 40900 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif -#endif +// #include -// disable float-equal warnings on GCC/clang -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #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" -#endif +#include -// allow for portable deprecation warnings -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) - #define JSON_DEPRECATED __declspec(deprecated) -#else - #define JSON_DEPRECATED -#endif +// #include -// allow to disable exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) -#else - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) -#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) -#else - #define JSON_LIKELY(x) x - #define JSON_UNLIKELY(x) x -#endif +#include // transform +#include // array +#include // and, not +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray -// cpp 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 +// #include -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -template -struct adl_serializer; -// forward declaration of basic_json (required to split the class) -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer> -class basic_json; +#include // exception +#include // runtime_error +#include // to_string -// Ugly macros to avoid uglier copy-paste when specializing basic_json -// This is only temporary and will be removed in 3.0 +// #include -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer> -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json +#include // size_t +namespace nlohmann +{ +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; -/*! -@brief unnamed namespace with internal helper functions -This namespace collects some functions that could not be defined inside the -@ref basic_json class. -@since version 2.1.0 -*/ + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ namespace detail { //////////////// @@ -167,10 +116,12 @@ namespace detail /*! @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 @@ -178,14 +129,17 @@ exceptions. 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 @@ -215,12 +169,16 @@ class exception : public std::exception /*! @brief exception indicating a parse error -This excpetion is thrown by the library when a parse error occurs. Parse errors + +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. + Member @a byte holds the byte index of the last read character in the input file. + Exceptions have ids 1xx. + 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. @@ -228,24 +186,29 @@ json.exception.parse_error.102 | parse error at 14: missing or wrong low surroga 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 wihtout a leading `0`. +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.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). + @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). + @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} -@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 + +@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 +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class parse_error : public exception @@ -254,22 +217,32 @@ class parse_error : public exception /*! @brief create a parse error exception @param[in] id_ the id of the exception - @param[in] byte_ the byte index where the error occurred (or 0 if the - position cannot be determined) + @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 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 " + std::to_string(byte_)) : "") + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + ": " + what_arg; return parse_error(id_, byte_, w.c_str()); } /*! @brief byte index of the parse error + The byte index of the last read character in the input file. + @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). @@ -279,13 +252,22 @@ class parse_error : public exception private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} + + 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); + } }; /*! @brief exception indicating errors with iterators + This exception is thrown if iterators passed to a library function do not match the expected semantics. + Exceptions have ids 2xx. + 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. @@ -302,14 +284,17 @@ json.exception.invalid_iterator.211 | passed iterators may not belong to contain 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(). + @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} -@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 + +@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 +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class invalid_iterator : public exception @@ -328,14 +313,17 @@ class invalid_iterator : public exception /*! @brief exception indicating executing a member function with a wrong type + 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. + Exceptions have ids 3xx. + 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.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. @@ -348,13 +336,18 @@ json.exception.type_error.312 | cannot use update() with string | The @ref updat 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) | + @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} -@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 + +@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 + @since version 3.0.0 */ class type_error : public exception @@ -372,10 +365,13 @@ class type_error : public exception /*! @brief exception indicating access out of the defined range + 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. + Exceptions have ids 4xx. + 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. @@ -384,14 +380,20 @@ json.exception.out_of_range.403 | key 'foo' not found | The provided key was not 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 | + @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} -@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 + +@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 +@sa - @ref other_error for exceptions indicating other library errors + @since version 3.0.0 */ class out_of_range : public exception @@ -409,21 +411,26 @@ class out_of_range : public exception /*! @brief exception indicating other library errors + 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. -json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair) -@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 + +@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 +@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 @@ -438,91 +445,186 @@ class other_error : public exception private: other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; +} // namespace detail +} // namespace nlohmann +// #include -/////////////////////////// -// JSON type enumeration // -/////////////////////////// +#include // pair -/*! -@brief the JSON type enumeration -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. -@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type -@since version 1.0.0 -*/ -enum class value_t : uint8_t -{ - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - discarded ///< discarded by the the parser callback function -}; +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them -/*! -@brief comparison operator for JSON types -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string -- furthermore, each type is not smaller than itself -@since version 1.0.0 -*/ -inline bool operator<(const value_t lhs, const value_t rhs) noexcept -{ - static constexpr std::array order = {{ - 0, // null - 3, // object - 4, // array - 5, // string - 1, // boolean - 2, // integer - 2, // unsigned - 2, // float - } - }; +// 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 - // discarded values are not comparable - return lhs != value_t::discarded and rhs != value_t::discarded and - order[static_cast(lhs)] < order[static_cast(rhs)]; -} +// 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 +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif -///////////// -// helpers // -///////////// +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif -template struct is_basic_json : std::false_type {}; +// allow for portable deprecation warnings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) + #define JSON_DEPRECATED __declspec(deprecated) +#else + #define JSON_DEPRECATED +#endif -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct is_basic_json : std::true_type {}; +// 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 + #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 +#endif -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; +// 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) +#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) +#endif -template -using uncvref_t = typename std::remove_cv::type>::type; +// override exception macros +#if defined(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 +#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 +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif -// implementation of C++14 index_sequence and affiliates -// source: https://stackoverflow.com/a/32223343 +// 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) +#else + #define JSON_LIKELY(x) x + #define JSON_UNLIKELY(x) x +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// #include + + +#include // not +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type + +namespace nlohmann +{ +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 { @@ -539,581 +641,778 @@ struct merge_and_renumber; template struct merge_and_renumber, index_sequence> - : index_sequence < I1..., (sizeof...(I1) + I2)... > - {}; + : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, - typename make_index_sequence < N - N / 2 >::type > -{}; + typename make_index_sequence < N - N / 2 >::type > {}; -template<> struct make_index_sequence<0> : index_sequence<> { }; -template<> struct make_index_sequence<1> : index_sequence<0> { }; +template<> struct make_index_sequence<0> : index_sequence<> {}; +template<> struct make_index_sequence<1> : index_sequence<0> {}; template using index_sequence_for = make_index_sequence; -/* -Implementation of two C++17 constructs: conjunction, negation. This is needed -to avoid evaluating all the traits in a condition -For example: not std::is_same::value and has_value_type::value -will not compile when T = void (on MSVC at least). Whereas -conjunction>, has_value_type>::value will -stop evaluating if negation<...>::value == false -Please note that those constructs must be used with caution, since symbols can -become very long quickly (which can slow down compilation and cause MSVC -internal compiler errors). Only use it when you have to (see example ahead). -*/ -template struct conjunction : std::true_type {}; -template struct conjunction : B1 {}; -template -struct conjunction : std::conditional, B1>::type {}; - -template struct negation : std::integral_constant < bool, !B::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{}; +}; -////////////////// -// constructors // -////////////////// +template +constexpr T static_const::value; +} // namespace detail +} // namespace nlohmann -template struct external_constructor; +// #include -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept - { - j.m_type = value_t::boolean; - j.m_value = b; - j.assert_invariant(); - } -}; -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) - { - j.m_type = value_t::string; - j.m_value = s; - j.assert_invariant(); - } +#include // not +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval - template - static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) - { - j.m_type = value_t::string; - j.m_value = std::move(s); - j.assert_invariant(); - } -}; +// #include -template<> -struct external_constructor + +#include // random_access_iterator_tag + +// #include + + +namespace nlohmann { - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept - { - j.m_type = value_t::number_float; - j.m_value = val; - j.assert_invariant(); - } +namespace detail +{ +template struct make_void +{ + using type = void; }; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann -template<> -struct external_constructor +// #include + + +namespace nlohmann { - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept - { - j.m_type = value_t::number_unsigned; - j.m_value = val; - j.assert_invariant(); - } +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 external_constructor +// 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 - static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept - { - j.m_type = value_t::number_integer; - j.m_value = val; - j.assert_invariant(); - } }; -template<> -struct external_constructor +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types { - template - static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) - { - j.m_type = value_t::array; - j.m_value = arr; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) - { - j.m_type = value_t::array; - j.m_value = std::move(arr); - j.assert_invariant(); - } - - template::value, - int> = 0> - static void construct(BasicJsonType& j, const CompatibleArrayType& arr) - { - using std::begin; - using std::end; - j.m_type = value_t::array; - j.m_value.array = j.template create(begin(arr), end(arr)); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, const std::vector& arr) - { - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->reserve(arr.size()); - for (bool x : arr) - { - j.m_value.array->push_back(x); - } - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const std::valarray& arr) - { - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->resize(arr.size()); - std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); - j.assert_invariant(); - } }; -template<> -struct external_constructor +template +struct iterator_traits::value>> { - template - static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) - { - j.m_type = value_t::object; - j.m_value = obj; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) - { - j.m_type = value_t::object; - j.m_value = std::move(obj); - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const CompatibleObjectType& obj) - { - using std::begin; - using std::end; - - j.m_type = value_t::object; - j.m_value.object = j.template create(begin(obj), end(obj)); - j.assert_invariant(); - } + 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 -//////////////////////// -// has_/is_ functions // -//////////////////////// - -/*! -@brief Helper to determine whether there's a key_type for T. -This helper is used to tell associative containers apart from other containers -such as sequence containers. For instance, `std::map` passes the test as it -contains a `mapped_type`, whereas `std::vector` fails the test. -@sa http://stackoverflow.com/a/7728728/266378 -@since version 1.0.0, overworked in version 2.0.6 -*/ -#define NLOHMANN_JSON_HAS_HELPER(type) \ - template struct has_##type { \ - private: \ - template \ - static int detect(U &&); \ - static void detect(...); \ - public: \ - static constexpr bool value = \ - std::is_integral()))>::value; \ - } +// #include -NLOHMANN_JSON_HAS_HELPER(mapped_type); -NLOHMANN_JSON_HAS_HELPER(key_type); -NLOHMANN_JSON_HAS_HELPER(value_type); -NLOHMANN_JSON_HAS_HELPER(iterator); +// #include -#undef NLOHMANN_JSON_HAS_HELPER +#include -template -struct is_compatible_object_type_impl : std::false_type {}; +// #include -template -struct is_compatible_object_type_impl -{ - static constexpr auto value = - std::is_constructible::value and - std::is_constructible::value; -}; -template -struct is_compatible_object_type +// http://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann { - static auto constexpr value = is_compatible_object_type_impl < - conjunction>, - has_mapped_type, - has_key_type>::value, - typename BasicJsonType::object_t, CompatibleObjectType >::value; -}; - -template -struct is_basic_json_nested_type +namespace detail { - static auto constexpr value = std::is_same::value or - std::is_same::value or - std::is_same::value or - std::is_same::value; -}; - -template -struct is_compatible_array_type +struct nonesuch { - static auto constexpr value = - conjunction>, - negation>, - negation>, - negation>, - has_value_type, - has_iterator>::value; + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; }; -template -struct is_compatible_integer_type_impl : std::false_type {}; - -template -struct is_compatible_integer_type_impl +template class Op, + class... Args> +struct detector { - // is there an assert somewhere on overflows? - using RealLimits = std::numeric_limits; - using CompatibleLimits = std::numeric_limits; - - static constexpr auto value = - std::is_constructible::value and - CompatibleLimits::is_integer and - RealLimits::is_signed == CompatibleLimits::is_signed; + using value_t = std::false_type; + using type = Default; }; -template -struct is_compatible_integer_type +template class Op, class... Args> +struct detector>, Op, Args...> { - static constexpr auto value = - is_compatible_integer_type_impl < - std::is_integral::value and - not std::is_same::value, - RealIntegerType, CompatibleNumberIntegerType > ::value; + using value_t = std::true_type; + using type = Op; }; +template