diff --git a/build.gradle b/build.gradle index 465fa9d9d2..1ab25675da 100644 --- a/build.gradle +++ b/build.gradle @@ -38,10 +38,12 @@ model { wpiutil(ExportsConfig) { x86ExcludeSymbols = [ '_CT??_R0?AV_System_error', '_CT??_R0?AVexception', '_CT??_R0?AVfailure', '_CT??_R0?AVruntime_error', '_CT??_R0?AVsystem_error', '_CTA5?AVfailure', - '_TI5?AVfailure' ] + '_TI5?AVfailure', '_CT??_R0?AVout_of_range', '_CTA3?AVout_of_range', + '_TI3?AVout_of_range' ] x64ExcludeSymbols = [ '_CT??_R0?AV_System_error', '_CT??_R0?AVexception', '_CT??_R0?AVfailure', '_CT??_R0?AVruntime_error', '_CT??_R0?AVsystem_error', '_CTA5?AVfailure', - '_TI5?AVfailure' ] + '_TI5?AVfailure', '_CT??_R0?AVout_of_range', '_CTA3?AVout_of_range', + '_TI3?AVout_of_range' ] } } components { diff --git a/license.txt b/license.txt index dc37477da0..3f3592e42d 100644 --- a/license.txt +++ b/license.txt @@ -66,4 +66,31 @@ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS 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 WITH THE +SOFTWARE. + + + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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/src/main/native/cpp/support/json.cpp b/src/main/native/cpp/support/json.cpp new file mode 100644 index 0000000000..698a9463dd --- /dev/null +++ b/src/main/native/cpp/support/json.cpp @@ -0,0 +1,1182 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#define WPI_JSON_IMPLEMENTATION +#include "support/json.h" + +using namespace wpi; + +namespace wpi { +namespace detail { + +std::string exception::name(const std::string& ename, int id) +{ + return "[json.exception." + ename + "." + std::to_string(id) + "] "; +} + +parse_error parse_error::create(int id, 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_)) : "") + + ": " + what_arg; + return parse_error(id, byte_, w.c_str()); +} + +invalid_iterator invalid_iterator::create(int id, const std::string& what_arg) +{ + std::string w = exception::name("invalid_iterator", id) + what_arg; + return invalid_iterator(id, w.c_str()); +} + +type_error type_error::create(int id, const std::string& what_arg) +{ + std::string w = exception::name("type_error", id) + what_arg; + return type_error(id, w.c_str()); +} + +out_of_range out_of_range::create(int id, const std::string& what_arg) +{ + std::string w = exception::name("out_of_range", id) + what_arg; + return out_of_range(id, w.c_str()); +} + +other_error other_error::create(int id, const std::string& what_arg) +{ + std::string w = exception::name("other_error", id) + what_arg; + return other_error(id, w.c_str()); +} + +} // namespace detail +} // namespace wpi + +json::json_value::json_value(value_t t) +{ + switch (t) + { + case value_t::object: + { + object = create(); + break; + } + + case value_t::array: + { + array = create(); + break; + } + + case value_t::string: + { + string = create(""); + break; + } + + case value_t::boolean: + { + boolean = false; + break; + } + + case value_t::number_integer: + { + number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + number_unsigned = 0; + break; + } + + case value_t::number_float: + { + number_float = 0.0; + break; + } + + case value_t::null: + { + break; + } + + default: + { + if (JSON_UNLIKELY(t == value_t::null)) + { + JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE + } + break; + } + } +} + +json::json_value::json_value(llvm::StringRef value) +{ + string = create(value); +} + +json::json_value::json_value(const std::string& value) +{ + string = create(value); +} + +json::json_value::json_value(const object_t& value) +{ + object = create(value); +} + +json::json_value::json_value(const array_t& value) +{ + array = create(value); +} + +json::json(std::initializer_list init, + bool type_deduction, + value_t manual_type) +{ + // check if each element is an array with two elements whose first + // element is a string + bool is_an_object = std::all_of(init.begin(), init.end(), + [](const json & element) + { + return element.is_array() && element.size() == 2 && element[0].is_string(); + }); + + // adjust type if type deduction is not wanted + if (!type_deduction) + { + // if array is wanted, do not create an object though possible + if (manual_type == value_t::array) + { + is_an_object = false; + } + + // if object is wanted but impossible, throw an exception + if (manual_type == value_t::object && !is_an_object) + { + JSON_THROW(type_error::create(301, "cannot create object from initializer list")); + } + } + + if (is_an_object) + { + // the initializer list is a list of pairs -> create object + m_type = value_t::object; + m_value = value_t::object; + + std::for_each(init.begin(), init.end(), [this](const json & element) + { + m_value.object->emplace_second(*(element[0].m_value.string), element[1]); + }); + } + else + { + // the initializer list describes an array -> create array + m_type = value_t::array; + m_value.array = create(init); + } + + assert_invariant(); +} + +json::json(size_type cnt, const json& val) + : m_type(value_t::array) +{ + m_value.array = create(cnt, val); + assert_invariant(); +} + +json::json(const json& other) + : m_type(other.m_type) +{ + // check of passed value is valid + other.assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + m_value = *other.m_value.object; + break; + } + + case value_t::array: + { + m_value = *other.m_value.array; + break; + } + + case value_t::string: + { + m_value = *other.m_value.string; + break; + } + + case value_t::boolean: + { + m_value = other.m_value.boolean; + break; + } + + case value_t::number_integer: + { + m_value = other.m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value = other.m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value = other.m_value.number_float; + break; + } + + default: + { + break; + } + } + + assert_invariant(); +} + +json::~json() +{ + assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + std::allocator alloc; + alloc.destroy(m_value.object); + alloc.deallocate(m_value.object, 1); + break; + } + + case value_t::array: + { + std::allocator alloc; + alloc.destroy(m_value.array); + alloc.deallocate(m_value.array, 1); + break; + } + + case value_t::string: + { + std::allocator alloc; + alloc.destroy(m_value.string); + alloc.deallocate(m_value.string, 1); + break; + } + + default: + { + // all other types need no specific destructor + break; + } + } +} + +json json::meta() +{ + json result; + + result["copyright"] = "(C) 2013-2017 Niels Lohmann, (C) 2017 FIRST"; + result["name"] = "WPI version of JSON for Modern C++"; + result["url"] = "https://github.com/wpilibsuite/wpiutil"; + result["version"] = + { + {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1} + }; + +#ifdef _WIN32 + result["platform"] = "win32"; +#elif defined __linux__ + result["platform"] = "linux"; +#elif defined __APPLE__ + result["platform"] = "apple"; +#elif defined __unix__ + result["platform"] = "unix"; +#else + result["platform"] = "unknown"; +#endif + +#if defined(__clang__) + result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; +#elif defined(__ICC) || defined(__INTEL_COMPILER) + result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; +#elif defined(__GNUC__) || defined(__GNUG__) + result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; +#elif defined(__HP_cc) || defined(__HP_aCC) + result["compiler"] = "hp" +#elif defined(__IBMCPP__) + result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; +#elif defined(_MSC_VER) + result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; +#elif defined(__PGI) + result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; +#elif defined(__SUNPRO_CC) + result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; +#else + result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; +#endif + +#ifdef __cplusplus + result["compiler"]["c++"] = std::to_string(__cplusplus); +#else + result["compiler"]["c++"] = "unknown"; +#endif + return result; +} + +namespace wpi { + +bool operator==(json::const_reference lhs, json::const_reference rhs) noexcept +{ + using value_t = json::value_t; + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + { + return *lhs.m_value.array == *rhs.m_value.array; + } + case value_t::object: + { + return *lhs.m_value.object == *rhs.m_value.object; + } + case value_t::null: + { + return true; + } + case value_t::string: + { + return *lhs.m_value.string == *rhs.m_value.string; + } + case value_t::boolean: + { + return lhs.m_value.boolean == rhs.m_value.boolean; + } + case value_t::number_integer: + { + return lhs.m_value.number_integer == rhs.m_value.number_integer; + } + case value_t::number_unsigned: + { + return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; + } + case value_t::number_float: + { + return lhs.m_value.number_float == rhs.m_value.number_float; + } + default: + { + return false; + } + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); + } + + return false; +} + +bool operator<(json::const_reference lhs, json::const_reference rhs) noexcept +{ + using value_t = json::value_t; + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + { + return (*lhs.m_value.array) < (*rhs.m_value.array); + } + case value_t::object: + { + return *lhs.m_value.object < *rhs.m_value.object; + } + case value_t::null: + { + return false; + } + case value_t::string: + { + return *lhs.m_value.string < *rhs.m_value.string; + } + case value_t::boolean: + { + return lhs.m_value.boolean < rhs.m_value.boolean; + } + case value_t::number_integer: + { + return lhs.m_value.number_integer < rhs.m_value.number_integer; + } + case value_t::number_unsigned: + { + return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; + } + case value_t::number_float: + { + return lhs.m_value.number_float < rhs.m_value.number_float; + } + default: + { + return false; + } + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; + } + + // We only reach this line if we cannot compare values. In that case, + // we compare types. Note we have to call the operator explicitly, + // because MSVC has problems otherwise. + return operator<(lhs_type, rhs_type); +} + +} // namespace wpi + +std::string json::type_name() const +{ + { + switch (m_type) + { + case value_t::null: + return "null"; + case value_t::object: + return "object"; + case value_t::array: + return "array"; + case value_t::string: + return "string"; + case value_t::boolean: + return "boolean"; + case value_t::discarded: + return "discarded"; + default: + return "number"; + } + } +} + +bool json::empty() const noexcept +{ + switch (m_type) + { + case value_t::null: + { + // null values are empty + return true; + } + + case value_t::array: + { + // delegate call to array_t::empty() + return m_value.array->empty(); + } + + case value_t::object: + { + // delegate call to object_t::empty() + return m_value.object->empty(); + } + + default: + { + // all other types are nonempty + return false; + } + } +} + +json::size_type json::size() const noexcept +{ + switch (m_type) + { + case value_t::null: + { + // null values are empty + return 0; + } + + case value_t::array: + { + // delegate call to array_t::size() + return m_value.array->size(); + } + + case value_t::object: + { + // delegate call to object_t::size() + return m_value.object->size(); + } + + default: + { + // all other types have size 1 + return 1; + } + } +} + +json::size_type json::max_size() const noexcept +{ + switch (m_type) + { + case value_t::array: + { + // delegate call to array_t::max_size() + return m_value.array->max_size(); + } + + case value_t::object: + { + // delegate call to std::allocator::max_size() + return std::allocator().max_size(); + } + + default: + { + // all other types have max_size() == size() + return size(); + } + } +} + +void json::clear() noexcept +{ + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = 0; + break; + } + + case value_t::number_float: + { + m_value.number_float = 0.0; + break; + } + + case value_t::boolean: + { + m_value.boolean = false; + break; + } + + case value_t::string: + { + m_value.string->clear(); + break; + } + + case value_t::array: + { + m_value.array->clear(); + break; + } + + case value_t::object: + { + m_value.object->clear(); + break; + } + + default: + { + break; + } + } +} + +void json::push_back(json&& val) +{ + // push_back only works for null objects or arrays + if (!(is_null() || is_array())) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name())); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (move semantics) + m_value.array->push_back(std::move(val)); + // invalidate object + val.m_type = value_t::null; +} + +void json::push_back(const json& val) +{ + // push_back only works for null objects or arrays + if (!(is_null() || is_array())) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name())); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array + m_value.array->push_back(val); +} + +void json::push_back(const std::pair& val) +{ + // push_back only works for null objects or objects + if (!(is_null() || is_object())) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name())); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array + m_value.object->insert(val); +} + +void json::push_back(std::initializer_list init) +{ + if (is_object() && init.size() == 2 && init.begin()->is_string()) + { + const std::string key = *init.begin(); + push_back(std::pair(key, *(init.begin() + 1))); + } + else + { + push_back(json(init)); + } +} + +json::reference json::at(size_type idx) +{ + // at only works for arrays + if (is_array()) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + type_name())); + } +} + +json::const_reference json::at(size_type idx) const +{ + // at only works for arrays + if (is_array()) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + type_name())); + } +} + +json::reference json::at(llvm::StringRef key) +{ + // at only works for objects + if (is_object()) + { + auto it = m_value.object->find(key); + if (it == m_value.object->end()) + { + JSON_THROW(out_of_range::create(403, "key '" + key.str() + "' not found")); + } + return it->second; + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + type_name())); + } +} + +json::const_reference json::at(llvm::StringRef key) const +{ + // at only works for objects + if (is_object()) + { + auto it = m_value.object->find(key); + if (it == m_value.object->end()) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key.str() + "' not found")); + } + return it->second; + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + type_name())); + } +} + +json::reference json::operator[](size_type idx) +{ + // implicitly convert null value to an empty array + if (is_null()) + { + m_type = value_t::array; + m_value.array = create(); + assert_invariant(); + } + + // operator[] only works for arrays + if (is_array()) + { + // fill up array with null values if given idx is outside range + if (idx >= m_value.array->size()) + { + m_value.array->insert(m_value.array->end(), + idx - m_value.array->size() + 1, + json()); + } + + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name())); +} + +json::const_reference json::operator[](size_type idx) const +{ + // const operator[] only works for arrays + if (is_array()) + { + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name())); +} + +json::reference json::operator[](llvm::StringRef key) +{ + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + // operator[] only works for objects + if (is_object()) + { + return m_value.object->operator[](key); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name())); +} + +json::const_reference json::operator[](llvm::StringRef key) const +{ + // const operator[] only works for objects + if (is_object()) + { + assert(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name())); +} + +json::reference json::back() +{ + switch (m_type) + { + case value_t::object: + { + JSON_THROW(type_error::create(305, "cannot use back() with " + type_name())); + } + + case value_t::array: + { + return m_value.array->back(); + } + + case value_t::null: + { + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + + default: + { + return *this; + } + } +} + +json::const_reference json::back() const +{ + switch (m_type) + { + case value_t::object: + { + JSON_THROW(type_error::create(305, "cannot use back() with " + type_name())); + } + + case value_t::array: + { + return m_value.array->back(); + } + + case value_t::null: + { + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + + default: + { + return *this; + } + } +} + +json::size_type json::erase(llvm::StringRef key) +{ + // this erase only works for objects + if (is_object()) + { + return m_value.object->erase(key); + } + + JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name())); +} + +void json::erase(const size_type idx) +{ + // this erase only works for arrays + if (is_array()) + { + if (idx >= size()) + { + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + + m_value.array->erase(m_value.array->begin() + static_cast(idx)); + } + else + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name())); + } +} + +json::iterator json::find(llvm::StringRef key) +{ + auto result = end(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(key); + } + + return result; +} + +json::const_iterator json::find(llvm::StringRef key) const +{ + auto result = cend(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(key); + } + + return result; +} + +json::iterator json::insert(const_iterator pos, const json& val) +{ + // insert only works for arrays + if (is_array()) + { + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // insert to array and return iterator + iterator result(this); + result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); + return result; + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name())); +} + +json::iterator json::insert(const_iterator pos, size_type cnt, const json& val) +{ + // insert only works for arrays + if (is_array()) + { + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // insert to array and return iterator + iterator result(this); +#if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 + // handle C++11 noncompliance: insert(it, cnt, val) returns void + if (cnt == 0) { + result.m_it.array_iterator = pos.m_it.array_iterator; + } else { + size_t ipos = pos.m_it.array_iterator - m_value.array->begin(); + m_value.array->insert(pos.m_it.array_iterator, cnt, val); + result.m_it.array_iterator = m_value.array->begin() + ipos; + } +#else + result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); +#endif + return result; + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name())); +} + +json::iterator json::insert(const_iterator pos, const_iterator first, const_iterator last) +{ + // insert only works for arrays + if (!is_array()) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name())); + } + + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // check if range iterators belong to the same JSON object + if (first.m_object != last.m_object) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); + } + + if (first.m_object == this || last.m_object == this) + { + JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); + } + + // insert to array and return iterator + iterator result(this); +#if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 + // handle C++11 noncompliance: insert(it, first, last) returns void + if (first == last) { + result.m_it.array_iterator = pos.m_it.array_iterator; + } else { + size_t ipos = pos.m_it.array_iterator - m_value.array->begin(); + m_value.array->insert(pos.m_it.array_iterator, first.m_it.array_iterator, + last.m_it.array_iterator); + result.m_it.array_iterator = m_value.array->begin() + ipos; + } +#else + result.m_it.array_iterator = m_value.array->insert( + pos.m_it.array_iterator, + first.m_it.array_iterator, + last.m_it.array_iterator); +#endif + return result; +} + +json::iterator json::insert(const_iterator pos, std::initializer_list ilist) +{ + // insert only works for arrays + if (!is_array()) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name())); + } + + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // insert to array and return iterator + iterator result(this); +#if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 + // handle C++11 noncompliance: insert(it, ilist) returns void + if (ilist.size() == 0) { + result.m_it.array_iterator = pos.m_it.array_iterator; + } else { + size_t ipos = pos.m_it.array_iterator - m_value.array->begin(); + m_value.array->insert(pos.m_it.array_iterator, ilist); + result.m_it.array_iterator = m_value.array->begin() + ipos; + } +#else + result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist); +#endif + return result; +} + +void json::insert(const_iterator first, const_iterator last) +{ + // insert only works for objects + if (!is_object()) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name())); + } + + // check if range iterators belong to the same JSON object + if (first.m_object != last.m_object) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); + } + + // passed iterators must belong to objects + if (!first.m_object->is_object() || !first.m_object->is_object()) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); + } + + for (auto it = first.m_it.object_iterator, end = last.m_it.object_iterator; it != end; ++it) + { + m_value.object->insert(std::make_pair(it->first(), it->second)); + } +} + +namespace std { + +std::size_t hash::operator()(const wpi::json& j) const +{ + // a naive hashing via the string representation + const auto& h = hash(); + llvm::SmallVector buf; + llvm::raw_svector_ostream os(buf); + j.dump(os); + return h(os.str()); +} + +} // namespace std diff --git a/src/main/native/cpp/support/json_binary_reader.cpp b/src/main/native/cpp/support/json_binary_reader.cpp new file mode 100644 index 0000000000..551b1ddb15 --- /dev/null +++ b/src/main/native/cpp/support/json_binary_reader.cpp @@ -0,0 +1,1233 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#define WPI_JSON_IMPLEMENTATION +#include "support/json.h" + +#include + +#include "llvm/Format.h" +#include "llvm/raw_ostream.h" +#include "support/raw_istream.h" + +using namespace wpi; + +namespace { + +/*! +@brief deserialization of CBOR and MessagePack values +*/ +class binary_reader +{ + using value_t = json::value_t; + + public: + /*! + @brief create a binary reader + + @param[in] adapter input adapter to read from + */ + explicit binary_reader(wpi::raw_istream& s) + : is(s), is_little_endian(little_endianess()) + { + } + + /*! + @brief create a JSON value from CBOR input + + @param[in] get_char whether a new character should be retrieved from + the input (true, default) or whether the last + read character should be considered instead + + @return JSON value created from CBOR input + + @throw parse_error.110 if input ended unexpectedly + @throw parse_error.112 if unsupported byte was read + */ + json parse_cbor(bool get_char = true); + + /*! + @brief create a JSON value from MessagePack input + + @return JSON value created from MessagePack input + + @throw parse_error.110 if input ended unexpectedly + @throw parse_error.112 if unsupported byte was read + */ + json parse_msgpack(); + + /*! + @brief determine system byte order + + @return true iff system's byte order is little endian + + @note from http://stackoverflow.com/a/1001328/266378 + */ + static bool little_endianess() noexcept + { + int num = 1; + return (*reinterpret_cast(&num) == 1); + } + + private: + /*! + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns + `std::char_traits::eof()` in that case. + + @return character read from the input + */ + int get() + { + ++chars_read; + unsigned char c; + is.read(c); + if (is.has_error()) + { + current = std::char_traits::eof(); + } + else + { + current = c; + } + return current; + } + + /* + @brief read a number from the input + + @tparam T the type of the number + + @return number of type @a T + + @note This function needs to respect the system's endianess, because + bytes in CBOR and MessagePack are stored in network order (big + endian) and therefore need reordering on little endian systems. + + @throw parse_error.110 if input has less than `sizeof(T)` bytes + */ + template + T get_number() + { + // step 1: read input into array with system's byte order + std::array vec; + for (size_t i = 0; i < sizeof(T); ++i) + { + get(); + check_eof(); + + // reverse byte order prior to conversion if necessary + if (is_little_endian) + { + vec[sizeof(T) - i - 1] = static_cast(current); + } + else + { + vec[i] = static_cast(current); + } + } + + // step 2: convert array into number of type T and return + T result; + std::memcpy(&result, vec.data(), sizeof(T)); + return result; + } + + /*! + @brief create a string by reading characters from the input + + @param[in] len number of bytes to read + + @return string created by reading @a len bytes + + @throw parse_error.110 if input has less than @a len bytes + */ + std::string get_string(const size_t len); + + /*! + @brief reads a CBOR string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + Additionally, CBOR's strings with indefinite lengths are supported. + + @return string + + @throw parse_error.110 if input ended + @throw parse_error.113 if an unexpexted byte is read + */ + std::string get_cbor_string(); + + /*! + @brief reads a MessagePack string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + + @return string + + @throw parse_error.110 if input ended + @throw parse_error.113 if an unexpexted byte is read + */ + std::string get_msgpack_string(); + + /*! + @brief check if input ended + @throw parse_error.110 if input ended + */ + void check_eof() const + { + if (JSON_UNLIKELY(current == std::char_traits::eof())) + { + JSON_THROW(json::parse_error::create(110, chars_read, "unexpected end of input")); + } + } + + private: + /// input adapter + wpi::raw_istream& is; + + /// the current character + int current = std::char_traits::eof(); + + /// the number of characters read + size_t chars_read = 0; + + /// whether we can assume little endianess + const bool is_little_endian = true; +}; + +} // anonymous namespace + +json binary_reader::parse_cbor(bool get_char) +{ + switch (get_char ? get() : current) + { + // EOF + case std::char_traits::eof(): + { + JSON_THROW(json::parse_error::create(110, chars_read, "unexpected end of input")); + } + + // Integer 0x00..0x17 (0..23) + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0a: + case 0x0b: + case 0x0c: + case 0x0d: + case 0x0e: + case 0x0f: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + { + return static_cast(current); + } + + case 0x18: // Unsigned integer (one-byte uint8_t follows) + { + return get_number(); + } + + case 0x19: // Unsigned integer (two-byte uint16_t follows) + { + return get_number(); + } + + case 0x1a: // Unsigned integer (four-byte uint32_t follows) + { + return get_number(); + } + + case 0x1b: // Unsigned integer (eight-byte uint64_t follows) + { + return get_number(); + } + + // Negative integer -1-0x00..-1-0x17 (-1..-24) + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2a: + case 0x2b: + case 0x2c: + case 0x2d: + case 0x2e: + case 0x2f: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + { + return static_cast(0x20 - 1 - current); + } + + case 0x38: // Negative integer (one-byte uint8_t follows) + { + // must be uint8_t ! + return static_cast(-1) - get_number(); + } + + case 0x39: // Negative integer -1-n (two-byte uint16_t follows) + { + return static_cast(-1) - get_number(); + } + + case 0x3a: // Negative integer -1-n (four-byte uint32_t follows) + { + return static_cast(-1) - get_number(); + } + + case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows) + { + return static_cast(-1) - static_cast(get_number()); + } + + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6a: + case 0x6b: + case 0x6c: + case 0x6d: + case 0x6e: + case 0x6f: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) + case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) + case 0x7f: // UTF-8 string (indefinite length) + { + return get_cbor_string(); + } + + // array (0x00..0x17 data items follow) + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8a: + case 0x8b: + case 0x8c: + case 0x8d: + case 0x8e: + case 0x8f: + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + { + json result = value_t::array; + const auto len = static_cast(current & 0x1f); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_cbor()); + } + return result; + } + + case 0x98: // array (one-byte uint8_t for n follows) + { + json result = value_t::array; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_cbor()); + } + return result; + } + + case 0x99: // array (two-byte uint16_t for n follow) + { + json result = value_t::array; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_cbor()); + } + return result; + } + + case 0x9a: // array (four-byte uint32_t for n follow) + { + json result = value_t::array; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_cbor()); + } + return result; + } + + case 0x9b: // array (eight-byte uint64_t for n follow) + { + json result = value_t::array; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_cbor()); + } + return result; + } + + case 0x9f: // array (indefinite length) + { + json result = value_t::array; + while (get() != 0xff) + { + result.push_back(parse_cbor(false)); + } + return result; + } + + // map (0x00..0x17 pairs of data items follow) + case 0xa0: + case 0xa1: + case 0xa2: + case 0xa3: + case 0xa4: + case 0xa5: + case 0xa6: + case 0xa7: + case 0xa8: + case 0xa9: + case 0xaa: + case 0xab: + case 0xac: + case 0xad: + case 0xae: + case 0xaf: + case 0xb0: + case 0xb1: + case 0xb2: + case 0xb3: + case 0xb4: + case 0xb5: + case 0xb6: + case 0xb7: + { + json result = value_t::object; + const auto len = static_cast(current & 0x1f); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_cbor_string(); + result[key] = parse_cbor(); + } + return result; + } + + case 0xb8: // map (one-byte uint8_t for n follows) + { + json result = value_t::object; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_cbor_string(); + result[key] = parse_cbor(); + } + return result; + } + + case 0xb9: // map (two-byte uint16_t for n follow) + { + json result = value_t::object; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_cbor_string(); + result[key] = parse_cbor(); + } + return result; + } + + case 0xba: // map (four-byte uint32_t for n follow) + { + json result = value_t::object; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_cbor_string(); + result[key] = parse_cbor(); + } + return result; + } + + case 0xbb: // map (eight-byte uint64_t for n follow) + { + json result = value_t::object; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_cbor_string(); + result[key] = parse_cbor(); + } + return result; + } + + case 0xbf: // map (indefinite length) + { + json result = value_t::object; + while (get() != 0xff) + { + auto key = get_cbor_string(); + result[key] = parse_cbor(); + } + return result; + } + + case 0xf4: // false + { + return false; + } + + case 0xf5: // true + { + return true; + } + + case 0xf6: // null + { + return value_t::null; + } + + case 0xf9: // Half-Precision Float (two-byte IEEE 754) + { + const int byte1 = get(); + check_eof(); + const int byte2 = get(); + check_eof(); + + // 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 + // easy to include at least decoding support for them even + // without such support. An example of a small decoder for + // half-precision floating-point numbers in the C language + // is shown in Fig. 3. + const int half = (byte1 << 8) + byte2; + const int exp = (half >> 10) & 0x1f; + const int mant = half & 0x3ff; + double val; + if (exp == 0) + { + val = std::ldexp(mant, -24); + } + else if (exp != 31) + { + val = std::ldexp(mant + 1024, exp - 25); + } + else + { + val = mant == 0 + ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + } + return (half & 0x8000) != 0 ? -val : val; + } + + case 0xfa: // Single-Precision Float (four-byte IEEE 754) + { + return get_number(); + } + + case 0xfb: // Double-Precision Float (eight-byte IEEE 754) + { + return get_number(); + } + + default: // anything else (0xFF is handled inside the other types) + { + std::string s; + llvm::raw_string_ostream ss(s); + ss << "error reading CBOR; last byte: "; + ss << llvm::format_hex(current, 2); + JSON_THROW(json::parse_error::create(112, chars_read, ss.str())); + } + } +} + +std::string binary_reader::get_cbor_string() +{ + check_eof(); + + switch (current) + { + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6a: + case 0x6b: + case 0x6c: + case 0x6d: + case 0x6e: + case 0x6f: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + const auto len = static_cast(current & 0x1f); + return get_string(len); + } + + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + case 0x7f: // UTF-8 string (indefinite length) + { + std::string result; + while (get() != 0xff) + { + check_eof(); + result.append(1, static_cast(current)); + } + return result; + } + + default: + { + std::string s; + llvm::raw_string_ostream ss(s); + ss << "expected a CBOR string; last byte: "; + ss << llvm::format_hex(current, 2); + JSON_THROW(json::parse_error::create(113, chars_read, ss.str())); + } + } +} + +json binary_reader::parse_msgpack() +{ + switch (get()) + { + // EOF + case std::char_traits::eof(): + { + JSON_THROW(json::parse_error::create(110, chars_read, "unexpected end of input")); + } + + // positive fixint + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0a: + case 0x0b: + case 0x0c: + case 0x0d: + case 0x0e: + case 0x0f: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1a: + case 0x1b: + case 0x1c: + case 0x1d: + case 0x1e: + case 0x1f: + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2a: + case 0x2b: + case 0x2c: + case 0x2d: + case 0x2e: + case 0x2f: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4a: + case 0x4b: + case 0x4c: + case 0x4d: + case 0x4e: + case 0x4f: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5a: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x5e: + case 0x5f: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6a: + case 0x6b: + case 0x6c: + case 0x6d: + case 0x6e: + case 0x6f: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7a: + case 0x7b: + case 0x7c: + case 0x7d: + case 0x7e: + case 0x7f: + { + return static_cast(current); + } + + // fixmap + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8a: + case 0x8b: + case 0x8c: + case 0x8d: + case 0x8e: + case 0x8f: + { + json result = value_t::object; + const auto len = static_cast(current & 0x0f); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_msgpack_string(); + result[key] = parse_msgpack(); + } + return result; + } + + // fixarray + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + case 0x98: + case 0x99: + case 0x9a: + case 0x9b: + case 0x9c: + case 0x9d: + case 0x9e: + case 0x9f: + { + json result = value_t::array; + const auto len = static_cast(current & 0x0f); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_msgpack()); + } + return result; + } + + // fixstr + case 0xa0: + case 0xa1: + case 0xa2: + case 0xa3: + case 0xa4: + case 0xa5: + case 0xa6: + case 0xa7: + case 0xa8: + case 0xa9: + case 0xaa: + case 0xab: + case 0xac: + case 0xad: + case 0xae: + case 0xaf: + case 0xb0: + case 0xb1: + case 0xb2: + case 0xb3: + case 0xb4: + case 0xb5: + case 0xb6: + case 0xb7: + case 0xb8: + case 0xb9: + case 0xba: + case 0xbb: + case 0xbc: + case 0xbd: + case 0xbe: + case 0xbf: + { + return get_msgpack_string(); + } + + case 0xc0: // nil + { + return value_t::null; + } + + case 0xc2: // false + { + return false; + } + + case 0xc3: // true + { + return true; + } + + case 0xca: // float 32 + { + return get_number(); + } + + case 0xcb: // float 64 + { + return get_number(); + } + + case 0xcc: // uint 8 + { + return get_number(); + } + + case 0xcd: // uint 16 + { + return get_number(); + } + + case 0xce: // uint 32 + { + return get_number(); + } + + case 0xcf: // uint 64 + { + return get_number(); + } + + case 0xd0: // int 8 + { + return get_number(); + } + + case 0xd1: // int 16 + { + return get_number(); + } + + case 0xd2: // int 32 + { + return get_number(); + } + + case 0xd3: // int 64 + { + return get_number(); + } + + case 0xd9: // str 8 + case 0xda: // str 16 + case 0xdb: // str 32 + { + return get_msgpack_string(); + } + + case 0xdc: // array 16 + { + json result = value_t::array; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_msgpack()); + } + return result; + } + + case 0xdd: // array 32 + { + json result = value_t::array; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + result.push_back(parse_msgpack()); + } + return result; + } + + case 0xde: // map 16 + { + json result = value_t::object; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_msgpack_string(); + result[key] = parse_msgpack(); + } + return result; + } + + case 0xdf: // map 32 + { + json result = value_t::object; + const auto len = static_cast(get_number()); + for (size_t i = 0; i < len; ++i) + { + get(); + auto key = get_msgpack_string(); + result[key] = parse_msgpack(); + } + return result; + } + + // positive fixint + case 0xe0: + case 0xe1: + case 0xe2: + case 0xe3: + case 0xe4: + case 0xe5: + case 0xe6: + case 0xe7: + case 0xe8: + case 0xe9: + case 0xea: + case 0xeb: + case 0xec: + case 0xed: + case 0xee: + case 0xef: + case 0xf0: + case 0xf1: + case 0xf2: + case 0xf3: + case 0xf4: + case 0xf5: + case 0xf6: + case 0xf7: + case 0xf8: + case 0xf9: + case 0xfa: + case 0xfb: + case 0xfc: + case 0xfd: + case 0xfe: + case 0xff: + { + return static_cast(current); + } + + default: // anything else + { + std::string s; + llvm::raw_string_ostream ss(s); + ss << "error reading MessagePack; last byte: "; + ss << llvm::format_hex(current, 2); + JSON_THROW(json::parse_error::create(112, chars_read, ss.str())); + } + } +} + +std::string binary_reader::get_msgpack_string() +{ + check_eof(); + + switch (current) + { + // fixstr + case 0xa0: + case 0xa1: + case 0xa2: + case 0xa3: + case 0xa4: + case 0xa5: + case 0xa6: + case 0xa7: + case 0xa8: + case 0xa9: + case 0xaa: + case 0xab: + case 0xac: + case 0xad: + case 0xae: + case 0xaf: + case 0xb0: + case 0xb1: + case 0xb2: + case 0xb3: + case 0xb4: + case 0xb5: + case 0xb6: + case 0xb7: + case 0xb8: + case 0xb9: + case 0xba: + case 0xbb: + case 0xbc: + case 0xbd: + case 0xbe: + case 0xbf: + { + const auto len = static_cast(current & 0x1f); + return get_string(len); + } + + case 0xd9: // str 8 + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + case 0xda: // str 16 + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + case 0xdb: // str 32 + { + const auto len = static_cast(get_number()); + return get_string(len); + } + + default: + { + std::string s; + llvm::raw_string_ostream ss(s); + ss << "expected a MessagePack string; last byte: "; + ss << llvm::format_hex(current, 2); + JSON_THROW(json::parse_error::create(113, chars_read, ss.str())); + } + } +} + +std::string binary_reader::get_string(const size_t len) +{ + std::string result; + for (size_t i = 0; i < len; ++i) + { + get(); + check_eof(); + result.append(1, static_cast(current)); + } + return result; +} + +json json::from_cbor(wpi::raw_istream& is) +{ + binary_reader br(is); + return br.parse_cbor(); +} + +json json::from_cbor(llvm::StringRef s) +{ + wpi::raw_mem_istream is(s.data(), s.size()); + binary_reader br(is); + return br.parse_cbor(); +} + +json json::from_msgpack(wpi::raw_istream& is) +{ + binary_reader br(is); + return br.parse_msgpack(); +} + +json json::from_msgpack(llvm::StringRef s) +{ + wpi::raw_mem_istream is(s.data(), s.size()); + binary_reader br(is); + return br.parse_msgpack(); +} diff --git a/src/main/native/cpp/support/json_binary_writer.cpp b/src/main/native/cpp/support/json_binary_writer.cpp new file mode 100644 index 0000000000..86a98115bf --- /dev/null +++ b/src/main/native/cpp/support/json_binary_writer.cpp @@ -0,0 +1,668 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#define WPI_JSON_IMPLEMENTATION +#include "support/json.h" + +#include +#include // lconv, localeconv +#include // locale +#include // accumulate + +#include "llvm/raw_ostream.h" +#include "llvm/SmallString.h" +#include "llvm/StringExtras.h" + +using namespace wpi; + +/*! +@brief serialization to CBOR and MessagePack values +*/ +class json::binary_writer +{ + public: + /*! + @brief create a binary writer + + @param[in] adapter output adapter to write to + */ + explicit binary_writer(llvm::raw_ostream& s) + : is_little_endian(little_endianess()), o(s) + { + } + + /*! + @brief[in] j JSON value to serialize + */ + void write_cbor(const json& j); + + /*! + @brief[in] j JSON value to serialize + */ + void write_msgpack(const json& j); + + /*! + @brief determine system byte order + + @return true iff system's byte order is little endian + + @note from http://stackoverflow.com/a/1001328/266378 + */ + static bool little_endianess() noexcept + { + int num = 1; + return (*reinterpret_cast(&num) == 1); + } + + private: + /*! + @brief[in] str string to serialize + */ + void write_cbor_string(llvm::StringRef str); + + /*! + @brief[in] str string to serialize + */ + void write_msgpack_string(llvm::StringRef str); + + /* + @brief write a number to output input + + @param[in] n number of type @a T + @tparam T the type of the number + + @note This function needs to respect the system's endianess, because + bytes in CBOR and MessagePack are stored in network order (big + endian) and therefore need reordering on little endian systems. + */ + template + void write_number(T n) + { + // step 1: write number to array of length T + std::array vec; + std::memcpy(vec.data(), &n, sizeof(T)); + + // step 2: write array to output (with possible reordering) + for (size_t i = 0; i < sizeof(T); ++i) + { + // reverse byte order prior to conversion if necessary + if (is_little_endian) + { + o << static_cast(vec[sizeof(T) - i - 1]); + } + else + { + o << static_cast(vec[i]); + } + } + } + + private: + /// whether we can assume little endianess + const bool is_little_endian = true; + + /// the output + llvm::raw_ostream& o; +}; + +void json::binary_writer::write_cbor(const json& j) +{ + switch (j.type()) + { + case value_t::null: + { + o << static_cast(0xf6); + break; + } + + case value_t::boolean: + { + o << static_cast(j.m_value.boolean ? 0xf5 : 0xf4); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // CBOR does not differentiate between positive signed + // integers and unsigned integers. Therefore, we used the + // code from the value_t::number_unsigned case here. + if (j.m_value.number_integer <= 0x17) + { + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + o << static_cast(0x18); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + o << static_cast(0x19); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + o << static_cast(0x1a); + write_number(static_cast(j.m_value.number_integer)); + } + else + { + o << static_cast(0x1b); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + // The conversions below encode the sign in the first + // byte, and the value is converted to a positive number. + const auto positive_number = -1 - j.m_value.number_integer; + if (j.m_value.number_integer >= -24) + { + write_number(static_cast(0x20 + positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + o << static_cast(0x38); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + o << static_cast(0x39); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + o << static_cast(0x3a); + write_number(static_cast(positive_number)); + } + else + { + o << static_cast(0x3b); + write_number(static_cast(positive_number)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= 0x17) + { + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + o << static_cast(0x18); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + o << static_cast(0x19); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + o << static_cast(0x1a); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + o << static_cast(0x1b); + write_number(static_cast(j.m_value.number_unsigned)); + } + break; + } + + case value_t::number_float: + { + // Double-Precision Float + o << static_cast(0xfb); + write_number(j.m_value.number_float); + break; + } + + case value_t::string: + { + write_cbor_string(*j.m_value.string); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 0x17) + { + write_number(static_cast(0x80 + N)); + } + else if (N <= 0xff) + { + o << static_cast(0x98); + write_number(static_cast(N)); + } + else if (N <= 0xffff) + { + o << static_cast(0x99); + write_number(static_cast(N)); + } + else if (N <= 0xffffffff) + { + o << static_cast(0x9a); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= 0xffffffffffffffff) + { + o << static_cast(0x9b); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_cbor(el); + } + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 0x17) + { + write_number(static_cast(0xa0 + N)); + } + else if (N <= 0xff) + { + o << static_cast(0xb8); + write_number(static_cast(N)); + } + else if (N <= 0xffff) + { + o << static_cast(0xb9); + write_number(static_cast(N)); + } + else if (N <= 0xffffffff) + { + o << static_cast(0xba); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= 0xffffffffffffffff) + { + o << static_cast(0xbb); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_cbor_string(el.first()); + write_cbor(el.second); + } + break; + } + + default: + { + break; + } + } +} + +void json::binary_writer::write_cbor_string(llvm::StringRef str) +{ + // step 1: write control byte and the string length + const auto N = str.size(); + if (N <= 0x17) + { + write_number(static_cast(0x60 + N)); + } + else if (N <= 0xff) + { + o << static_cast(0x78); + write_number(static_cast(N)); + } + else if (N <= 0xffff) + { + o << static_cast(0x79); + write_number(static_cast(N)); + } + else if (N <= 0xffffffff) + { + o << static_cast(0x7a); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= 0xffffffffffffffff) + { + o << static_cast(0x7b); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write the string + o << str; +} + +void json::binary_writer::write_msgpack(const json& j) +{ + switch (j.type()) + { + case value_t::null: + { + // nil + o << static_cast(0xc0); + break; + } + + case value_t::boolean: + { + // true and false + o << static_cast(j.m_value.boolean ? 0xc3 : 0xc2); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // MessagePack does not differentiate between positive + // signed integers and unsigned integers. Therefore, we + // used the code from the value_t::number_unsigned case + // here. + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + o << static_cast(0xcc); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + o << static_cast(0xcd); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + o << static_cast(0xce); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + o << static_cast(0xcf); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + if (j.m_value.number_integer >= -32) + { + // negative fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 8 + o << static_cast(0xd0); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 16 + o << static_cast(0xd1); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 32 + o << static_cast(0xd2); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 64 + o << static_cast(0xd3); + write_number(static_cast(j.m_value.number_integer)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + o << static_cast(0xcc); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + o << static_cast(0xcd); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + o << static_cast(0xce); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + o << static_cast(0xcf); + write_number(static_cast(j.m_value.number_integer)); + } + break; + } + + case value_t::number_float: + { + // float 64 + o << static_cast(0xcb); + write_number(j.m_value.number_float); + break; + } + + case value_t::string: + { + write_msgpack_string(*j.m_value.string); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 15) + { + // fixarray + write_number(static_cast(0x90 | N)); + } + else if (N <= 0xffff) + { + // array 16 + o << static_cast(0xdc); + write_number(static_cast(N)); + } + else if (N <= 0xffffffff) + { + // array 32 + o << static_cast(0xdd); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_msgpack(el); + } + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 15) + { + // fixmap + write_number(static_cast(0x80 | (N & 0xf))); + } + else if (N <= 65535) + { + // map 16 + o << static_cast(0xde); + write_number(static_cast(N)); + } + else if (N <= 4294967295) + { + // map 32 + o << static_cast(0xdf); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_msgpack_string(el.first()); + write_msgpack(el.second); + } + break; + } + + default: + { + break; + } + } +} + +void json::binary_writer::write_msgpack_string(llvm::StringRef str) +{ + // step 1: write control byte and the string length + const auto N = str.size(); + if (N <= 31) + { + // fixstr + write_number(static_cast(0xa0 | N)); + } + else if (N <= 255) + { + // str 8 + o << static_cast(0xd9); + write_number(static_cast(N)); + } + else if (N <= 65535) + { + // str 16 + o << static_cast(0xda); + write_number(static_cast(N)); + } + else if (N <= 4294967295) + { + // str 32 + o << static_cast(0xdb); + write_number(static_cast(N)); + } + + // step 2: write the string + o << str; +} + +void json::to_cbor(llvm::raw_ostream& os, const json& j) +{ + binary_writer bw(os); + bw.write_cbor(j); +} + +llvm::StringRef json::to_cbor(const json& j, llvm::SmallVectorImpl buf) +{ + llvm::raw_svector_ostream os(buf); + binary_writer bw(os); + bw.write_cbor(j); + return os.str(); +} + +std::string json::to_cbor(const json& j) +{ + std::string s; + llvm::raw_string_ostream os(s); + binary_writer bw(os); + bw.write_cbor(j); + os.flush(); + return s; +} + +void json::to_msgpack(llvm::raw_ostream& os, const json& j) +{ + binary_writer bw(os); + bw.write_msgpack(j); +} + +llvm::StringRef json::to_msgpack(const json& j, llvm::SmallVectorImpl buf) +{ + llvm::raw_svector_ostream os(buf); + binary_writer bw(os); + bw.write_msgpack(j); + return os.str(); +} + +std::string json::to_msgpack(const json& j) +{ + std::string s; + llvm::raw_string_ostream os(s); + binary_writer bw(os); + bw.write_msgpack(j); + os.flush(); + return s; +} diff --git a/src/main/native/cpp/support/json_parser.cpp b/src/main/native/cpp/support/json_parser.cpp new file mode 100644 index 0000000000..1ff331392f --- /dev/null +++ b/src/main/native/cpp/support/json_parser.cpp @@ -0,0 +1,2095 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#define WPI_JSON_IMPLEMENTATION +#include "support/json.h" + +#include +#include // lconv, localeconv +#include // locale + +#include "llvm/Format.h" +#include "llvm/raw_ostream.h" +#include "llvm/SmallString.h" +#include "support/raw_istream.h" + +using namespace wpi; + +namespace { + +////////////////////// +// lexer and parser // +////////////////////// + +/*! +@brief lexical analysis + +This class organizes the lexical analysis during JSON deserialization. +*/ +class lexer +{ + public: + /// token types for the parser + enum class token_type + { + uninitialized, ///< indicating the scanner is uninitialized + literal_true, ///< the `true` literal + literal_false, ///< the `false` literal + literal_null, ///< the `null` literal + value_string, ///< a string -- use get_string() for actual value + value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value + value_integer, ///< a signed integer -- use get_number_integer() for actual value + value_float, ///< an floating point number -- use get_number_float() for actual value + begin_array, ///< the character for array begin `[` + begin_object, ///< the character for object begin `{` + end_array, ///< the character for array end `]` + end_object, ///< the character for object end `}` + name_separator, ///< the name separator `:` + value_separator, ///< the value separator `,` + parse_error, ///< indicating a parse error + end_of_input ///< indicating the end of the input buffer + }; + + /// return name of values of type token_type (only used for errors) + static const char* token_type_name(const token_type t) noexcept; + + explicit lexer(wpi::raw_istream& s) + : is(s), decimal_point_char(get_decimal_point()) + {} + + private: + ///////////////////// + // locales + ///////////////////// + + /// return the locale-dependent decimal point + static char get_decimal_point() noexcept + { + const auto loc = localeconv(); + assert(loc != nullptr); + return (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0]; + } + + ///////////////////// + // scan functions + ///////////////////// + + /*! + @brief get codepoint from 4 hex characters following `\u` + + @return codepoint or -1 in case of an error (e.g. EOF or non-hex + character) + */ + int get_codepoint(); + + /*! + @brief create diagnostic representation of a codepoint + @return string "U+XXXX" for codepoint XXXX + */ + static std::string codepoint_to_string(int codepoint); + + /*! + @brief scan a string literal + + This function scans a string according to Sect. 7 of RFC 7159. While + scanning, bytes are escaped and copied into buffer yytext. Then the + function returns successfully. + + @return token_type::value_string if string could be successfully + scanned, token_type::parse_error otherwise + + @note In case of errors, variable error_message contains a textual + description. + */ + token_type scan_string(); + + static void strtof(float& f, const char* str, char** endptr) noexcept + { + f = std::strtof(str, endptr); + } + + static void strtof(double& f, const char* str, char** endptr) noexcept + { + f = std::strtod(str, endptr); + } + + static void strtof(long double& f, const char* str, char** endptr) noexcept + { + f = std::strtold(str, endptr); + } + + /*! + @brief scan a number literal + + This function scans a string according to Sect. 6 of RFC 7159. + + The function is realized with a deterministic finite state machine + derived from the grammar described in RFC 7159. Starting in state + "init", the input is read and used to determined the next state. Only + state "done" accepts the number. State "error" is a trap state to model + errors. In the table below, "anything" means any character but the ones + listed before. + + state | 0 | 1-9 | e E | + | - | . | anything + ---------|----------|----------|----------|---------|---------|----------|----------- + init | zero | any1 | [error] | [error] | minus | [error] | [error] + minus | zero | any1 | [error] | [error] | [error] | [error] | [error] + zero | done | done | exponent | done | done | decimal1 | done + any1 | any1 | any1 | exponent | done | done | decimal1 | done + decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error] + decimal2 | decimal2 | decimal2 | exponent | done | done | done | done + exponent | any2 | any2 | [error] | sign | sign | [error] | [error] + sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] + any2 | any2 | any2 | done | done | done | done | done + + The state machine is realized with one label per state (prefixed with + "scan_number_") and `goto` statements between them. The state machine + contains cycles, but any cycle can be left when EOF is read. Therefore, + the function is guaranteed to terminate. + + During scanning, the read bytes are stored in yytext. This string is + then converted to a signed integer, an unsigned integer, or a + floating-point number. + + @return token_type::value_unsigned, token_type::value_integer, or + token_type::value_float if number could be successfully scanned, + token_type::parse_error otherwise + + @note The scanner is independent of the current locale. Internally, the + locale's decimal point is used instead of `.` to work with the + locale-dependent converters. + */ + token_type scan_number(); + + token_type scan_true(); + token_type scan_false(); + token_type scan_null(); + + ///////////////////// + // input management + ///////////////////// + + /// reset yytext + void reset() noexcept + { + token_string.resize(0); + yytext.resize(0); + } + + /// get a character from the input + int get() + { + ++chars_read; + if (next_unget) + { + next_unget = false; + return current; + } + char c; + is.read(c); + if (is.has_error()) + { + current = std::char_traits::eof(); + } + else + { + current = static_cast(c); + token_string.push_back(c); + } + return current; + } + + /// add a character to yytext + void add(int c) + { + yytext.push_back(static_cast(c)); + } + + public: + ///////////////////// + // value getters + ///////////////////// + + /// return integer value + std::int64_t get_number_integer() const noexcept + { + return value_integer; + } + + /// return unsigned integer value + std::uint64_t get_number_unsigned() const noexcept + { + return value_unsigned; + } + + /// return floating-point value + double get_number_float() const noexcept + { + return value_float; + } + + /// return string value + llvm::StringRef get_string() + { + return yytext.str(); + } + + ///////////////////// + // diagnostics + ///////////////////// + + /// return position of last read token + size_t get_position() const noexcept + { + return chars_read; + } + + /// return the last read token (for errors only) + std::string get_token_string() const; + + /// return syntax error message + const std::string& get_error_message() const noexcept + { + return error_message; + } + + ///////////////////// + // actual scanner + ///////////////////// + + token_type scan(); + + private: + /// input adapter + wpi::raw_istream& is; + + /// the current character + int current = std::char_traits::eof(); + + /// whether get() should return the last character again + bool next_unget = false; + + /// the number of characters read + size_t chars_read = 0; + + /// buffer for raw byte sequence of the current token + llvm::SmallString<128> token_string; + + /// buffer for variable-length tokens (numbers, strings) + llvm::SmallString<128> yytext; + + /// a description of occurred lexer errors + std::string error_message = ""; + + // number values + std::int64_t value_integer = 0; + std::uint64_t value_unsigned = 0; + double value_float = 0; + + /// the decimal point + const char decimal_point_char = '.'; +}; + +} // anonymous namespace + +const char* lexer::token_type_name(const token_type t) noexcept +{ + switch (t) + { + case token_type::uninitialized: + return ""; + case token_type::literal_true: + return "true literal"; + case token_type::literal_false: + return "false literal"; + case token_type::literal_null: + return "null literal"; + case token_type::value_string: + return "string literal"; + case lexer::token_type::value_unsigned: + case lexer::token_type::value_integer: + case lexer::token_type::value_float: + return "number literal"; + case token_type::begin_array: + return "'['"; + case token_type::begin_object: + return "'{'"; + case token_type::end_array: + return "']'"; + case token_type::end_object: + return "'}'"; + case token_type::name_separator: + return "':'"; + case token_type::value_separator: + return "','"; + case token_type::parse_error: + return ""; + case token_type::end_of_input: + return "end of input"; + default: + { + // catch non-enum values + return "unknown token"; // LCOV_EXCL_LINE + } + } +} + +int lexer::get_codepoint() +{ + // this function only makes sense after reading `\u` + assert(current == 'u'); + int codepoint = 0; + + // byte 1: \uXxxx + switch (get()) + { + case '0': + break; + case '1': + codepoint += 0x1000; + break; + case '2': + codepoint += 0x2000; + break; + case '3': + codepoint += 0x3000; + break; + case '4': + codepoint += 0x4000; + break; + case '5': + codepoint += 0x5000; + break; + case '6': + codepoint += 0x6000; + break; + case '7': + codepoint += 0x7000; + break; + case '8': + codepoint += 0x8000; + break; + case '9': + codepoint += 0x9000; + break; + case 'A': + case 'a': + codepoint += 0xa000; + break; + case 'B': + case 'b': + codepoint += 0xb000; + break; + case 'C': + case 'c': + codepoint += 0xc000; + break; + case 'D': + case 'd': + codepoint += 0xd000; + break; + case 'E': + case 'e': + codepoint += 0xe000; + break; + case 'F': + case 'f': + codepoint += 0xf000; + break; + default: + return -1; + } + + // byte 2: \uxXxx + switch (get()) + { + case '0': + break; + case '1': + codepoint += 0x0100; + break; + case '2': + codepoint += 0x0200; + break; + case '3': + codepoint += 0x0300; + break; + case '4': + codepoint += 0x0400; + break; + case '5': + codepoint += 0x0500; + break; + case '6': + codepoint += 0x0600; + break; + case '7': + codepoint += 0x0700; + break; + case '8': + codepoint += 0x0800; + break; + case '9': + codepoint += 0x0900; + break; + case 'A': + case 'a': + codepoint += 0x0a00; + break; + case 'B': + case 'b': + codepoint += 0x0b00; + break; + case 'C': + case 'c': + codepoint += 0x0c00; + break; + case 'D': + case 'd': + codepoint += 0x0d00; + break; + case 'E': + case 'e': + codepoint += 0x0e00; + break; + case 'F': + case 'f': + codepoint += 0x0f00; + break; + default: + return -1; + } + + // byte 3: \uxxXx + switch (get()) + { + case '0': + break; + case '1': + codepoint += 0x0010; + break; + case '2': + codepoint += 0x0020; + break; + case '3': + codepoint += 0x0030; + break; + case '4': + codepoint += 0x0040; + break; + case '5': + codepoint += 0x0050; + break; + case '6': + codepoint += 0x0060; + break; + case '7': + codepoint += 0x0070; + break; + case '8': + codepoint += 0x0080; + break; + case '9': + codepoint += 0x0090; + break; + case 'A': + case 'a': + codepoint += 0x00a0; + break; + case 'B': + case 'b': + codepoint += 0x00b0; + break; + case 'C': + case 'c': + codepoint += 0x00c0; + break; + case 'D': + case 'd': + codepoint += 0x00d0; + break; + case 'E': + case 'e': + codepoint += 0x00e0; + break; + case 'F': + case 'f': + codepoint += 0x00f0; + break; + default: + return -1; + } + + // byte 4: \uxxxX + switch (get()) + { + case '0': + break; + case '1': + codepoint += 0x0001; + break; + case '2': + codepoint += 0x0002; + break; + case '3': + codepoint += 0x0003; + break; + case '4': + codepoint += 0x0004; + break; + case '5': + codepoint += 0x0005; + break; + case '6': + codepoint += 0x0006; + break; + case '7': + codepoint += 0x0007; + break; + case '8': + codepoint += 0x0008; + break; + case '9': + codepoint += 0x0009; + break; + case 'A': + case 'a': + codepoint += 0x000a; + break; + case 'B': + case 'b': + codepoint += 0x000b; + break; + case 'C': + case 'c': + codepoint += 0x000c; + break; + case 'D': + case 'd': + codepoint += 0x000d; + break; + case 'E': + case 'e': + codepoint += 0x000e; + break; + case 'F': + case 'f': + codepoint += 0x000f; + break; + default: + return -1; + } + + return codepoint; +} + +std::string lexer::codepoint_to_string(int codepoint) +{ + std::string s; + llvm::raw_string_ostream ss(s); + ss << "U+" << llvm::format_hex_no_prefix(codepoint, 4, true); + return ss.str(); +} + +lexer::token_type lexer::scan_string() +{ + // reset yytext (ignore opening quote) + reset(); + + // we entered the function by reading an open quote + assert(current == '\"'); + + while (true) + { + // get next character + get(); + + switch (current) + { + // end of file while parsing string + case std::char_traits::eof(): + { + error_message = "invalid string: missing closing quote"; + return token_type::parse_error; + } + + // closing quote + case '\"': + { + // terminate yytext + return token_type::value_string; + } + + // escapes + case '\\': + { + switch (get()) + { + // quotation mark + case '\"': + add('\"'); + break; + // reverse solidus + case '\\': + add('\\'); + break; + // solidus + case '/': + add('/'); + break; + // backspace + case 'b': + add('\b'); + break; + // form feed + case 'f': + add('\f'); + break; + // line feed + case 'n': + add('\n'); + break; + // carriage return + case 'r': + add('\r'); + break; + // tab + case 't': + add('\t'); + break; + + // unicode escapes + case 'u': + { + int codepoint; + int codepoint1 = get_codepoint(); + + if (JSON_UNLIKELY(codepoint1 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if code point is a high surrogate + if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) + { + // expect next \uxxxx entry + if (JSON_LIKELY(get() == '\\' && get() == 'u')) + { + const int codepoint2 = get_codepoint(); + + if (JSON_UNLIKELY(codepoint2 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if codepoint2 is a low surrogate + if (JSON_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) + { + codepoint = + // high surrogate occupies the most significant 22 bits + (codepoint1 << 10) + // low surrogate occupies the least significant 15 bits + + codepoint2 + // there is still the 0xD800, 0xDC00 and 0x10000 noise + // in the result so we have to subtract with: + // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 + - 0x35FDC00; + } + else + { + error_message = "invalid string: surrogate " + codepoint_to_string(codepoint1) + " must be followed by U+DC00..U+DFFF instead of " + codepoint_to_string(codepoint2); + return token_type::parse_error; + } + } + else + { + error_message = "invalid string: surrogate " + codepoint_to_string(codepoint1) + " must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + if (JSON_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) + { + error_message = "invalid string: surrogate " + codepoint_to_string(codepoint1) + " must follow U+D800..U+DBFF"; + return token_type::parse_error; + } + + // only work with first code point + codepoint = codepoint1; + } + + // result of the above calculation yields a proper codepoint + assert(0x00 <= codepoint && codepoint <= 0x10FFFF); + + // translate code point to bytes + if (codepoint < 0x80) + { + // 1-byte characters: 0xxxxxxx (ASCII) + add(codepoint); + } + else if (codepoint <= 0x7ff) + { + // 2-byte characters: 110xxxxx 10xxxxxx + add(0xC0 | (codepoint >> 6)); + add(0x80 | (codepoint & 0x3F)); + } + else if (codepoint <= 0xffff) + { + // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx + add(0xE0 | (codepoint >> 12)); + add(0x80 | ((codepoint >> 6) & 0x3F)); + add(0x80 | (codepoint & 0x3F)); + } + else + { + // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + add(0xF0 | (codepoint >> 18)); + add(0x80 | ((codepoint >> 12) & 0x3F)); + add(0x80 | ((codepoint >> 6) & 0x3F)); + add(0x80 | (codepoint & 0x3F)); + } + + break; + } + + // other characters after escape + default: + error_message = "invalid string: forbidden character after backslash"; + return token_type::parse_error; + } + + break; + } + + // invalid control characters + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0a: + case 0x0b: + case 0x0c: + case 0x0d: + case 0x0e: + case 0x0f: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1a: + case 0x1b: + case 0x1c: + case 0x1d: + case 0x1e: + case 0x1f: + { + error_message = "invalid string: control character " + codepoint_to_string(current) + " must be escaped"; + return token_type::parse_error; + } + + // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) + case 0x20: + case 0x21: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2a: + case 0x2b: + case 0x2c: + case 0x2d: + case 0x2e: + case 0x2f: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4a: + case 0x4b: + case 0x4c: + case 0x4d: + case 0x4e: + case 0x4f: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5a: + case 0x5b: + case 0x5d: + case 0x5e: + case 0x5f: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6a: + case 0x6b: + case 0x6c: + case 0x6d: + case 0x6e: + case 0x6f: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7a: + case 0x7b: + case 0x7c: + case 0x7d: + case 0x7e: + case 0x7f: + { + add(current); + break; + } + + // U+0080..U+07FF: bytes C2..DF 80..BF + case 0xc2: + case 0xc3: + case 0xc4: + case 0xc5: + case 0xc6: + case 0xc7: + case 0xc8: + case 0xc9: + case 0xca: + case 0xcb: + case 0xcc: + case 0xcd: + case 0xce: + case 0xcf: + case 0xd0: + case 0xd1: + case 0xd2: + case 0xd3: + case 0xd4: + case 0xd5: + case 0xd6: + case 0xd7: + case 0xd8: + case 0xd9: + case 0xda: + case 0xdb: + case 0xdc: + case 0xdd: + case 0xde: + case 0xdf: + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // U+0800..U+0FFF: bytes E0 A0..BF 80..BF + case 0xe0: + { + add(current); + get(); + if (JSON_LIKELY(0xa0 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF + // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF + case 0xe1: + case 0xe2: + case 0xe3: + case 0xe4: + case 0xe5: + case 0xe6: + case 0xe7: + case 0xe8: + case 0xe9: + case 0xea: + case 0xeb: + case 0xec: + case 0xee: + case 0xef: + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // U+D000..U+D7FF: bytes ED 80..9F 80..BF + case 0xed: + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0x9f)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF + case 0xf0: + { + add(current); + get(); + if (JSON_LIKELY(0x90 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + } + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF + case 0xf1: + case 0xf2: + case 0xf3: + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + } + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF + case 0xf4: + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0x8f)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + get(); + if (JSON_LIKELY(0x80 <= current && current <= 0xbf)) + { + add(current); + continue; + } + } + } + + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + + // remaining bytes (80..C1 and F5..FF) are ill-formed + default: + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + } + } +} + +lexer::token_type lexer::scan_number() +{ + // reset yytext to store the number's bytes + reset(); + + // the type of the parsed number; initially set to unsigned; will be + // 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 + switch (current) + { + case '-': + { + add(current); + goto scan_number_minus; + } + + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + default: + { + // all other characters are rejected outside scan_number() + assert(false); // LCOV_EXCL_LINE + } + } + +scan_number_minus: + // state: we just parsed a leading minus sign + number_type = token_type::value_integer; + switch (get()) + { + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + default: + { + error_message = "invalid number; expected digit after '-'"; + return token_type::parse_error; + } + } + +scan_number_zero: + // state: we just parse a zero (maybe with a leading minus sign) + switch (get()) + { + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + { + goto scan_number_done; + } + } + +scan_number_any1: + // state: we just parsed a number 0-9 (maybe with a leading minus sign) + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + { + goto scan_number_done; + } + } + +scan_number_decimal1: + // state: we just parsed a decimal point + number_type = token_type::value_float; + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + default: + { + error_message = "invalid number; expected digit after '.'"; + return token_type::parse_error; + } + } + +scan_number_decimal2: + // we just parsed at least one number after a decimal point + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + { + goto scan_number_done; + } + } + +scan_number_exponent: + // we just parsed an exponent + number_type = token_type::value_float; + switch (get()) + { + case '+': + case '-': + { + add(current); + goto scan_number_sign; + } + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = "invalid number; expected '+', '-', or digit after exponent"; + return token_type::parse_error; + } + } + +scan_number_sign: + // we just parsed an exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = "invalid number; expected digit after exponent sign"; + return token_type::parse_error; + } + } + +scan_number_any2: + // we just parsed a number after the exponent or exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + goto scan_number_done; + } + } + +scan_number_done: + // unget the character after the number (we only read it to know + // that we are done scanning a number) + --chars_read; + next_unget = true; + + // try to parse integers first and fall back to floats + if (number_type == token_type::value_unsigned) + { + char* endptr = nullptr; + errno = 0; + const auto x = std::strtoull(yytext.c_str(), &endptr, 10); + + // we checked the number format before + assert(endptr == yytext.data() + yytext.size()); + + if (errno == 0) + { + value_unsigned = static_cast(x); + if (value_unsigned == x) + { + return token_type::value_unsigned; + } + } + } + else if (number_type == token_type::value_integer) + { + char* endptr = nullptr; + errno = 0; + const auto x = std::strtoll(yytext.c_str(), &endptr, 10); + + // we checked the number format before + assert(endptr == yytext.data() + yytext.size()); + + if (errno == 0) + { + value_integer = static_cast(x); + if (value_integer == x) + { + return token_type::value_integer; + } + } + } + + // this code is reached if we parse a floating-point number or if + // an integer conversion above failed + strtof(value_float, yytext.c_str(), nullptr); + return token_type::value_float; +} + +lexer::token_type lexer::scan_true() +{ + assert(current == 't'); + if (JSON_LIKELY((get() == 'r' && get() == 'u' && get() == 'e'))) + { + return token_type::literal_true; + } + + error_message = "invalid literal; expected 'true'"; + return token_type::parse_error; +} + +lexer::token_type lexer::scan_false() +{ + assert(current == 'f'); + if (JSON_LIKELY((get() == 'a' && get() == 'l' && get() == 's' && get() == 'e'))) + { + return token_type::literal_false; + } + + error_message = "invalid literal; expected 'false'"; + return token_type::parse_error; +} + +lexer::token_type lexer::scan_null() +{ + assert(current == 'n'); + if (JSON_LIKELY((get() == 'u' && get() == 'l' && get() == 'l'))) + { + return token_type::literal_null; + } + + error_message = "invalid literal; expected 'null'"; + return token_type::parse_error; +} + +std::string lexer::get_token_string() const +{ + // escape control characters + std::string result; + for (auto c : token_string) + { + if (c == '\0' || c == std::char_traits::eof()) + { + // ignore EOF + continue; + } + else if ('\x00' <= c && c <= '\x1f') + { + // escape control characters + result += "<" + codepoint_to_string(c) + ">"; + } + else + { + // add character as is + result.append(1, c); + } + } + + return result; +} + +lexer::token_type lexer::scan() +{ + // read next character and ignore whitespace + do + { + get(); + } + while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); + + switch (current) + { + // structural characters + case '[': + return token_type::begin_array; + case ']': + return token_type::end_array; + case '{': + return token_type::begin_object; + case '}': + return token_type::end_object; + case ':': + return token_type::name_separator; + case ',': + return token_type::value_separator; + + // literals + case 't': + return scan_true(); + case 'f': + return scan_false(); + case 'n': + return scan_null(); + + // string + case '\"': + return scan_string(); + + // number + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return scan_number(); + + // end of input (the null byte is needed when parsing from + // string literals) + case '\0': + case std::char_traits::eof(): + return token_type::end_of_input; + + // error + default: + error_message = "invalid literal"; + return token_type::parse_error; + } +} + +/*! +@brief syntax analysis + +This class implements a recursive decent parser. +*/ +class json::parser +{ + using value_t = json::value_t; + + public: + /// a parser reading from an input adapter + explicit parser(wpi::raw_istream& s, + const parser_callback_t cb = nullptr) + : callback(cb), m_lexer(s) + {} + + /*! + @brief public parser interface + + @param[in] strict whether to expect the last token to be EOF + @return parsed JSON value + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + json parse(bool strict = true); + + /*! + @brief public accept interface + + @param[in] strict whether to expect the last token to be EOF + @return whether the input is a proper JSON text + */ + bool accept(bool strict = true); + + private: + /*! + @brief the actual parser + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + json parse_internal(bool keep); + + /*! + @brief the acutal acceptor + + @invariant 1. The last token is not yet processed. Therefore, the + caller of this function must make sure a token has + been read. + 2. When this function returns, the last token is processed. + That is, the last read character was already considered. + + This invariant makes sure that no token needs to be "unput". + */ + bool accept_internal(); + + /// get next token from lexer + lexer::token_type get_token() + { + last_token = m_lexer.scan(); + return last_token; + } + + /*! + @throw parse_error.101 if expected token did not occur + */ + void expect(lexer::token_type t) const; + + /*! + @throw parse_error.101 if unexpected token occurred + */ + void unexpect(lexer::token_type t) const; + + private: + /// current level of recursion + int depth = 0; + /// callback function + const parser_callback_t callback = nullptr; + /// the type of the last read token + lexer::token_type last_token = lexer::token_type::uninitialized; + /// the lexer + lexer m_lexer; +}; + +json json::parser::parse(bool strict) +{ + // read first token + get_token(); + + json result = parse_internal(true); + result.assert_invariant(); + + if (strict) + { + get_token(); + expect(lexer::token_type::end_of_input); + } + + // return parser result and replace it with null in case the + // top-level value was discarded by the callback function + return result.is_discarded() ? json() : std::move(result); +} + +bool json::parser::accept(bool strict) +{ + // read first token + get_token(); + + if (!accept_internal()) + { + return false; + } + + if (strict && get_token() != lexer::token_type::end_of_input) + { + return false; + } + + return true; +} + +json json::parser::parse_internal(bool keep) +{ + auto result = json(value_t::discarded); + + switch (last_token) + { + case lexer::token_type::begin_object: + { + if (keep && (!callback + || ((keep = callback(depth++, parse_event_t::object_start, result)) != 0))) + { + // explicitly set result to object to cope with {} + result.m_type = value_t::object; + result.m_value = value_t::object; + } + + // read next token + get_token(); + + // closing } -> we are done + if (last_token == lexer::token_type::end_object) + { + if (keep && callback && !callback(--depth, parse_event_t::object_end, result)) + { + result = json(value_t::discarded); + } + return result; + } + + // parse values + while (true) + { + // store key + expect(lexer::token_type::value_string); + std::string key = m_lexer.get_string(); + + bool keep_tag = false; + if (keep) + { + if (callback) + { + json k(key); + keep_tag = callback(depth, parse_event_t::key, k); + } + else + { + keep_tag = true; + } + } + + // parse separator (:) + get_token(); + expect(lexer::token_type::name_separator); + + // parse and add value + get_token(); + auto value = parse_internal(keep); + if (keep && keep_tag && !value.is_discarded()) + { + result[key] = std::move(value); + } + + // comma -> next value + get_token(); + if (last_token == lexer::token_type::value_separator) + { + get_token(); + continue; + } + + // closing } + expect(lexer::token_type::end_object); + break; + } + + if (keep && callback && !callback(--depth, parse_event_t::object_end, result)) + { + result = json(value_t::discarded); + } + + return result; + } + + case lexer::token_type::begin_array: + { + if (keep && (!callback + || ((keep = callback(depth++, parse_event_t::array_start, result)) != 0))) + { + // explicitly set result to object to cope with [] + result.m_type = value_t::array; + result.m_value = value_t::array; + } + + // read next token + get_token(); + + // closing ] -> we are done + if (last_token == lexer::token_type::end_array) + { + if (callback && !callback(--depth, parse_event_t::array_end, result)) + { + result = json(value_t::discarded); + } + return result; + } + + // parse values + while (true) + { + // parse value + auto value = parse_internal(keep); + if (keep && !value.is_discarded()) + { + result.push_back(std::move(value)); + } + + // comma -> next value + get_token(); + if (last_token == lexer::token_type::value_separator) + { + get_token(); + continue; + } + + // closing ] + expect(lexer::token_type::end_array); + break; + } + + if (keep && callback && !callback(--depth, parse_event_t::array_end, result)) + { + result = json(value_t::discarded); + } + + return result; + } + + case lexer::token_type::literal_null: + { + result.m_type = value_t::null; + break; + } + + case lexer::token_type::value_string: + { + result = json(m_lexer.get_string()); + break; + } + + case lexer::token_type::literal_true: + { + result.m_type = value_t::boolean; + result.m_value = true; + break; + } + + case lexer::token_type::literal_false: + { + result.m_type = value_t::boolean; + result.m_value = false; + break; + } + + case lexer::token_type::value_unsigned: + { + result.m_type = value_t::number_unsigned; + result.m_value = m_lexer.get_number_unsigned(); + break; + } + + case lexer::token_type::value_integer: + { + result.m_type = value_t::number_integer; + result.m_value = m_lexer.get_number_integer(); + break; + } + + case lexer::token_type::value_float: + { + result.m_type = value_t::number_float; + result.m_value = m_lexer.get_number_float(); + + // throw in case of infinity or NAN + if (JSON_UNLIKELY(!std::isfinite(result.m_value.number_float))) + { + JSON_THROW(json::out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); + } + + break; + } + + default: + { + // the last token was unexpected + unexpect(last_token); + } + } + + if (keep && callback && !callback(depth, parse_event_t::value, result)) + { + result = json(value_t::discarded); + } + return result; +} + +bool json::parser::accept_internal() +{ + switch (last_token) + { + case lexer::token_type::begin_object: + { + // read next token + get_token(); + + // closing } -> we are done + if (last_token == lexer::token_type::end_object) + { + return true; + } + + // parse values + while (true) + { + // parse key + if (last_token != lexer::token_type::value_string) + { + return false; + } + + // parse separator (:) + get_token(); + if (last_token != lexer::token_type::name_separator) + { + return false; + } + + // parse value + get_token(); + if (!accept_internal()) + { + return false; + } + + // comma -> next value + get_token(); + if (last_token == lexer::token_type::value_separator) + { + get_token(); + continue; + } + + // closing } + if (last_token != lexer::token_type::end_object) + { + return false; + } + + return true; + } + } + + case lexer::token_type::begin_array: + { + // read next token + get_token(); + + // closing ] -> we are done + if (last_token == lexer::token_type::end_array) + { + return true; + } + + // parse values + while (true) + { + // parse value + if (!accept_internal()) + { + return false; + } + + // comma -> next value + get_token(); + if (last_token == lexer::token_type::value_separator) + { + get_token(); + continue; + } + + // closing ] + if (last_token != lexer::token_type::end_array) + { + return false; + } + + return true; + } + } + + case lexer::token_type::literal_false: + case lexer::token_type::literal_null: + case lexer::token_type::literal_true: + case lexer::token_type::value_float: + case lexer::token_type::value_integer: + case lexer::token_type::value_string: + case lexer::token_type::value_unsigned: + { + return true; + } + + default: + { + // the last token was unexpected + return false; + } + } +} + +void json::parser::expect(lexer::token_type t) const +{ + if (JSON_UNLIKELY(t != last_token)) + { + std::string error_msg = "syntax error - "; + if (last_token == lexer::token_type::parse_error) + { + error_msg += m_lexer.get_error_message() + "; last read: '" + m_lexer.get_token_string() + "'"; + } + else + { + error_msg += "unexpected " + std::string(lexer::token_type_name(last_token)); + } + + error_msg += "; expected " + std::string(lexer::token_type_name(t)); + JSON_THROW(json::parse_error::create(101, m_lexer.get_position(), error_msg)); + } +} + +void json::parser::unexpect(lexer::token_type t) const +{ + if (JSON_UNLIKELY(t == last_token)) + { + std::string error_msg = "syntax error - "; + if (last_token == lexer::token_type::parse_error) + { + error_msg += m_lexer.get_error_message() + "; last read '" + m_lexer.get_token_string() + "'"; + } + else + { + error_msg += "unexpected " + std::string(lexer::token_type_name(last_token)); + } + + JSON_THROW(json::parse_error::create(101, m_lexer.get_position(), error_msg)); + } +} + +json json::parse(llvm::StringRef s, const parser_callback_t cb) +{ + wpi::raw_mem_istream is(s.data(), s.size()); + return parser(is, cb).parse(true); +} + +json json::parse(wpi::raw_istream& i, const parser_callback_t cb) +{ + return parser(i, cb).parse(true); +} + +namespace wpi { + +wpi::raw_istream& operator>>(wpi::raw_istream& i, json& j) +{ + j = json::parser(i).parse(false); + return i; +} + +} // namespace wpi diff --git a/src/main/native/cpp/support/json_pointer.cpp b/src/main/native/cpp/support/json_pointer.cpp new file mode 100644 index 0000000000..375805a30c --- /dev/null +++ b/src/main/native/cpp/support/json_pointer.cpp @@ -0,0 +1,540 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#define WPI_JSON_IMPLEMENTATION +#include "support/json.h" + +#include +#include // accumulate + +using namespace wpi; + +std::string json::json_pointer::to_string() const noexcept +{ + return std::accumulate(reference_tokens.begin(), + reference_tokens.end(), std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + escape(b); + }); +} + +json::reference json::json_pointer::get_and_create(reference j) const +{ + pointer result = &j; + + // in case no reference tokens exist, return a reference to the + // JSON value j which will be overwritten by a primitive value + for (const auto& reference_token : reference_tokens) + { + switch (result->m_type) + { + case value_t::null: + { + if (reference_token == "0") + { + // start a new array if reference token is 0 + result = &result->operator[](0); + } + else + { + // start a new object otherwise + result = &result->operator[](reference_token); + } + break; + } + + case value_t::object: + { + // create an entry in the object + result = &result->operator[](reference_token); + break; + } + + case value_t::array: + { + // create an entry in the array + JSON_TRY + { + result = &result->operator[](static_cast(std::stoi(reference_token))); + } + JSON_CATCH (std::invalid_argument&) + { + JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); + } + break; + } + + /* + 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 single value; that is, with an + empty list of reference tokens. + */ + default: + { + JSON_THROW(type_error::create(313, "invalid value to unflatten")); + } + } + } + + return *result; +} + +json::reference json::json_pointer::get_unchecked(pointer ptr) const +{ + for (const auto& reference_token : reference_tokens) + { + // convert null values to arrays or objects before continuing + if (ptr->m_type == value_t::null) + { + // check if reference token is a number + const bool nums = std::all_of(reference_token.begin(), + reference_token.end(), + [](const char x) + { + return (x >= '0' && x <= '9'); + }); + + // change value to array for numbers or "-" or to object + // otherwise + if (nums || reference_token == "-") + { + *ptr = value_t::array; + } + else + { + *ptr = value_t::object; + } + } + + switch (ptr->m_type) + { + case value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case value_t::array: + { + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 && reference_token[0] == '0') + { + JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); + } + + if (reference_token == "-") + { + // explicitly treat "-" as index beyond the end + ptr = &ptr->operator[](ptr->m_value.array->size()); + } + else + { + // convert array index to number; unchecked access + JSON_TRY + { + ptr = &ptr->operator[](static_cast(std::stoi(reference_token))); + } + JSON_CATCH (std::invalid_argument&) + { + JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); + } + } + break; + } + + default: + { + JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; +} + +json::reference json::json_pointer::get_checked(pointer ptr) const +{ + for (const auto& reference_token : reference_tokens) + { + switch (ptr->m_type) + { + case value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case value_t::array: + { + if (reference_token == "-") + { + // "-" always fails the range check + JSON_THROW(out_of_range::create(402, "array index '-' (" + + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 && reference_token[0] == '0') + { + JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); + } + + // note: at performs range check + JSON_TRY + { + ptr = &ptr->at(static_cast(std::stoi(reference_token))); + } + JSON_CATCH (std::invalid_argument&) + { + JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); + } + break; + } + + default: + { + JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; +} + +json::const_reference json::json_pointer::get_unchecked(const_pointer ptr) const +{ + for (const auto& reference_token : reference_tokens) + { + switch (ptr->m_type) + { + case value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case value_t::array: + { + if (reference_token == "-") + { + // "-" cannot be used for const access + JSON_THROW(out_of_range::create(402, "array index '-' (" + + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 && reference_token[0] == '0') + { + JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); + } + + // use unchecked array access + JSON_TRY + { + ptr = &ptr->operator[](static_cast(std::stoi(reference_token))); + } + JSON_CATCH (std::invalid_argument&) + { + JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); + } + break; + } + + default: + { + JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; +} + +json::const_reference json::json_pointer::get_checked(const_pointer ptr) const +{ + for (const auto& reference_token : reference_tokens) + { + switch (ptr->m_type) + { + case value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case value_t::array: + { + if (reference_token == "-") + { + // "-" always fails the range check + JSON_THROW(out_of_range::create(402, "array index '-' (" + + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 && reference_token[0] == '0') + { + JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); + } + + // note: at performs range check + JSON_TRY + { + ptr = &ptr->at(static_cast(std::stoi(reference_token))); + } + JSON_CATCH (std::invalid_argument&) + { + JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); + } + break; + } + + default: + { + JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; +} + +std::vector json::json_pointer::split(const std::string& reference_string) +{ + std::vector result; + + // special case: empty reference string -> no reference tokens + if (reference_string.empty()) + { + return result; + } + + // check if nonempty reference string begins with slash + if (reference_string[0] != '/') + { + JSON_THROW(parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'")); + } + + // extract the reference tokens: + // - slash: position of the last read slash (or end of string) + // - start: position after the previous slash + for ( + // search for the first slash after the first character + size_t slash = reference_string.find_first_of('/', 1), + // set the beginning of the first reference token + start = 1; + // we can stop if start == string::npos+1 = 0 + start != 0; + // set the beginning of the next reference token + // (will eventually be 0 if slash == std::string::npos) + start = slash + 1, + // find next slash + slash = reference_string.find_first_of('/', start)) + { + // use the text between the beginning of the reference token + // (start) and the last slash (slash). + auto reference_token = reference_string.substr(start, slash - start); + + // check reference tokens are properly escaped + for (size_t pos = reference_token.find_first_of('~'); + pos != std::string::npos; + pos = reference_token.find_first_of('~', pos + 1)) + { + assert(reference_token[pos] == '~'); + + // ~ must be followed by 0 or 1 + if (pos == reference_token.size() - 1 || + (reference_token[pos + 1] != '0' && + reference_token[pos + 1] != '1')) + { + JSON_THROW(parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); + } + } + + // finally, store the reference token + unescape(reference_token); + result.push_back(reference_token); + } + + return result; +} + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is + enforced with an assertion.** + +@since version 2.0.0 +*/ +void json::json_pointer::replace_substring(std::string& s, + const std::string& f, + const std::string& t) +{ + assert(!f.empty()); + + for ( + size_t pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t + pos = s.find(f, pos + t.size()) // find next occurrence of f + ); +} + +/// escape tilde and slash +std::string json::json_pointer::escape(std::string s) +{ + // escape "~"" to "~0" and "/" to "~1" + replace_substring(s, "~", "~0"); + replace_substring(s, "/", "~1"); + return s; +} + +/// unescape tilde and slash +void json::json_pointer::unescape(std::string& s) +{ + // first transform any occurrence of the sequence '~1' to '/' + replace_substring(s, "~1", "/"); + // then transform any occurrence of the sequence '~0' to '~' + replace_substring(s, "~0", "~"); +} + +void json::json_pointer::flatten(const std::string& reference_string, + const json& value, + json& result) +{ + switch (value.m_type) + { + case value_t::array: + { + if (value.m_value.array->empty()) + { + // flatten empty array as null + result[reference_string] = nullptr; + } + else + { + // iterate array and use index as reference string + for (size_t i = 0; i < value.m_value.array->size(); ++i) + { + flatten(reference_string + "/" + std::to_string(i), + value.m_value.array->operator[](i), result); + } + } + break; + } + + case value_t::object: + { + if (value.m_value.object->empty()) + { + // flatten empty object as null + result[reference_string] = nullptr; + } + else + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + flatten(reference_string + "/" + escape(element.first()), + element.second, result); + } + } + break; + } + + default: + { + // add primitive value with its reference string + result[reference_string] = value; + break; + } + } +} + +json json::json_pointer::unflatten(const json& value) +{ + if (!value.is_object()) + { + JSON_THROW(type_error::create(314, "only objects can be unflattened")); + } + + // we need to iterate over the object values in sorted key order + llvm::SmallVector, 64> sorted; + for (auto i = value.m_value.object->begin(), + end = value.m_value.object->end(); i != end; ++i) + { + if (!i->second.is_primitive()) + { + JSON_THROW(type_error::create(315, "values in object must be primitive")); + } + sorted.push_back(i); + } + std::sort(sorted.begin(), sorted.end(), + [](const llvm::StringMapConstIterator& a, + const llvm::StringMapConstIterator& b) { + return a->getKey() < b->getKey(); + }); + + json result; + + // iterate the sorted JSON object values + for (const auto& element : sorted) + { + + // 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; +} + diff --git a/src/main/native/cpp/support/json_serializer.cpp b/src/main/native/cpp/support/json_serializer.cpp new file mode 100644 index 0000000000..3ee052d2ba --- /dev/null +++ b/src/main/native/cpp/support/json_serializer.cpp @@ -0,0 +1,433 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#define WPI_JSON_IMPLEMENTATION +#include "support/json.h" + +#include "llvm/SmallString.h" +#include "llvm/StringExtras.h" + +#include "json_serializer.h" + +using namespace wpi; + +void json::serializer::dump(const json& val, + const bool pretty_print, + const unsigned int indent_step, + const unsigned int current_indent) +{ + switch (val.m_type) + { + case value_t::object: + { + if (val.m_value.object->empty()) + { + o << "{}"; + return; + } + + if (pretty_print) + { + o << "{\n"; + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + + // first n-1 elements + auto i = val.m_value.object->begin(); + for (size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o.indent(new_indent); + o << '\"'; + dump_escaped(i->first()); + o << "\": "; + dump(i->second, true, indent_step, new_indent); + o << ",\n"; + } + + // last element + assert(i != val.m_value.object->end()); + o.indent(new_indent); + o << '\"'; + dump_escaped(i->first()); + o << "\": "; + dump(i->second, true, indent_step, new_indent); + + o << '\n'; + o.indent(current_indent); + o << '}'; + } + else + { + o << '{'; + + // first n-1 elements + auto i = val.m_value.object->begin(); + for (size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o << '\"'; + dump_escaped(i->first()); + o << "\":"; + dump(i->second, false, indent_step, current_indent); + o << ','; + } + + // last element + assert(i != val.m_value.object->end()); + o << '\"'; + dump_escaped(i->first()); + o << "\":"; + dump(i->second, false, indent_step, current_indent); + + o << '}'; + } + + return; + } + + case value_t::array: + { + if (val.m_value.array->empty()) + { + o << "[]"; + return; + } + + if (pretty_print) + { + o << "[\n"; + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) + { + o.indent(new_indent); + dump(*i, true, indent_step, new_indent); + o << ",\n"; + } + + // last element + assert(!val.m_value.array->empty()); + o.indent(new_indent); + dump(val.m_value.array->back(), true, indent_step, new_indent); + + o << '\n'; + o.indent(current_indent); + o << ']'; + } + else + { + o << '['; + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) + { + dump(*i, false, indent_step, current_indent); + o << ','; + } + + // last element + assert(!val.m_value.array->empty()); + dump(val.m_value.array->back(), false, indent_step, current_indent); + + o << ']'; + } + + return; + } + + case value_t::string: + { + o << '\"'; + dump_escaped(*val.m_value.string); + o << '\"'; + return; + } + + case value_t::boolean: + { + if (val.m_value.boolean) + { + o << "true"; + } + else + { + o << "false"; + } + return; + } + + case value_t::number_integer: + { + o << static_cast(val.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + o << static_cast(val.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float(val.m_value.number_float); + return; + } + + case value_t::discarded: + { + o << ""; + return; + } + + case value_t::null: + { + o << "null"; + return; + } + } +} + +void json::serializer::dump_escaped(llvm::StringRef s) const +{ + for (const auto& c : s) + { + switch (c) + { + // quotation mark (0x22) + case '"': + { + o << '\\' << '"'; + break; + } + + // reverse solidus (0x5c) + case '\\': + { + // nothing to change + o << '\\' << '\\'; + break; + } + + // backspace (0x08) + case '\b': + { + o << '\\' << 'b'; + break; + } + + // formfeed (0x0c) + case '\f': + { + o << '\\' << 'f'; + break; + } + + // newline (0x0a) + case '\n': + { + o << '\\' << 'n'; + break; + } + + // carriage return (0x0d) + case '\r': + { + o << '\\' << 'r'; + break; + } + + // horizontal tab (0x09) + case '\t': + { + o << '\\' << 't'; + break; + } + + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x0b: + case 0x0e: + case 0x0f: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1a: + case 0x1b: + case 0x1c: + case 0x1d: + case 0x1e: + case 0x1f: + { + // print character c as \uxxxx + o << "\\u00"; + o << llvm::hexdigit((c >> 4) & 0xf, true); + o << llvm::hexdigit((c >> 0) & 0xf, true); + break; + } + + default: + { + // all other characters are added as-is + o << c; + break; + } + } + } +} + +void json::serializer::dump_float(double x) +{ + // NaN / inf + if (!std::isfinite(x) || std::isnan(x)) + { + o << "null"; + return; + } + + // special case for 0.0 and -0.0 + if (x == 0) + { + if (std::signbit(x)) + { + o << "-0.0"; + } + else + { + o << "0.0"; + } + return; + } + + // get number of digits for a text -> float -> text round-trip + static constexpr auto d = std::numeric_limits::digits10; + + // the actual conversion + llvm::SmallString<64> number_buffer; + number_buffer.resize(64); + std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), + "%.*g", d, x); + + // negative value indicates an error + assert(len > 0); + // check if buffer was large enough + assert(static_cast(len) < number_buffer.size()); + + // erase thousands separator + if (thousands_sep != '\0') + { + const auto end = std::remove(number_buffer.begin(), + number_buffer.begin() + len, + thousands_sep); + std::fill(end, number_buffer.end(), '\0'); + assert((end - number_buffer.begin()) <= len); + len = (end - number_buffer.begin()); + } + + // convert decimal point to '.' + if (decimal_point != '\0' && decimal_point != '.') + { + for (auto& c : number_buffer) + { + if (c == decimal_point) + { + c = '.'; + break; + } + } + } + + o.write(number_buffer.data(), static_cast(len)); + + // determine if need to append ".0" + const bool value_is_int_like = std::none_of(number_buffer.begin(), + number_buffer.begin() + len + 1, + [](char c) + { + return c == '.' || c == 'e'; + }); + + if (value_is_int_like) + { + o << ".0"; + } +} + +namespace wpi { + +llvm::raw_ostream& operator<<(llvm::raw_ostream& o, const json& j) +{ + j.dump(o, 0); + return o; +} + +} // namespace wpi + +std::string json::dump(int indent) const +{ + std::string s; + llvm::raw_string_ostream os(s); + dump(os, indent); + os.flush(); + return s; +} + +void json::dump(llvm::raw_ostream& os, int indent) const +{ + serializer s(os); + + if (indent >= 0) + { + s.dump(*this, true, static_cast(indent)); + } + else + { + s.dump(*this, false, 0); + } +} diff --git a/src/main/native/cpp/support/json_serializer.h b/src/main/native/cpp/support/json_serializer.h new file mode 100644 index 0000000000..fcbb488eb5 --- /dev/null +++ b/src/main/native/cpp/support/json_serializer.h @@ -0,0 +1,120 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ +#include "support/json.h" + +#include // lconv, localeconv +#include // locale + +#include "llvm/raw_ostream.h" + +namespace wpi { + +/*! +@brief wrapper around the serialization functions +*/ +class json::serializer +{ + public: + serializer(const serializer&) = delete; + serializer& operator=(const serializer&) = delete; + + /*! + @param[in] s output stream to serialize to + @param[in] ichar indentation character to use + */ + explicit serializer(llvm::raw_ostream& s) + : o(s), loc(std::localeconv()), + thousands_sep(!loc->thousands_sep ? '\0' : loc->thousands_sep[0]), + decimal_point(!loc->decimal_point ? '\0' : loc->decimal_point[0]) + {} + + /*! + @brief internal implementation of the serialization function + + This function is called by the public member function dump and + organizes the serialization internally. The indentation level is + propagated as additional parameter. In case of arrays and objects, the + function is called recursively. + + - strings and object keys are escaped using `escape_string()` + - integer numbers are converted implicitly via `operator<<` + - floating-point numbers are converted to a string using `"%g"` format + + @param[in] val value to serialize + @param[in] pretty_print whether the output shall be pretty-printed + @param[in] indent_step the indent level + @param[in] current_indent the current indent level (only used internally) + */ + void dump(const json& val, + const bool pretty_print, + const unsigned int indent_step, + const unsigned int current_indent = 0); + + /*! + @brief dump escaped string + + Escape a string by replacing certain special characters by a sequence + of an escape character (backslash) and another character and other + control characters by a sequence of "\u" followed by a four-digit hex + representation. The escaped string is written to output stream @a o. + + @param[in] s the string to escape + + @complexity Linear in the length of string @a s. + */ + void dump_escaped(llvm::StringRef s) const; + + /*! + @brief dump a floating-point number + + Dump a given floating-point number to output stream @a o. Works + internally with @a number_buffer. + + @param[in] x floating-point number to dump + */ + void dump_float(double x); + + private: + /// the output of the serializer + llvm::raw_ostream& o; + + /// the locale + const std::lconv* loc = nullptr; + /// the locale's thousand separator character + const char thousands_sep = '\0'; + /// the locale's decimal point character + const char decimal_point = '\0'; +}; + +} // namespace wpi diff --git a/src/main/native/include/support/json.h b/src/main/native/include/support/json.h new file mode 100644 index 0000000000..6e4b33d4ba --- /dev/null +++ b/src/main/native/include/support/json.h @@ -0,0 +1,7257 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#ifndef WPI_SUPPORT_JSON_H_ +#define WPI_SUPPORT_JSON_H_ + +#include // assert +#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 // function, hash, less +#include // initializer_list +#include // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag +#include // numeric_limits +#include // addressof, allocator, allocator_traits, unique_ptr +#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 // vector + +#include "llvm/ArrayRef.h" +#include "llvm/raw_ostream.h" +#include "llvm/StringMap.h" +#include "llvm/StringRef.h" + +// 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__) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif +#endif + +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" + #pragma GCC diagnostic ignored "-Wtype-limits" +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" + #pragma GCC diagnostic ignored "-Wtautological-constant-out-of-range-compare" +#endif + +// allow to disable exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) +#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 + +namespace wpi +{ + +class raw_istream; + +/*! +@brief unnamed namespace with internal helper functions + +This namespace collects some functions that could not be defined inside the +@ref json class. + +@since version 2.1.0 +*/ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/*! +@brief general exception of the @ref json class + +Extension of std::exception objects with a member @a id for exception ids. + +@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. + +@since version 3.0.0 +*/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + virtual const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; + + protected: + exception(int id_, const char* what_arg) + : id(id_), m(what_arg) + {} + + static std::string name(const std::string& ename, int id); + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/*! +@brief exception indicating a parse error + +This excpetion is thrown by the library when a parse error occurs. Parse +errors can occur during the deserialization of JSON text as well as when +using JSON Patch. + +Member @a byte holds 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). + +Exceptions have ids 1xx. + +name / id | example massage | description +------------------------------ | --------------- | ------------------------- +json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. +json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. +json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. +json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. +json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number wihtout 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.111 | parse error: bad input stream | Parsing CBOR or MessagePack from an input stream where the [`badbit` or `failbit`](http://en.cppreference.com/w/cpp/io/ios_base/iostate) is set. +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. + +@since version 3.0.0 +*/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id the id of the exception + @param[in] byte_ the byte index where the error occured (or 0 if + the position cannot be determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + static parse_error create(int id, size_t byte_, const std::string& what_arg); + + /*! + @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). + */ + const size_t byte; + + private: + parse_error(int id_, size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) + {} +}; + +/*! +@brief exception indicating errors with iterators + +Exceptions have ids 2xx. + +name / id | example massage | description +----------------------------------- | --------------- | ------------------------- +json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. +json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. +json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. +json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. +json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. +json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. +json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. +json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. +json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compated, 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(). + +@since version 3.0.0 +*/ +class invalid_iterator : public exception +{ + public: + static invalid_iterator create(int id, const std::string& what_arg); + + private: + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) + {} +}; + +/*! +@brief exception indicating executing a member function with a wrong type + +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 json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. +json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. +json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. +json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. +json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. +json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. +json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. +json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. +json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. +json.exception.type_error.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. + +@since version 3.0.0 +*/ +class type_error : public exception +{ + public: + static type_error create(int id, const std::string& what_arg); + + private: + type_error(int id_, const char* what_arg) + : exception(id_, what_arg) + {} +}; + +/*! +@brief exception indicating access out of the defined range + +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. +json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. +json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. +json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. +json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. +json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. + +@since version 3.0.0 +*/ +class out_of_range : public exception +{ + public: + static out_of_range create(int id, const std::string& what_arg); + + private: + out_of_range(int id_, const char* what_arg) + : exception(id_, what_arg) + {} +}; + +/*! +@brief exception indicating other errors + +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) + +@since version 3.0.0 +*/ +class other_error : public exception +{ + public: + static other_error create(int id, const std::string& what_arg); + + private: + other_error(int id_, const char* what_arg) + : exception(id_, what_arg) + {} +}; + + + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@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 json::is_null(), +@ref json::is_object(), @ref json::is_array(), +@ref json::is_string(), @ref json::is_boolean(), +@ref json::is_number() (with @ref json::is_number_integer(), +@ref json::is_number_unsigned(), and @ref json::is_number_float()), +@ref json::is_discarded(), @ref json::is_primitive(), and +@ref 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: +std::uint64_t is used for unsigned integers, +std::int64_t is used for signed integers, and +double is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa @ref json::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 +}; + +/*! +@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 uint8_t order[] = { + 0, // null + 3, // object + 4, // array + 5, // string + 1, // boolean + 2, // integer + 2, // unsigned + 2, // float + }; + + // discarded values are not comparable + if (lhs == value_t::discarded || rhs == value_t::discarded) + { + return false; + } + + return order[static_cast(lhs)] < + order[static_cast(rhs)]; +} + + +///////////// +// helpers // +///////////// + +// 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 two C++17 constructs: conjunction, negation. This is needed +to avoid evaluating all the traits in a condition + +For example: !std::is_same::value && 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> {}; + + +////////////////// +// constructors // +////////////////// + +template struct external_constructor; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, bool 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, llvm::StringRef s) + { + j.m_type = value_t::string; + j.m_value = s; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, double val) noexcept + { + j.m_type = value_t::number_float; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, std::uint64_t val) noexcept + { + j.m_type = value_t::number_unsigned; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, std::int64_t val) noexcept + { + j.m_type = value_t::number_integer; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + 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, llvm::ArrayRef 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::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<> +struct external_constructor +{ + 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::value, + int> = 0> + static void construct(BasicJsonType& j, const CompatibleObjectType& obj) + { + j.m_type = value_t::object; + j.m_value = value_t::object; + for (const auto& x : obj) + { + j.m_value.object->emplace_second(x.first, x.second); + } + j.assert_invariant(); + } +}; + + +//////////////////////// +// 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 WPI_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; \ + } + +WPI_JSON_HAS_HELPER(mapped_type); +WPI_JSON_HAS_HELPER(key_type); +WPI_JSON_HAS_HELPER(value_type); +WPI_JSON_HAS_HELPER(iterator); + +#undef WPI_JSON_HAS_HELPER + + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl +{ + static constexpr auto value = + std::is_constructible::value && + std::is_constructible::value; +}; + +template +struct is_compatible_object_type +{ + 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_json_nested_type +{ + static auto constexpr value = std::is_same::value || + std::is_same::value || + std::is_same::value; +}; + +template +struct is_compatible_array_type +{ + static auto constexpr value = + conjunction>, + negation>, + negation>, + negation>, + has_value_type, + has_iterator>::value; +}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl +{ + // 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 && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type +{ + static constexpr auto value = + is_compatible_integer_type_impl < + std::is_integral::value && + !std::is_same::value, + RealIntegerType, CompatibleNumberIntegerType > ::value; +}; + +///////////// +// to_json // +///////////// + +template::value, int> = 0> +inline +void to_json(BasicJsonType& j, T b) noexcept +{ + detail::external_constructor::construct(j, b); +} + +template::value, int> = 0> +inline +void to_json(BasicJsonType& j, const CompatibleString& s) +{ + external_constructor::construct(j, s); +} + +template::value, int> = 0> +inline +void to_json(BasicJsonType& j, FloatType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template < + typename BasicJsonType, typename CompatibleNumberUnsignedType, + enable_if_t::value, int> = 0 > +inline +void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template < + typename BasicJsonType, typename CompatibleNumberIntegerType, + enable_if_t::value, int> = 0 > +inline +void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +inline +void to_json(BasicJsonType& j, EnumType e) noexcept +{ + using underlying_type = typename std::underlying_type::type; + external_constructor::construct(j, static_cast(e)); +} + +template +inline +void to_json(BasicJsonType& j, const std::vector& e) +{ + external_constructor::construct(j, e); +} + +template +inline +void to_json(BasicJsonType& j, llvm::ArrayRef arr) +{ + external_constructor::construct(j, arr); +} + +template < + typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < + is_compatible_array_type::value || + std::is_same::value, + int > = 0 > +inline +void to_json(BasicJsonType& j, const CompatibleArrayType& arr) +{ + external_constructor::construct(j, arr); +} + +template < + typename BasicJsonType, typename CompatibleObjectType, + enable_if_t::value, + int> = 0 > +inline +void to_json(BasicJsonType& j, const CompatibleObjectType& arr) +{ + external_constructor::construct(j, arr); +} + +template ::value, + int> = 0> +inline +void to_json(BasicJsonType& j, T (&arr)[N]) +{ + external_constructor::construct(j, arr); +} + +template ::value, int> = 0> +inline +void to_json(BasicJsonType& j, std::pair const& p) +{ + j[p.first] = p.second; +} + +/////////////// +// from_json // +/////////////// + +// overloads for json template parameters +template::value && + !std::is_same::value, + int> = 0> +void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast( + *j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast( + *j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast( + *j.template get_ptr()); + break; + } + default: + { + JSON_THROW(type_error::create(302, "type must be number, but is " + j.type_name())); + } + } +} + +template +inline +void from_json(const BasicJsonType& j, bool& b) +{ + if (!j.is_boolean()) + { + JSON_THROW(type_error::create(302, "type must be boolean, but is " + j.type_name())); + } + b = *j.template get_ptr(); +} + +template +inline +void from_json(const BasicJsonType& j, std::string& s) +{ + if (!j.is_string()) + { + JSON_THROW(detail::type_error::create(302, "type must be string, but is " + j.type_name())); + } + s = *j.template get_ptr(); +} + +template +inline +void from_json(const BasicJsonType& j, double& val) +{ + get_arithmetic_value(j, val); +} + +template +inline +void from_json(const BasicJsonType& j, std::uint64_t& val) +{ + get_arithmetic_value(j, val); +} + +template +inline +void from_json(const BasicJsonType& j, std::int64_t& val) +{ + get_arithmetic_value(j, val); +} + +template::value, int> = 0> +inline +void from_json(const BasicJsonType& j, EnumType& e) +{ + typename std::underlying_type::type val; + get_arithmetic_value(j, val); + e = static_cast(val); +} + +template +inline +void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) +{ + if (!j.is_array()) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name())); + } + arr = *j.template get_ptr(); +} + +template +void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, detail::priority_tag<0>) +{ + using std::begin; + using std::end; + + std::transform(j.begin(), j.end(), + std::inserter(arr, end(arr)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); +} + +template +auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, detail::priority_tag<1>) +-> decltype( + arr.reserve(std::declval()), + void()) +{ + using std::begin; + using std::end; + + arr.reserve(j.size()); + std::transform(j.begin(), j.end(), + std::inserter(arr, end(arr)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); +} + +template::value && + std::is_convertible::value && + !std::is_same::value, int> = 0> +void from_json(const BasicJsonType& j, CompatibleArrayType& arr) +{ + if (!j.is_array()) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name())); + } + + from_json_array_impl(j, arr, priority_tag<1> {}); +} + +template +inline +void from_json(const BasicJsonType& j, typename BasicJsonType::object_t& obj) +{ + if (!j.is_object()) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + j.type_name())); + } + + auto inner_object = j.template get_ptr(); + for (const auto& i : *inner_object) { + obj.emplace_second(i.first(), i.second); + } +} + +template::value && + !std::is_same::value, int> = 0> +void from_json(const BasicJsonType& j, CompatibleObjectType& obj) +{ + if (!j.is_object()) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + j.type_name())); + } + + auto inner_object = j.template get_ptr(); + using std::begin; + using std::end; + using value_type = typename CompatibleObjectType::value_type; + std::vector v; + v.reserve(j.size()); + for (const auto& p : *inner_object) + { + v.emplace_back( + p.first(), + p.second + .template get()); + } + // we could avoid the assignment, but this might require a for loop, which + // might be less efficient than the container constructor for some + // containers (would it?) + obj = CompatibleObjectType(std::make_move_iterator(begin(v)), + std::make_move_iterator(end(v))); +} + +// overload for arithmetic types, not chosen for json template arguments; +template::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same::value, + int> = 0> +void from_json(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::boolean: + { + val = static_cast(*j.template get_ptr()); + break; + } + default: + { + JSON_THROW(type_error::create(302, "type must be number, but is " + j.type_name())); + } + } +} + +template ::value, int> = 0> +void from_json(const BasicJsonType& j, std::pair& p) +{ + if (!j.is_object()) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + j.type_name())); + } + + auto const inner_object = j.template get_ptr(); + auto const size = inner_object->size(); + if (size != 1) + { + JSON_THROW(other_error::create(502, "conversion to std::pair requires the object to have exactly one field, but it has " + std::to_string(size))); + } + auto const& obj = *inner_object->begin(); + // cannot use *inner_object, need to convert both members + p = std::make_pair(CompatibleString(obj.first()), obj.second.template get()); +} + +struct to_json_fn +{ + private: + template + auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward(val)))) + -> decltype(to_json(j, std::forward(val)), void()) + { + return to_json(j, std::forward(val)); + } + + template + void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept + { + static_assert(sizeof(BasicJsonType) == 0, + "could not find to_json() method in T's namespace"); + } + + public: + template + void operator()(BasicJsonType& j, T&& val) const + noexcept(noexcept(std::declval().call(j, std::forward(val), priority_tag<1> {}))) + { + return call(j, std::forward(val), priority_tag<1> {}); + } +}; + +struct from_json_fn +{ + private: + template + auto call(const BasicJsonType& j, T& val, priority_tag<1>) const + noexcept(noexcept(from_json(j, val))) + -> decltype(from_json(j, val), void()) + { + return from_json(j, val); + } + + template + void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept + { + static_assert(sizeof(BasicJsonType) == 0, + "could not find from_json() method in T's namespace"); + } + + public: + template + void operator()(const BasicJsonType& j, T& val) const + noexcept(noexcept(std::declval().call(j, val, priority_tag<1> {}))) + { + return call(j, val, priority_tag<1> {}); + } +}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; +} // namespace detail + + +/// namespace to hold default `to_json` / `from_json` functions +namespace +{ +constexpr const auto& to_json = detail::static_const::value; +constexpr const auto& from_json = detail::static_const::value; +} + +/*! +@brief a class to store JSON values + +@requirement The class satisfies the following concept requirements: +- Basic + - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible): + JSON values can be default constructed. The result will be a JSON null + value. + - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible): + A JSON value can be constructed from an rvalue argument. + - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible): + A JSON value can be copy-constructed from an lvalue expression. + - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable): + A JSON value van be assigned from an rvalue argument. + - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable): + A JSON value can be copy-assigned from an lvalue expression. + - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible): + JSON values can be destructed. +- Layout + - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType): + JSON values have + [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout): + All non-static data members are private and standard layout types, the + class has no virtual functions or (virtual) base classes. +- Library-wide + - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable): + JSON values can be compared with `==`, see @ref + operator==(const_reference,const_reference). + - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable): + JSON values can be compared with `<`, see @ref + operator<(const_reference,const_reference). + - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable): + Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of + other compatible types, using unqualified function call @ref swap(). + - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer): + JSON values can be compared against `std::nullptr_t` objects which are used + to model the `null` value. +- Container + - [Container](http://en.cppreference.com/w/cpp/concept/Container): + JSON values can be used like STL containers and provide iterator access. + - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer); + JSON values can be used like STL containers and provide reverse iterator + access. + +@invariant The member variables @a m_value and @a m_type have the following +relationship: +- If `m_type == value_t::object`, then `m_value.object != nullptr`. +- If `m_type == value_t::array`, then `m_value.array != nullptr`. +- If `m_type == value_t::string`, then `m_value.string != nullptr`. +The invariants are checked by member function assert_invariant(). + +@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange +Format](http://rfc7159.net/rfc7159) + +@since version 1.0.0 + +@nosubgrouping +*/ +class json +{ + private: + template friend struct detail::external_constructor; + friend class JsonTest; + + public: + using value_t = detail::value_t; + // forward declarations + template class iter_impl; + class json_pointer; + + class parser; + class serializer; + class binary_writer; + + //////////////// + // exceptions // + //////////////// + + /// @name exceptions + /// Classes to implement user-defined exceptions. + /// @{ + + /// @copydoc detail::exception + using exception = detail::exception; + /// @copydoc detail::parse_error + using parse_error = detail::parse_error; + /// @copydoc detail::invalid_iterator + using invalid_iterator = detail::invalid_iterator; + /// @copydoc detail::type_error + using type_error = detail::type_error; + /// @copydoc detail::out_of_range + using out_of_range = detail::out_of_range; + /// @copydoc detail::other_error + using other_error = detail::other_error; + + /// @} + + + ///////////////////// + // container types // + ///////////////////// + + /// @name container types + /// The canonic container types to use @ref json like any other STL + /// container. + /// @{ + + /// the type of elements in a json container + using value_type = json; + + /// the type of an element reference + using reference = value_type&; + /// the type of an element const reference + using const_reference = const value_type&; + + /// a type to represent differences between iterators + using difference_type = std::ptrdiff_t; + /// a type to represent container sizes + using size_type = std::size_t; + + /// the type of an element pointer + using pointer = json*; + /// the type of an element const pointer + using const_pointer = const json*; + + /// an iterator for a json container + using iterator = iter_impl; + /// a const iterator for a json container + using const_iterator = iter_impl; + + /// @} + + /*! + @brief returns version information on the library + + This function returns a JSON object with information about the library, + including the version number and information on the platform and compiler. + + @return JSON object holding version information + key | description + ----------- | --------------- + `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). + `copyright` | The copyright line for the library as string. + `name` | The name of the library as string. + `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. + `url` | The URL of the project as string. + `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). + + @liveexample{The following code shows an example output of the `meta()` + function.,meta} + + @complexity Constant. + + @since 2.1.0 + */ + static json meta(); + + /////////////////////////// + // JSON value data types // + /////////////////////////// + + /// @name JSON value data types + /// The data types to store a JSON value. These types are derived from + /// the template arguments passed to class @ref json. + /// @{ + + /*! + @brief a type for an object + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: + > An object is an unordered collection of zero or more name/value pairs, + > where a name is a string and a value is a string, number, boolean, null, + > object, or array. + + #### Behavior + + The choice of @a object_t influences the behavior of the JSON class. With + the default type, objects have the following behavior: + + - When all names are unique, objects will be interoperable in the sense + that all software implementations receiving that object will agree on + the name-value mappings. + - When the names within an object are not unique, later stored name/value + pairs overwrite previously stored name/value pairs, leaving the used + names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will + be treated as equal and both stored as `{"key": 1}`. + - Internally, name/value pairs are stored in lexicographical order of the + names. Objects will also be serialized (see @ref dump) in this order. + For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored + and serialized as `{"a": 2, "b": 1}`. + - When comparing objects, the order of the name/value pairs is irrelevant. + This makes objects interoperable in the sense that they will not be + affected by these differences. For instance, `{"b": 1, "a": 2}` and + `{"a": 2, "b": 1}` will be treated as equal. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the object's limit of nesting is not constraint explicitly. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON object. + + #### Storage + + Objects are stored as pointers in a @ref json type. That is, for any + access to object values, a pointer of type `object_t*` must be + dereferenced. + + @sa @ref array_t -- type for an array value + + @since version 1.0.0 + + @note The order name/value pairs are added to the object is *not* + preserved by the library. Therefore, iterating an object may return + name/value pairs in a different order than they were originally stored. In + fact, keys will be traversed in alphabetical order as `std::map` with + `std::less` is used by default. Please note this behavior conforms to [RFC + 7159](http://rfc7159.net/rfc7159), because any order implements the + specified "unordered" nature of JSON objects. + */ + using object_t = llvm::StringMap; + + /*! + @brief a type for an array + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: + > An array is an ordered sequence of zero or more values. + + To store objects in C++, a type is defined by the template parameters + explained below. + + #### Default type + + The default value for @a array_t is: + + @code {.cpp} + std::vector< + json // value_type + > + @endcode + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the array's limit of nesting is not constraint explicitly. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON array. + + #### Storage + + Arrays are stored as pointers in a @ref json type. That is, for any + access to array values, a pointer of type `array_t*` must be dereferenced. + + @sa @ref object_t -- type for an object value + + @since version 1.0.0 + */ + using array_t = std::vector; + + /*! + @brief a type for a string + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: + > A string is a sequence of zero or more Unicode characters. + + To store objects in C++, a type is defined by the template parameter + described below. Unicode values are split by the JSON class into + byte-sized characters during deserialization. + + #### Default type + + The default value for @a string_t is: + + @code {.cpp} + std::string + @endcode + + #### Encoding + + Strings are stored in UTF-8 encoding. Therefore, functions like + `std::string::size()` or `std::string::length()` return the number of + bytes in the string rather than the number of characters or glyphs. + + #### String comparison + + [RFC 7159](http://rfc7159.net/rfc7159) states: + > Software implementations are typically required to test names of object + > members for equality. Implementations that transform the textual + > representation into sequences of Unicode code units and then perform the + > comparison numerically, code unit by code unit, are interoperable in the + > sense that implementations will agree in all cases on equality or + > inequality of two strings. For example, implementations that compare + > strings with escaped characters unconverted may incorrectly find that + > `"a\\b"` and `"a\u005Cb"` are not equal. + + This implementation is interoperable as it does compare strings code unit + by code unit. + + #### Storage + + String values are stored as pointers in a @ref basic_json type. That is, + for any access to string values, a pointer of type `string_t*` must be + dereferenced. + + @since version 1.0.0 + */ + using string_t = std::string; + + /*! + @brief a type for a boolean + + [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a + type which differentiates the two literals `true` and `false`. + + #### Default type + + The default value for @a boolean_t is: + + @code {.cpp} + bool + @endcode + + #### Storage + + Boolean values are stored directly inside a @ref basic_json type. + + @since version 1.0.0 + */ + using boolean_t = bool; + + /*! + @brief a type for a number (integer) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + #### Default type + + The default value for @a number_integer_t is: + + @code {.cpp} + int64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `9223372036854775807` (INT64_MAX) and the minimal integer number + that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers + that are out of range will yield over/underflow when used in a + constructor. During deserialization, too large or small integer numbers + will be automatically be stored as @ref number_unsigned_t or @ref + number_float_t. + + [RFC 7159](http://rfc7159.net/rfc7159) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange of the exactly supported range [INT64_MIN, + INT64_MAX], this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa @ref number_float_t -- type for number values (floating-point) + + @sa @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_integer_t = int64_t; + + /*! + @brief a type for a number (unsigned) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + #### Default type + + The default value for @a number_unsigned_t is: + + @code {.cpp} + uint64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `18446744073709551615` (UINT64_MAX) and the minimal integer + number that can be stored is `0`. Integer numbers that are out of range + will yield over/underflow when used in a constructor. During + deserialization, too large or small integer numbers will be automatically + be stored as @ref number_integer_t or @ref number_float_t. + + [RFC 7159](http://rfc7159.net/rfc7159) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange (when considered in conjunction with the + number_integer_t type) of the exactly supported range [0, UINT64_MAX], + this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa @ref number_float_t -- type for number values (floating-point) + @sa @ref number_integer_t -- type for number values (integer) + + @since version 2.0.0 + */ + using number_unsigned_t = uint64_t; + + /*! + @brief a type for a number (floating-point) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + #### Default type + + The default value for @a number_float_t is: + + @code {.cpp} + double + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in floating-point literals will be ignored. Internally, + the value will be stored as decimal number. For instance, the C++ + floating-point literal `01.2` will be serialized to `1.2`. During + deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) states: + > This specification allows implementations to set limits on the range and + > precision of numbers accepted. Since software that implements IEEE + > 754-2008 binary64 (double precision) numbers is generally available and + > widely used, good interoperability can be achieved by implementations + > that expect no more precision or range than these provide, in the sense + > that implementations will approximate JSON numbers within the expected + > precision. + + This implementation does exactly follow this approach, as it uses double + precision floating-point numbers. Note values smaller than + `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` + will be stored as NaN internally and be serialized to `null`. + + #### Storage + + Floating-point number values are stored directly inside a @ref basic_json + type. + + @sa @ref number_integer_t -- type for number values (integer) + + @sa @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_float_t = double; + + /// @} + + private: + + /// helper for exception-safe object creation + template + static T* create(Args&& ... args) + { + std::allocator alloc; + auto deleter = [&](T * object) + { + alloc.deallocate(object, 1); + }; + std::unique_ptr object(alloc.allocate(1), deleter); + alloc.construct(object.get(), std::forward(args)...); + assert(object != nullptr); + return object.release(); + } + + //////////////////////// + // JSON value storage // + //////////////////////// + + public: + /*! + @brief a JSON value + + The actual storage for a JSON value of the @ref json class. This + union combines the different storage types for the JSON value types + defined in @ref value_t. + + JSON type | value_t type | used type + --------- | --------------- | ------------------------ + object | object | pointer to @ref object_t + array | array | pointer to @ref array_t + string | string | pointer to std::string + boolean | boolean | bool + number | number_integer | std::int64_t + number | number_unsigned | std::uint64_t + number | number_float | double + null | null | *no value is stored* + + @note Variable-length types (objects, arrays, and strings) are stored as + pointers. The size of the union should not exceed 64 bits if the default + value types are used. + + @since version 1.0.0 + */ + union json_value + { + /// object (stored with pointer to save storage) + object_t* object; + /// array (stored with pointer to save storage) + array_t* array; + /// string (stored with pointer to save storage) + std::string* string; + /// boolean + bool boolean; + /// number (integer) + std::int64_t number_integer; + /// number (unsigned integer) + std::uint64_t number_unsigned; + /// number (floating-point) + double number_float; + + /// default constructor (for null values) + json_value() = default; + /// constructor for booleans + json_value(bool v) noexcept : boolean(v) {} + /// constructor for numbers (integer) + json_value(std::int64_t v) noexcept : number_integer(v) {} + /// constructor for numbers (unsigned) + json_value(std::uint64_t v) noexcept : number_unsigned(v) {} + /// constructor for numbers (floating-point) + json_value(double v) noexcept : number_float(v) {} + /// constructor for empty values of a given type + json_value(value_t t); + + /// constructor for strings + json_value(llvm::StringRef value); + json_value(const std::string& value); + + /// constructor for objects + json_value(const object_t& value); + + /// constructor for arrays + json_value(const array_t& value); + }; + + private: + /*! + @brief checks the class invariants + + This function asserts the class invariants. It needs to be called at the + end of every constructor to make sure that created objects respect the + invariant. Furthermore, it has to be called each time the type of a JSON + value is changed, because the invariant expresses a relationship between + @a m_type and @a m_value. + */ + void assert_invariant() const + { + assert(m_type != value_t::object || m_value.object != nullptr); + assert(m_type != value_t::array || m_value.array != nullptr); + assert(m_type != value_t::string || m_value.string != nullptr); + } + + public: + ////////////////////////// + // JSON parser callback // + ////////////////////////// + + /*! + @brief JSON callback events + + This enumeration lists the parser events that can trigger calling a + callback function of type @ref parser_callback_t during parsing. + + @image html callback_events.png "Example when certain parse events are triggered" + + @since version 1.0.0 + */ + enum class parse_event_t : uint8_t + { + /// the parser read `{` and started to process a JSON object + object_start, + /// the parser read `}` and finished processing a JSON object + object_end, + /// the parser read `[` and started to process a JSON array + array_start, + /// the parser read `]` and finished processing a JSON array + array_end, + /// the parser read a key of a value in an object + key, + /// the parser finished reading a JSON value + value + }; + + /*! + @brief per-element parser callback type + + With a parser callback function, the result of parsing a JSON text can be + influenced. When passed to @ref parse(wpi::raw_istream&, const + parser_callback_t) or @ref parse(const CharT, const parser_callback_t), + it is called on certain events (passed as @ref parse_event_t via parameter + @a event) with a set recursion depth @a depth and context JSON value + @a parsed. The return value of the callback function is a boolean + indicating whether the element that emitted the callback shall be kept or + not. + + We distinguish six scenarios (determined by the event type) in which the + callback function can be called. The following table describes the values + of the parameters @a depth, @a event, and @a parsed. + + parameter @a event | description | parameter @a depth | parameter @a parsed + ------------------ | ----------- | ------------------ | ------------------- + parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded + parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key + parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object + parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded + parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array + parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value + + @image html callback_events.png "Example when certain parse events are triggered" + + Discarding a value (i.e., returning `false`) has different effects + depending on the context in which function was called: + + - Discarded values in structured types are skipped. That is, the parser + will behave as if the discarded value was never read. + - In case a value outside a structured type is skipped, it is replaced + with `null`. This case happens if the top-level element is skipped. + + @param[in] depth the depth of the recursion during parsing + + @param[in] event an event of type parse_event_t indicating the context in + the callback function has been called + + @param[in,out] parsed the current intermediate parse result; note that + writing to this value has no effect for parse_event_t::key events + + @return Whether the JSON value which called the function during parsing + should be kept (`true`) or not (`false`). In the latter case, it is either + skipped completely or replaced by an empty discarded object. + + @sa @ref parse(wpi::raw_istream&, parser_callback_t) or + @ref parse(const CharT, const parser_callback_t) for examples + + @since version 1.0.0 + */ + using parser_callback_t = std::function; + + + ////////////////// + // constructors // + ////////////////// + + /// @name constructors and destructors + /// Constructors of class @ref json, copy/move constructor, copy + /// assignment, static functions creating objects, and the destructor. + /// @{ + + /*! + @brief create an empty value with a given type + + Create an empty JSON value with a given type. The value will be default + initialized with an empty value which depends on the type: + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + object | `{}` + array | `[]` + + @param[in] value_type the type of the value to create + + @complexity Constant. + + @liveexample{The following code shows the constructor for different @ref + value_t values,json__value_t} + + @since version 1.0.0 + */ + json(const value_t value_type) + : m_type(value_type), m_value(value_type) + { + assert_invariant(); + } + + /*! + @brief create a null object + + Create a `null` JSON value. It either takes a null pointer as parameter + (explicitly creating `null`) or no parameter (implicitly creating `null`). + The passed null pointer itself is not read -- it is only used to choose + the right constructor. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this constructor never throws + exceptions. + + @liveexample{The following code shows the constructor with and without a + null pointer parameter.,json__nullptr_t} + + @since version 1.0.0 + */ + json(std::nullptr_t = nullptr) noexcept + : json(value_t::null) + { + assert_invariant(); + } + + /*! + @brief create a JSON value + + This is a "catch all" constructor for all compatible JSON types; that is, + types for which a `to_json()` method exsits. The constructor forwards the + parameter @a val to that method (to `json_serializer::to_json` method + with `U = uncvref_t`, to be exact). + + Template type @a CompatibleType includes, but is not limited to, the + following types: + - **arrays**: @ref array_t and all kinds of compatible containers such as + `std::vector`, `std::deque`, `std::list`, `std::forward_list`, + `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and + `unordered_multiset` with a `value_type` from which a @ref json + value can be constructed. + - **objects**: @ref object_t and all kinds of compatible associative + containers such as `std::map`, `std::unordered_map`, `std::multimap`, + and `std::unordered_multimap` with a `key_type` compatible to + std::string and a `value_type` from which a @ref json value can + be constructed. + - **strings**: std::string, string literals, and all compatible string + containers can be used. + - **numbers**: std::int64_t, std::uint64_t, + double, and all convertible number types such as `int`, + `size_t`, `int64_t`, `float` or `double` can be used. + - **boolean**: `bool` can be used. + + See the examples below. + + @tparam CompatibleType a type such that: + - @a CompatibleType is not derived from `wpi::raw_istream`, + - @a CompatibleType is not @ref json (to avoid hijacking copy/move + constructors), + - @a CompatibleType is not a @ref json nested type (e.g., + @ref json_pointer, @ref iterator, etc ...) + - @ref @ref json_serializer has a + `to_json(json&, CompatibleType&&)` method + + @tparam U = `uncvref_t` + + @param[in] val the value to be forwarded + + @complexity Usually linear in the size of the passed @a val, also + depending on the implementation of the called `to_json()` + method. + + @throw what `json_serializer::to_json()` throws + + @liveexample{The following code shows the constructor with several + compatible types.,json__CompatibleType} + + @since version 2.1.0 + */ + template, + detail::enable_if_t::value && + !std::is_same::value && + !detail::is_json_nested_type::value, + int> = 0> + json(CompatibleType && val) + { + to_json(*this, std::forward(val)); + assert_invariant(); + } + + /*! + @brief create a container (array or object) from an initializer list + + Creates a JSON value of type array or object from the passed initializer + list @a init. In case @a type_deduction is `true` (default), the type of + the JSON value to be created is deducted from the initializer list @a init + according to the following rules: + + 1. If the list is empty, an empty JSON object value `{}` is created. + 2. If the list consists of pairs whose first element is a string, a JSON + object value is created where the first elements of the pairs are + treated as keys and the second elements are as values. + 3. In all other cases, an array is created. + + The rules aim to create the best fit between a C++ initializer list and + JSON values. The rationale is as follows: + + 1. The empty initializer list is written as `{}` which is exactly an empty + JSON object. + 2. C++ has now way of describing mapped types other than to list a list of + pairs. As JSON requires that keys must be of type string, rule 2 is the + weakest constraint one can pose on initializer lists to interpret them + as an object. + 3. In all other cases, the initializer list could not be interpreted as + JSON object type, so interpreting it as JSON array type is safe. + + With the rules described above, the following JSON values cannot be + expressed by an initializer list: + + - the empty array (`[]`): use @ref array(std::initializer_list) + with an empty initializer list in this case + - arrays whose elements satisfy rule 2: use @ref + array(std::initializer_list) with the same initializer list + in this case + + @note When used without parentheses around an empty initializer list, @ref + json() is called instead of this function, yielding the JSON null + value. + + @param[in] init initializer list with JSON values + + @param[in] type_deduction internal parameter; when set to `true`, the type + of the JSON value is deducted from the initializer list @a init; when set + to `false`, the type provided via @a manual_type is forced. This mode is + used by the functions @ref array(std::initializer_list) and + @ref object(std::initializer_list). + + @param[in] manual_type internal parameter; when @a type_deduction is set + to `false`, the created JSON value will use the provided type (only @ref + value_t::array and @ref value_t::object are valid); when @a type_deduction + is set to `true`, this parameter has no effect + + @throw type_error.301 if @a type_deduction is `false`, @a manual_type is + `value_t::object`, but @a init contains an element which is not a pair + whose first element is a string. In this case, the constructor could not + create an object. If @a type_deduction would have be `true`, an array + would have been created. See @ref object(std::initializer_list) + for an example. + + @complexity Linear in the size of the initializer list @a init. + + @liveexample{The example below shows how JSON values are created from + initializer lists.,json__list_init_t} + + @sa @ref array(std::initializer_list) -- create a JSON array + value from an initializer list + @sa @ref object(std::initializer_list) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + json(std::initializer_list init, + bool type_deduction = true, + value_t manual_type = value_t::array); + + /*! + @brief explicitly create an array from an initializer list + + Creates a JSON array value from a given initializer list. That is, given a + list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the + initializer list is empty, the empty array `[]` is created. + + @note This function is only needed to express two edge cases that cannot + be realized with the initializer list constructor (@ref + json(std::initializer_list, bool, value_t)). These cases + are: + 1. creating an array whose elements are all pairs whose first element is a + string -- in this case, the initializer list constructor would create an + object, taking the first elements as keys + 2. creating an empty array -- passing the empty initializer list to the + initializer list constructor yields an empty object + + @param[in] init initializer list with JSON values to create an array from + (optional) + + @return JSON array value + + @complexity Linear in the size of @a init. + + @liveexample{The following code shows an example for the `array` + function.,array} + + @sa @ref json(std::initializer_list, bool, value_t) -- + create a JSON value from an initializer list + @sa @ref object(std::initializer_list) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + static json array(std::initializer_list init = + std::initializer_list()) + { + return json(init, false, value_t::array); + } + + /*! + @brief explicitly create an object from an initializer list + + Creates a JSON object value from a given initializer list. The initializer + lists elements must be pairs, and their first elements must be strings. If + the initializer list is empty, the empty object `{}` is created. + + @note This function is only added for symmetry reasons. In contrast to the + related function @ref array(std::initializer_list), there are + no cases which can only be expressed by this function. That is, any + initializer list @a init can also be passed to the initializer list + constructor @ref json(std::initializer_list, bool, value_t). + + @param[in] init initializer list to create an object from (optional) + + @return JSON object value + + @throw type_error.301 if @a init is not a list of pairs whose first + elements are strings. In this case, no object can be created. When such a + value is passed to @ref json(std::initializer_list, bool, value_t), + an array would have been created from the passed initializer list @a init. + See example below. + + @complexity Linear in the size of @a init. + + @liveexample{The following code shows an example for the `object` + function.,object} + + @sa @ref json(std::initializer_list, bool, value_t) -- + create a JSON value from an initializer list + @sa @ref array(std::initializer_list) -- create a JSON array + value from an initializer list + + @since version 1.0.0 + */ + static json object(std::initializer_list init = + std::initializer_list()) + { + return json(init, false, value_t::object); + } + + /*! + @brief construct an array with count copies of given value + + Constructs a JSON array value by creating @a cnt copies of a passed value. + In case @a cnt is `0`, an empty array is created. As postcondition, + `std::distance(begin(),end()) == cnt` holds. + + @param[in] cnt the number of JSON copies of @a val to create + @param[in] val the JSON value to copy + + @complexity Linear in @a cnt. + + @liveexample{The following code shows examples for the @ref + json(size_type\, const json&) + constructor.,json__size_type_json} + + @since version 1.0.0 + */ + json(size_type cnt, const json& val); + + /*! + @brief construct a JSON container given an iterator range + + Constructs the JSON value with the contents of the range `[first, last)`. + The semantics depends on the different types a JSON value can have: + - In case of primitive types (number, boolean, or string), @a first must + be `begin()` and @a last must be `end()`. In this case, the value is + copied. Otherwise, invalid_iterator.204 is thrown. + - In case of structured types (array, object), the constructor behaves as + similar versions for `std::vector`. + - In case of a null type, invalid_iterator.206 is thrown. + + @tparam InputIT an input iterator type (@ref iterator or @ref + const_iterator) + + @param[in] first begin of the range to copy from (included) + @param[in] last end of the range to copy from (excluded) + + @pre Iterators @a first and @a last must be initialized. **This + precondition is enforced with an assertion.** + + @pre Range `[first, last)` is valid. Usually, this precondition cannot be + checked efficiently. Only certain edge cases are detected; see the + description of the exceptions below. + + @throw invalid_iterator.201 if iterators @a first and @a last are not + compatible (i.e., do not belong to the same JSON value). In this case, + the range `[first, last)` is undefined. + @throw invalid_iterator.204 if iterators @a first and @a last belong to a + primitive type (number, boolean, or string), but @a first does not point + to the first element any more. In this case, the range `[first, last)` is + undefined. See example code below. + @throw invalid_iterator.206 if iterators @a first and @a last belong to a + null value. In this case, the range `[first, last)` is undefined. + + @complexity Linear in distance between @a first and @a last. + + @liveexample{The example below shows several ways to create JSON values by + specifying a subrange with iterators.,json__InputIt_InputIt} + + @since version 1.0.0 + */ + template::value || + std::is_same::value, int>::type = 0> + json(InputIT first, InputIT last) + { + assert(first.m_object != nullptr); + assert(last.m_object != nullptr); + + // make sure iterator fits the current value + if (first.m_object != last.m_object) + { + JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); + } + + // copy type from first iterator + m_type = first.m_object->m_type; + + // check if iterator range is complete for primitive values + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end()) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range")); + } + break; + } + + default: + { + break; + } + } + + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = first.m_object->m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = first.m_object->m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value.number_float = first.m_object->m_value.number_float; + break; + } + + case value_t::boolean: + { + m_value.boolean = first.m_object->m_value.boolean; + break; + } + + case value_t::string: + { + m_value = *first.m_object->m_value.string; + break; + } + + case value_t::array: + { + m_value.array = create(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + default: + { + JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + + first.m_object->type_name())); + } + } + + assert_invariant(); + } + + + /////////////////////////////////////// + // other constructors and destructor // + /////////////////////////////////////// + + /*! + @brief copy constructor + + Creates a copy of a given JSON value. + + @param[in] other the JSON value to copy + + @complexity Linear in the size of @a other. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is linear. + - As postcondition, it holds: `other == json(other)`. + + @liveexample{The following code shows an example for the copy + constructor.,json__json} + + @since version 1.0.0 + */ + json(const json& other); + + /*! + @brief move constructor + + Move constructor. Constructs a JSON value with the contents of the given + value @a other using move semantics. It "steals" the resources from @a + other and leaves it as JSON null value. + + @param[in,out] other value to move to this object + + @post @a other is a JSON null value + + @complexity Constant. + + @liveexample{The code below shows the move constructor explicitly called + via std::move.,json__moveconstructor} + + @since version 1.0.0 + */ + json(json&& other) noexcept + : m_type(std::move(other.m_type)), + m_value(std::move(other.m_value)) + { + // check that passed value is valid + other.assert_invariant(); + + // invalidate payload + other.m_type = value_t::null; + other.m_value = {}; + + assert_invariant(); + } + + /*! + @brief copy assignment + + Copy assignment operator. Copies a JSON value via the "copy and swap" + strategy: It is expressed in terms of the copy constructor, destructor, + and the swap() member function. + + @param[in] other value to copy from + + @complexity Linear. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is linear. + + @liveexample{The code below shows and example for the copy assignment. It + creates a copy of value `a` which is then swapped with `b`. Finally\, the + copy of `a` (which is the null value after the swap) is + destroyed.,json__copyassignment} + + @since version 1.0.0 + */ + reference& operator=(json other) noexcept ( + std::is_nothrow_move_constructible::value && + std::is_nothrow_move_assignable::value && + std::is_nothrow_move_constructible::value && + std::is_nothrow_move_assignable::value + ) + { + // check that passed value is valid + other.assert_invariant(); + + using std::swap; + swap(m_type, other.m_type); + swap(m_value, other.m_value); + + assert_invariant(); + return *this; + } + + /*! + @brief destructor + + Destroys the JSON value and frees all allocated memory. + + @complexity Linear. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is linear. + - All stored elements are destroyed and all memory is freed. + + @since version 1.0.0 + */ + ~json(); + + /// @} + + public: + /////////////////////// + // object inspection // + /////////////////////// + + /// @name object inspection + /// Functions to inspect the type of a JSON value. + /// @{ + + /*! + @brief serialization + + Serialization function for JSON values. The function tries to mimic + Python's `json.dumps()` function, and currently supports its @a indent + parameter. + + @param[in] indent If indent is nonnegative, then array elements and object + members will be pretty-printed with that indent level. An indent level of + `0` will only insert newlines. `-1` (the default) selects the most compact + representation. + + @return string containing the serialization of the JSON value + + @complexity Linear. + + @liveexample{The following example shows the effect of different @a indent + parameters to the result of the serialization.,dump} + + @see https://docs.python.org/2/library/json.html#json.dump + + @since version 1.0.0; indentaction character added in version 3.0.0 + */ + std::string dump(const int indent = -1) const; + + /*! + @brief serialization + + Serialization function for JSON values. The function tries to mimic + Python's `json.dumps()` function, and currently supports its @a indent + parameter. + + @param[in,out] os Output stream + @param[in] indent If indent is nonnegative, then array elements and object + members will be pretty-printed with that indent level. An indent level of + `0` will only insert newlines. `-1` (the default) selects the most compact + representation. + + @complexity Linear. + + @liveexample{The following example shows the effect of different @a indent + parameters to the result of the serialization.,dump} + + @see https://docs.python.org/2/library/json.html#json.dump + + @since version 1.0.0; indentaction character added in version 3.0.0 + */ + void dump(llvm::raw_ostream& os, int indent = -1) const; + + /*! + @brief return the type of the JSON value (explicit) + + Return the type of the JSON value as a value from the @ref value_t + enumeration. + + @return the type of the JSON value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `type()` for all JSON + types.,type} + + @since version 1.0.0 + */ + value_t type() const noexcept + { + return m_type; + } + + /*! + @brief return whether type is primitive + + This function returns true iff the JSON type is primitive (string, number, + boolean, or null). + + @return `true` if type is primitive (string, number, boolean, or null), + `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_primitive()` for all JSON + types.,is_primitive} + + @sa @ref is_structured() -- returns whether JSON value is structured + @sa @ref is_null() -- returns whether JSON value is `null` + @sa @ref is_string() -- returns whether JSON value is a string + @sa @ref is_boolean() -- returns whether JSON value is a boolean + @sa @ref is_number() -- returns whether JSON value is a number + + @since version 1.0.0 + */ + bool is_primitive() const noexcept + { + return is_null() || is_string() || is_boolean() || is_number(); + } + + /*! + @brief return whether type is structured + + This function returns true iff the JSON type is structured (array or + object). + + @return `true` if type is structured (array or object), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_structured()` for all JSON + types.,is_structured} + + @sa @ref is_primitive() -- returns whether value is primitive + @sa @ref is_array() -- returns whether value is an array + @sa @ref is_object() -- returns whether value is an object + + @since version 1.0.0 + */ + bool is_structured() const noexcept + { + return is_array() || is_object(); + } + + /*! + @brief return whether value is null + + This function returns true iff the JSON value is null. + + @return `true` if type is null, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_null()` for all JSON + types.,is_null} + + @since version 1.0.0 + */ + bool is_null() const noexcept + { + return m_type == value_t::null; + } + + /*! + @brief return whether value is a boolean + + This function returns true iff the JSON value is a boolean. + + @return `true` if type is boolean, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_boolean()` for all JSON + types.,is_boolean} + + @since version 1.0.0 + */ + bool is_boolean() const noexcept + { + return m_type == value_t::boolean; + } + + /*! + @brief return whether value is a number + + This function returns true iff the JSON value is a number. This includes + both integer and floating-point values. + + @return `true` if type is number (regardless whether integer, unsigned + integer or floating-type), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number()` for all JSON + types.,is_number} + + @sa @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + bool is_number() const noexcept + { + return is_number_integer() || is_number_float(); + } + + /*! + @brief return whether value is an integer number + + This function returns true iff the JSON value is an integer or unsigned + integer number. This excludes floating-point values. + + @return `true` if type is an integer or unsigned integer number, `false` + otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_integer()` for all + JSON types.,is_number_integer} + + @sa @ref is_number() -- check if value is a number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + bool is_number_integer() const noexcept + { + return m_type == value_t::number_integer || m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is an unsigned integer number + + This function returns true iff the JSON value is an unsigned integer + number. This excludes floating-point and (signed) integer values. + + @return `true` if type is an unsigned integer number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_unsigned()` for all + JSON types.,is_number_unsigned} + + @sa @ref is_number() -- check if value is a number + @sa @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 2.0.0 + */ + bool is_number_unsigned() const noexcept + { + return m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is a floating-point number + + This function returns true iff the JSON value is a floating-point number. + This excludes integer and unsigned integer values. + + @return `true` if type is a floating-point number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_float()` for all + JSON types.,is_number_float} + + @sa @ref is_number() -- check if value is number + @sa @ref is_number_integer() -- check if value is an integer number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + + @since version 1.0.0 + */ + bool is_number_float() const noexcept + { + return m_type == value_t::number_float; + } + + /*! + @brief return whether value is an object + + This function returns true iff the JSON value is an object. + + @return `true` if type is object, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_object()` for all JSON + types.,is_object} + + @since version 1.0.0 + */ + bool is_object() const noexcept + { + return m_type == value_t::object; + } + + /*! + @brief return whether value is an array + + This function returns true iff the JSON value is an array. + + @return `true` if type is array, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_array()` for all JSON + types.,is_array} + + @since version 1.0.0 + */ + bool is_array() const noexcept + { + return m_type == value_t::array; + } + + /*! + @brief return whether value is a string + + This function returns true iff the JSON value is a string. + + @return `true` if type is string, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_string()` for all JSON + types.,is_string} + + @since version 1.0.0 + */ + bool is_string() const noexcept + { + return m_type == value_t::string; + } + + /*! + @brief return whether value is discarded + + This function returns true iff the JSON value was discarded during parsing + with a callback function (see @ref parser_callback_t). + + @note This function will always be `false` for JSON values after parsing. + That is, discarded values can only occur during parsing, but will be + removed when inside a structured value or replaced by null in other cases. + + @return `true` if type is discarded, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_discarded()` for all JSON + types.,is_discarded} + + @since version 1.0.0 + */ + bool is_discarded() const noexcept + { + return m_type == value_t::discarded; + } + + /*! + @brief return the type of the JSON value (implicit) + + Implicitly return the type of the JSON value as a value from the @ref + value_t enumeration. + + @return the type of the JSON value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies the @ref value_t operator for + all JSON types.,operator__value_t} + + @since version 1.0.0 + */ + operator value_t() const noexcept + { + return m_type; + } + + /// @} + + private: + ////////////////// + // value access // + ////////////////// + + /// get a boolean (explicit) + bool get_impl(bool* /*unused*/) const + { + if (is_boolean()) + { + return m_value.boolean; + } + + JSON_THROW(type_error::create(302, "type must be boolean, but is " + type_name())); + } + + /// get a pointer to the value (object) + object_t* get_impl_ptr(object_t* /*unused*/) noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (object) + const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (array) + array_t* get_impl_ptr(array_t* /*unused*/) noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (array) + const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (string) + std::string* get_impl_ptr(std::string* /*unused*/) noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (string) + const std::string* get_impl_ptr(const std::string* /*unused*/) const noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (boolean) + bool* get_impl_ptr(bool* /*unused*/) noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (boolean) + const bool* get_impl_ptr(const bool* /*unused*/) const noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (integer number) + std::int64_t* get_impl_ptr(std::int64_t* /*unused*/) noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (integer number) + const std::int64_t* get_impl_ptr(const std::int64_t* /*unused*/) const noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (unsigned number) + std::uint64_t* get_impl_ptr(std::uint64_t* /*unused*/) noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (unsigned number) + const std::uint64_t* get_impl_ptr(const std::uint64_t* /*unused*/) const noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (floating-point number) + double* get_impl_ptr(double* /*unused*/) noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (floating-point number) + const double* get_impl_ptr(const double* /*unused*/) const noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /*! + @brief helper function to implement get_ref() + + This funcion helps to implement get_ref() without code duplication for + const and non-const overloads + + @tparam ThisType will be deduced as `json` or `const json` + + @throw type_error.303 if ReferenceType does not match underlying value + type of the current JSON + */ + template + static ReferenceType get_ref_impl(ThisType& obj) + { + // helper type + using PointerType = typename std::add_pointer::type; + + // delegate the call to get_ptr<>() + auto ptr = obj.template get_ptr(); + + if (ptr != nullptr) + { + return *ptr; + } + + JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + obj.type_name())); + } + + public: + /// @name value access + /// Direct access to the stored value of a JSON value. + /// @{ + + /*! + @brief get special-case overload + + This overloads avoids a lot of template boilerplate, it can be seen as the + identity method + + @tparam BasicJsonType == @ref json + + @return a copy of *this + + @complexity Constant. + + @since version 2.1.0 + */ + template < + typename BasicJsonType, + detail::enable_if_t::type, + json>::value, + int> = 0 > + json get() const + { + return *this; + } + + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value + which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) + and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType ret; + adl_serializer::from_json(*this, ret); + return ret; + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const json&, ValueType&)`, and + - @ref json_serializer does not have a `from_json()` method of + the form `ValueType from_json(const json&)` + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get__ValueType_const} + + @since version 2.1.0 + */ + template < + typename ValueTypeCV, + typename ValueType = detail::uncvref_t, + detail::enable_if_t < !std::is_same::value, int > = 0 > + ValueType get() const + { + // we cannot static_assert on ValueTypeCV being non-const, because + // there is support for get(), which is why we + // still need the uncvref + static_assert(!std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + static_assert(std::is_default_constructible::value, + "types must be DefaultConstructible when used with get()"); + + ValueType ret; + from_json(*this, ret); + return ret; + } + + /*! + @brief get a pointer value (explicit) + + Explicit pointer access to the internally stored JSON value. No copies are + made. + + @warning The pointer becomes invalid if the underlying JSON object + changes. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, std::string, bool, std::int64_t, + std::uint64_t, or double. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get__PointerType} + + @sa @ref get_ptr() for explicit pointer-member access + + @since version 1.0.0 + */ + template::value, int>::type = 0> + PointerType get() noexcept + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a pointer value (explicit) + @copydoc get() + */ + template::value, int>::type = 0> + const PointerType get() const noexcept + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a pointer value (implicit) + + Implicit pointer access to the internally stored JSON value. No copies are + made. + + @warning Writing data to the pointee of the result yields an undefined + state. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, std::string, bool, std::int64_t, + std::uint64_t, or double. Enforced by a static + assertion. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get_ptr} + + @since version 1.0.0 + */ + template::value, int>::type = 0> + PointerType get_ptr() noexcept + { + // get the type of the PointerType (remove pointer and const) + using pointee_t = typename std::remove_const::type>::type>::type; + // make sure the type matches the allowed types + static_assert( + std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + , "incompatible pointer type"); + + // delegate the call to get_impl_ptr<>() + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a pointer value (implicit) + @copydoc get_ptr() + */ + template::value && + std::is_const::type>::value, int>::type = 0> + const PointerType get_ptr() const noexcept + { + // get the type of the PointerType (remove pointer and const) + using pointee_t = typename std::remove_const::type>::type>::type; + // make sure the type matches the allowed types + static_assert( + std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + || std::is_same::value + , "incompatible pointer type"); + + // delegate the call to get_impl_ptr<>() const + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a reference value (implicit) + + Implicit reference access to the internally stored JSON value. No copies + are made. + + @warning Writing data to the referee of the result yields an undefined + state. + + @tparam ReferenceType reference type; must be a reference to @ref array_t, + @ref object_t, std::string, bool, std::int64_t, or + double. Enforced by static assertion. + + @return reference to the internally stored JSON value if the requested + reference type @a ReferenceType fits to the JSON value; throws + type_error.303 otherwise + + @throw type_error.303 in case passed type @a ReferenceType is incompatible + with the stored JSON value; see example below + + @complexity Constant. + + @liveexample{The example shows several calls to `get_ref()`.,get_ref} + + @since version 1.1.0 + */ + template::value, int>::type = 0> + ReferenceType get_ref() + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a reference value (implicit) + @copydoc get_ref() + */ + template::value && + std::is_const::type>::value, int>::type = 0> + ReferenceType get_ref() const + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a value (implicit) + + Implicit type conversion between the JSON value and a compatible value. + The call is realized by calling @ref get() const. + + @tparam ValueType non-pointer type compatible to the JSON value, for + instance `int` for JSON integer numbers, `bool` for JSON booleans, or + `std::vector` types for JSON arrays. The character type of std::string + as well as an initializer list of this type is excluded to avoid + ambiguities as these types implicitly convert to `std::string`. + + @return copy of the JSON value, converted to type @a ValueType + + @throw type_error.302 in case passed type @a ValueType is incompatible + to the JSON value type (e.g., the JSON value is of type boolean, but a + string is requested); see example below + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,operator__ValueType} + + @since version 1.0.0 + */ + template < typename ValueType, typename std::enable_if < + !std::is_pointer::value && + !std::is_same::value +#ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 + && !std::is_same>::value +#endif +#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSC_VER) && _MSC_VER >1900 && defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + && !std::is_same::value +#endif + , int >::type = 0 > + operator ValueType() const + { + // delegate the call to get<>() const + return get(); + } + + /// @} + + + //////////////////// + // element access // + //////////////////// + + /// @name element access + /// Access to the JSON value. + /// @{ + + /*! + @brief access specified array element with bounds checking + + Returns a reference to the element at specified location @a idx, with + bounds checking. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw type_error.304 if the JSON value is not an array; in this case, + calling `at` with an index makes no sense. See example below. + @throw out_of_range.401 if the index @a idx is out of range of the array; + that is, `idx >= size()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 1.0.0 + + @liveexample{The example below shows how array elements can be read and + written using `at()`. It also demonstrates the different exceptions that + can be thrown.,at__size_type} + */ + reference at(size_type idx); + + /*! + @brief access specified array element with bounds checking + + Returns a const reference to the element at specified location @a idx, + with bounds checking. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw type_error.304 if the JSON value is not an array; in this case, + calling `at` with an index makes no sense. See example below. + @throw out_of_range.401 if the index @a idx is out of range of the array; + that is, `idx >= size()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 1.0.0 + + @liveexample{The example below shows how array elements can be read using + `at()`. It also demonstrates the different exceptions that can be thrown., + at__size_type_const} + */ + const_reference at(size_type idx) const; + + /*! + @brief access specified object element with bounds checking + + Returns a reference to the element at with specified key @a key, with + bounds checking. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.304 if the JSON value is not an object; in this case, + calling `at` with a key makes no sense. See example below. + @throw out_of_range.403 if the key @a key is is not stored in the object; + that is, `find(key) == end()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Logarithmic in the size of the container. + + @sa @ref operator[](llvm::StringRef) for unchecked + access by reference + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + + @liveexample{The example below shows how object elements can be read and + written using `at()`. It also demonstrates the different exceptions that + can be thrown.,at__object_t_key_type} + */ + reference at(llvm::StringRef key); + + /*! + @brief access specified object element with bounds checking + + Returns a const reference to the element at with specified key @a key, + with bounds checking. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @throw type_error.304 if the JSON value is not an object; in this case, + calling `at` with a key makes no sense. See example below. + @throw out_of_range.403 if the key @a key is is not stored in the object; + that is, `find(key) == end()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Logarithmic in the size of the container. + + @sa @ref operator[](llvm::StringRef) for unchecked + access by reference + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + + @liveexample{The example below shows how object elements can be read using + `at()`. It also demonstrates the different exceptions that can be thrown., + at__object_t_key_type_const} + */ + const_reference at(llvm::StringRef key) const; + + /*! + @brief access specified array element + + Returns a reference to the element at specified location @a idx. + + @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), + then the array is silently filled up with `null` values to make `idx` a + valid reference to the last stored element. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw type_error.305 if the JSON value is not an array or null; in that + cases, using the [] operator with an index makes no sense. + + @complexity Constant if @a idx is in the range of the array. Otherwise + linear in `idx - size()`. + + @liveexample{The example below shows how array elements can be read and + written using `[]` operator. Note the addition of `null` + values.,operatorarray__size_type} + + @since version 1.0.0 + */ + reference operator[](size_type idx); + + /*! + @brief access specified array element + + Returns a const reference to the element at specified location @a idx. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw type_error.305 if the JSON value is not an array; in that cases, + using the [] operator with an index makes no sense. + + @complexity Constant. + + @liveexample{The example below shows how array elements can be read using + the `[]` operator.,operatorarray__size_type_const} + + @since version 1.0.0 + */ + const_reference operator[](size_type idx) const; + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(llvm::StringRef) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + reference operator[](llvm::StringRef key); + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw type_error.305 if the JSON value is not an object; in that cases, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(llvm::StringRef) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + const_reference operator[](llvm::StringRef key) const; + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + template + reference operator[](T * (&key)[n]) + { + return operator[](static_cast(key)); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @note This function is required for compatibility reasons with Clang. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object; in that cases, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + template + const_reference operator[](T * (&key)[n]) const + { + return operator[](static_cast(key)); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + reference operator[](T* key) + { + return this->operator[](llvm::StringRef(key)); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw type_error.305 if the JSON value is not an object; in that cases, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + const_reference operator[](T* key) const + { + return this->operator[](llvm::StringRef(key)); + } + + /*! + @brief access specified object element with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(key); + } catch(out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(llvm::StringRef), this function + does not throw if the given key @a key was not found. + + @note Unlike @ref operator[](llvm::StringRef key), this + function does not implicitly add an element to the position defined by @a + key. This function is furthermore also applicable to const objects. + + @param[in] key key of the element to access + @param[in] default_value the value to return if @a key is not found + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw type_error.306 if the JSON value is not an objec; in that cases, + using `value()` with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,json__value} + + @sa @ref at(llvm::StringRef) for access by reference + with range checking + @sa @ref operator[](llvm::StringRef) for unchecked + access by reference + + @since version 1.0.0 + */ + template::value, int>::type = 0> + ValueType value(llvm::StringRef key, ValueType default_value) const + { + // at only works for objects + if (is_object()) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return *it; + } + + return default_value; + } + else + { + JSON_THROW(type_error::create(306, "cannot use value() with " + type_name())); + } + } + + /*! + @brief overload for a default value of type const char* + @copydoc json::value(llvm::StringRef, ValueType) const + */ + std::string value(llvm::StringRef key, const char* default_value) const + { + return value(key, std::string(default_value)); + } + + /*! + @brief access specified object element via JSON Pointer with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(ptr); + } catch(out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const json_pointer&), this function does not throw + if the given key @a key was not found. + + @param[in] ptr a JSON pointer to the element to access + @param[in] default_value the value to return if @a ptr found no value + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw type_error.306 if the JSON value is not an objec; in that cases, + using `value()` with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,json__value_ptr} + + @sa @ref operator[](const json_pointer&) for unchecked access by reference + + @since version 2.0.2 + */ + template::value, int>::type = 0> + ValueType value(const json_pointer& ptr, ValueType default_value) const + { + // at only works for objects + if (is_object()) + { + // if pointer resolves a value, return it or use default value + JSON_TRY + { + return ptr.get_checked(this); + } + JSON_CATCH (out_of_range&) + { + return default_value; + } + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + type_name())); + } + + /*! + @brief overload for a default value of type const char* + @copydoc json::value(const json_pointer&, ValueType) const + */ + std::string value(const json_pointer& ptr, const char* default_value) const + { + return value(ptr, std::string(default_value)); + } + + /*! + @brief access the first element + + Returns a reference to the first element in the container. For a JSON + container `c`, the expression `c.front()` is equivalent to `*c.begin()`. + + @return In case of a structured type (array or object), a reference to the + first element is returned. In case of number, string, or boolean values, a + reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw invalid_iterator.214 when called on `null` value + + @liveexample{The following code shows an example for `front()`.,front} + + @sa @ref back() -- access the last element + + @since version 1.0.0 + */ + reference front() + { + return *begin(); + } + + /*! + @copydoc json::front() + */ + const_reference front() const + { + return *cbegin(); + } + + /*! + @brief access the last element + + Returns a reference to the last element in the container. For a JSON + container `c`, the expression `c.back()` is equivalent to + @code {.cpp} + auto tmp = c.end(); + --tmp; + return *tmp; + @endcode + + @return In case of a structured type (array or object), a reference to the + last element is returned. In case of number, string, or boolean values, a + reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw invalid_iterator.214 when called on a `null` value. See example + below. + + @liveexample{The following code shows an example for `back()`.,back} + + @sa @ref front() -- access the first element + + @since version 1.0.0 + */ + reference back(); + + /*! + @copydoc json::back() + */ + const_reference back() const; + + /*! + @brief remove element given an iterator + + Removes the element specified by iterator @a pos. The iterator @a pos must + be valid and dereferenceable. Thus the `end()` iterator (which is valid, + but is not dereferenceable) cannot be used as a value for @a pos. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] pos iterator to the element to remove + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw type_error.307 if called on a `null` value; example: `"cannot use + erase() with null"` + @throw invalid_iterator.202 if called on an iterator which does not belong + to the current JSON value; example: `"iterator does not fit current + value"` + @throw invalid_iterator.205 if called on a primitive type with invalid + iterator (i.e., any iterator which is not `begin()`); example: `"iterator + out of range"` + + @complexity The complexity depends on the type: + - objects: amortized constant + - arrays: linear in distance between @a pos and the end of the container + - strings: linear in the length of the string + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType} + + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(llvm::StringRef) -- removes the element + from an object at the given key + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template::value || + std::is_same::value, int>::type + = 0> + void erase(IteratorType pos) + { + // make sure iterator fits the current value + if (this != pos.m_object) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (!pos.m_it.primitive_iterator.is_begin()) + { + JSON_THROW(invalid_iterator::create(205, "iterator out of range")); + } + + if (is_string()) + { + std::allocator alloc; + alloc.destroy(m_value.string); + alloc.deallocate(m_value.string, 1); + m_value.string = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + m_value.object->erase(pos.m_it.object_iterator); + break; + } + + case value_t::array: + { + m_value.array->erase(pos.m_it.array_iterator); + break; + } + + default: + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name())); + } + } + } + + /*! + @brief remove elements given an iterator range + + Removes the element specified by the range `[first; last)`. The iterator + @a first does not need to be dereferenceable if `first == last`: erasing + an empty range is a no-op. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] first iterator to the beginning of the range to remove + @param[in] last iterator past the end of the range to remove + @return Iterator following the last removed element. If the iterator @a + second refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw type_error.307 if called on a `null` value; example: `"cannot use + erase() with null"` + @throw invalid_iterator.203 if called on iterators which does not belong + to the current JSON value; example: `"iterators do not fit current value"` + @throw invalid_iterator.204 if called on a primitive type with invalid + iterators (i.e., if `first != begin()` and `last != end()`); example: + `"iterators out of range"` + + @complexity The complexity depends on the type: + - objects: `log(size()) + std::distance(first, last)` + - arrays: linear in the distance between @a first and @a last, plus linear + in the distance between @a last and end of the container + - strings: linear in the length of the string + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType_IteratorType} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(llvm::StringRef) -- removes the element + from an object at the given key + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template::value || + std::is_same::value, int>::type + = 0> + void erase(IteratorType first, IteratorType last) + { + // make sure iterator fits the current value + if (this != first.m_object || this != last.m_object) + { + JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); + } + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end()) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range")); + } + + if (is_string()) + { + std::allocator alloc; + alloc.destroy(m_value.string); + alloc.deallocate(m_value.string, 1); + m_value.string = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::array: + { + m_value.array->erase(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + default: + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name())); + } + } + } + + /*! + @brief remove element from a JSON object given a key + + Removes elements from a JSON object with the key value @a key. + + @param[in] key value of the elements to remove + + @return Number of elements removed. + The return value will always be `0` (@a key was not + found) or `1` (@a key was found). + + @post References and iterators to the erased elements are invalidated. + Other references and iterators are not affected. + + @throw type_error.307 when called on a type other than JSON object; + example: `"cannot use erase() with null"` + + @complexity `log(size()) + count(key)` + + @liveexample{The example shows the effect of `erase()`.,erase__key_type} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + size_type erase(llvm::StringRef key); + + /*! + @brief remove element from a JSON array given an index + + Removes element from a JSON array at the index @a idx. + + @param[in] idx index of the element to remove + + @throw type_error.307 when called on a type other than JSON object; + example: `"cannot use erase() with null"` + @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 + is out of range"` + + @complexity Linear in distance between @a idx and the end of the container. + + @liveexample{The example shows the effect of `erase()`.,erase__size_type} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(llvm::StringRef) -- removes the element + from an object at the given key + + @since version 1.0.0 + */ + void erase(const size_type idx); + + /// @} + + + //////////// + // lookup // + //////////// + + /// @name lookup + /// @{ + + /*! + @brief find an element in a JSON object + + Finds an element in a JSON object with key equivalent to @a key. If the + element is not found or the JSON value is not an object, end() is + returned. + + @note This method always returns @ref end() when executed on a JSON type + that is not an object. + + @param[in] key key value of the element to search for + + @return Iterator to an element with key equivalent to @a key. If no such + element is found or the JSON value is not an object, past-the-end (see + @ref end()) iterator is returned. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `find()` is used.,find__key_type} + + @since version 1.0.0 + */ + iterator find(llvm::StringRef key); + + /*! + @brief find an element in a JSON object + @copydoc find(llvm::StringRef) + */ + const_iterator find(llvm::StringRef key) const; + + /*! + @brief returns the number of occurrences of a key in a JSON object + + Returns the number of elements with key @a key. + The return value will always be `0` (@a key was + not found) or `1` (@a key was found). + + @note This method always returns `0` when executed on a JSON type that is + not an object. + + @param[in] key key value of the element to count + + @return Number of elements with key @a key. If the JSON value is not an + object, the return value will be `0`. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `count()` is used.,count} + + @since version 1.0.0 + */ + size_type count(llvm::StringRef key) const + { + // return 0 for all nonobject types + return is_object() ? m_value.object->count(key) : 0; + } + + /// @} + + + /////////////// + // iterators // + /////////////// + + /// @name iterators + /// @{ + + /*! + @brief returns an iterator to the first element + + Returns an iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator to the first element + + @complexity Constant. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `begin()`.,begin} + + @sa @ref cbegin() -- returns a const iterator to the beginning + @sa @ref end() -- returns an iterator to the end + @sa @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + iterator begin() noexcept + { + iterator result(this); + result.set_begin(); + return result; + } + + /*! + @copydoc json::cbegin() + */ + const_iterator begin() const noexcept + { + return cbegin(); + } + + /*! + @brief returns a const iterator to the first element + + Returns a const iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator to the first element + + @complexity Constant. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).begin()`. + + @liveexample{The following code shows an example for `cbegin()`.,cbegin} + + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref end() -- returns an iterator to the end + @sa @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + const_iterator cbegin() const noexcept + { + const_iterator result(this); + result.set_begin(); + return result; + } + + /*! + @brief returns an iterator to one past the last element + + Returns an iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator one past the last element + + @complexity Constant. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `end()`.,end} + + @sa @ref cend() -- returns a const iterator to the end + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + iterator end() noexcept + { + iterator result(this); + result.set_end(); + return result; + } + + /*! + @copydoc json::cend() + */ + const_iterator end() const noexcept + { + return cend(); + } + + /*! + @brief returns a const iterator to one past the last element + + Returns a const iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator one past the last element + + @complexity Constant. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).end()`. + + @liveexample{The following code shows an example for `cend()`.,cend} + + @sa @ref end() -- returns an iterator to the end + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + const_iterator cend() const noexcept + { + const_iterator result(this); + result.set_end(); + return result; + } + + private: + // forward declaration + template class iteration_proxy; + + public: + /*! + @brief wrapper to access iterator member functions in range-based for + + This function allows to access @ref iterator::key() and @ref + iterator::value() during range-based for loops. In these loops, a + reference to the JSON values is returned, so there is no access to the + underlying iterator. + + @liveexample{The following code shows how the wrapper is used,iterator_wrapper} + + @note The name of this function is not yet final and may change in the + future. + */ + static iteration_proxy iterator_wrapper(reference cont) + { + return iteration_proxy(cont); + } + + /*! + @copydoc iterator_wrapper(reference) + */ + static iteration_proxy iterator_wrapper(const_reference cont) + { + return iteration_proxy(cont); + } + + /// @} + + + ////////////// + // capacity // + ////////////// + + /// @name capacity + /// @{ + + /*! + @brief checks whether the container is empty + + Checks if a JSON value has no elements. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `true` + boolean | `false` + string | `false` + number | `false` + object | result of function `object_t::empty()` + array | result of function `array_t::empty()` + + @note This function does not return whether a string stored as JSON value + is empty - it returns whether the JSON container itself is empty which is + false in the case of a string. + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `empty()` functions have constant + complexity. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `begin() == end()`. + + @liveexample{The following code uses `empty()` to check if a JSON + object contains any elements.,empty} + + @sa @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + bool empty() const noexcept; + + /*! + @brief returns the number of elements + + Returns the number of elements in a JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` + boolean | `1` + string | `1` + number | `1` + object | result of function object_t::size() + array | result of function array_t::size() + + @note This function does not return the length of a string stored as JSON + value - it returns the number of elements in the JSON value which is 1 in + the case of a string. + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their size() functions have constant + complexity. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `std::distance(begin(), end())`. + + @liveexample{The following code calls `size()` on the different value + types.,size} + + @sa @ref empty() -- checks whether the container is empty + @sa @ref max_size() -- returns the maximal number of elements + + @since version 1.0.0 + */ + size_type size() const noexcept; + + /*! + @brief returns the maximum possible number of elements + + Returns the maximum number of elements a JSON value is able to hold due to + system or library implementation limitations, i.e. `std::distance(begin(), + end())` for the JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` (same as `size()`) + boolean | `1` (same as `size()`) + string | `1` (same as `size()`) + number | `1` (same as `size()`) + object | result of function `object_t::max_size()` + array | result of function `array_t::max_size()` + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `max_size()` functions have constant + complexity. + + @requirement This function helps `json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of returning `b.size()` where `b` is the largest + possible JSON value. + + @liveexample{The following code calls `max_size()` on the different value + types. Note the output is implementation specific.,max_size} + + @sa @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + size_type max_size() const noexcept; + + /// @} + + + /////////////// + // modifiers // + /////////////// + + /// @name modifiers + /// @{ + + /*! + @brief clears the contents + + Clears the content of a JSON value and resets it to the default value as + if @ref json(value_t) would have been called: + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + object | `{}` + array | `[]` + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows the effect of `clear()` to different + JSON types.,clear} + + @since version 1.0.0 + */ + void clear() noexcept; + + /*! + @brief add an object to an array + + Appends the given element @a val to the end of the JSON value. If the + function is called on a JSON null value, an empty array is created before + appending @a val. + + @param[in] val the value to add to the JSON array + + @throw type_error.308 when called on a type other than JSON array or + null; example: `"cannot use push_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON array. Note how the `null` value was silently + converted to a JSON array.,push_back} + + @since version 1.0.0 + */ + void push_back(json&& val); + + /*! + @brief add an object to an array + @copydoc push_back(json&&) + */ + reference operator+=(json&& val) + { + push_back(std::move(val)); + return *this; + } + + /*! + @brief add an object to an array + @copydoc push_back(json&&) + */ + void push_back(const json& val); + + /*! + @brief add an object to an array + @copydoc push_back(json&&) + */ + reference operator+=(const json& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + Inserts the given element @a val to the JSON object. If the function is + called on a JSON null value, an empty object is created before inserting + @a val. + + @param[in] val the value to add to the JSON object + + @throw type_error.308 when called on a type other than JSON object or + null; example: `"cannot use push_back() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON object. Note how the `null` value was silently + converted to a JSON object.,push_back__object_t__value} + + @since version 1.0.0 + */ + void push_back(const std::pair& val); + + /*! + @brief add an object to an object + @copydoc push_back(const typename object_t::value_type&) + */ + reference operator+=(const std::pair& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + This function allows to use `push_back` with an initializer list. In case + + 1. the current value is an object, + 2. the initializer list @a init contains only two elements, and + 3. the first element of @a init is a string, + + @a init is converted into an object element and added using + @ref push_back(const typename object_t::value_type&). Otherwise, @a init + is converted to a JSON value and added using @ref push_back(json&&). + + @param[in] init an initializer list + + @complexity Linear in the size of the initializer list @a init. + + @note This function is required to resolve an ambiguous overload error, + because pairs like `{"key", "value"}` can be both interpreted as + `object_t::value_type` or `std::initializer_list`, see + https://github.com/nlohmann/json/issues/235 for more information. + + @liveexample{The example shows how initializer lists are treated as + objects when possible.,push_back__initializer_list} + */ + void push_back(std::initializer_list init); + + /*! + @brief add an object to an object + @copydoc push_back(std::initializer_list) + */ + reference operator+=(std::initializer_list init) + { + push_back(init); + return *this; + } + + /*! + @brief add an object to an array + + Creates a JSON value from the passed parameters @a args to the end of the + JSON value. If the function is called on a JSON null value, an empty array + is created before appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref json + @tparam Args compatible types to create a @ref json object + + @throw type_error.311 when called on a type other than JSON array or + null; example: `"cannot use emplace_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` can be used to add + elements to a JSON array. Note how the `null` value was silently converted + to a JSON array.,emplace_back} + + @since version 2.0.8 + */ + template + void emplace_back(Args&& ... args) + { + // emplace_back only works for null objects or arrays + if (!(is_null() || is_array())) + { + JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + type_name())); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (perfect forwarding) + m_value.array->emplace_back(std::forward(args)...); + } + + /*! + @brief add an object to an object if key does not exist + + Inserts a new element into a JSON object constructed in-place with the + given @a args if there is no element with the key in the container. If the + function is called on a JSON null value, an empty object is created before + appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref json + @tparam Args compatible types to create a @ref json object + + @return a pair consisting of an iterator to the inserted element, or the + already-existing element if no insertion happened, and a bool + denoting whether the insertion took place. + + @throw type_error.311 when called on a type other than JSON object or + null; example: `"cannot use emplace() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `emplace()` can be used to add elements + to a JSON object. Note how the `null` value was silently converted to a + JSON object. Further note how no value is added if there was already one + value stored with the same key.,emplace} + + @since version 2.0.8 + */ + template + std::pair emplace(llvm::StringRef key, Args&& ... args) + { + // emplace only works for null objects or arrays + if (!(is_null() || is_object())) + { + JSON_THROW(type_error::create(311, "cannot use emplace() with " + type_name())); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array (perfect forwarding) + auto res = m_value.object->emplace_second(key, std::forward(args)...); + // create result iterator and set iterator to the result of emplace + auto it = begin(); + it.m_it.object_iterator = res.first; + + // return pair of iterator and boolean + return {it, res.second}; + } + + /*! + @brief inserts element + + Inserts element @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] val element to insert + @return iterator pointing to the inserted @a val. + + @throw type_error.309 if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @complexity Constant plus linear in the distance between @a pos and end of + the container. + + @liveexample{The example shows how `insert()` is used.,insert} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const json& val); + + /*! + @brief inserts element + @copydoc insert(const_iterator, const json&) + */ + iterator insert(const_iterator pos, json&& val) + { + return insert(pos, val); + } + + /*! + @brief inserts elements + + Inserts @a cnt copies of @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] cnt number of copies of @a val to insert + @param[in] val element to insert + @return iterator pointing to the first element inserted, or @a pos if + `cnt==0` + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @complexity Linear in @a cnt plus linear in the distance between @a pos + and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__count} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, size_type cnt, const json& val); + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)` before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + @throw invalid_iterator.211 if @a first or @a last are iterators into + container for which insert is called; example: `"passed iterators may not + belong to container"` + + @return iterator pointing to the first element inserted, or @a pos if + `first==last` + + @complexity Linear in `std::distance(first, last)` plus linear in the + distance between @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__range} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const_iterator first, const_iterator last); + + /*! + @brief inserts elements + + Inserts elements from initializer list @a ilist before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] ilist initializer list to insert the values from + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @return iterator pointing to the first element inserted, or @a pos if + `ilist` is empty + + @complexity Linear in `ilist.size()` plus linear in the distance between + @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__ilist} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, std::initializer_list ilist); + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)`. + + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.309 if called on JSON values other than objects; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if iterator @a first or @a last does does not + point to an object; example: `"iterators first and last must point to + objects"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + + @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number + of elements to insert. + + @liveexample{The example shows how `insert()` is used.,insert__range_object} + + @since version 3.0.0 + */ + void insert(const_iterator first, const_iterator last); + + /*! + @brief exchanges the values + + Exchanges the contents of the JSON value with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other JSON value to exchange the contents with + + @complexity Constant. + + @liveexample{The example below shows how JSON values can be swapped with + `swap()`.,swap__reference} + + @since version 1.0.0 + */ + void swap(reference other) noexcept ( + std::is_nothrow_move_constructible::value && + std::is_nothrow_move_assignable::value && + std::is_nothrow_move_constructible::value && + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_type, other.m_type); + std::swap(m_value, other.m_value); + assert_invariant(); + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON array with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other array to exchange the contents with + + @throw type_error.310 when JSON value is not an array; example: `"cannot + use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how arrays can be swapped with + `swap()`.,swap__array_t} + + @since version 1.0.0 + */ + void swap(array_t& other) + { + // swap only works for arrays + if (is_array()) + { + std::swap(*(m_value.array), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name())); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON object with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other object to exchange the contents with + + @throw type_error.310 when JSON value is not an object; example: + `"cannot use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how objects can be swapped with + `swap()`.,swap__object_t} + + @since version 1.0.0 + */ + void swap(object_t& other) + { + // swap only works for objects + if (is_object()) + { + std::swap(*(m_value.object), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name())); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON string with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other string to exchange the contents with + + @throw type_error.310 when JSON value is not a string; example: `"cannot + use swap() with boolean"` + + @complexity Constant. + + @liveexample{The example below shows how strings can be swapped with + `swap()`.,swap__std::string} + + @since version 1.0.0 + */ + void swap(std::string& other) + { + // swap only works for strings + if (is_string()) + { + std::swap(*(m_value.string), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name())); + } + } + + /// @} + + public: + ////////////////////////////////////////// + // lexicographical comparison operators // + ////////////////////////////////////////// + + /// @name lexicographical comparison operators + /// @{ + + /*! + @brief comparison: equal + + Compares two JSON values for equality according to the following rules: + - Two JSON values are equal if (1) they are from the same type and (2) + their stored values are the same according to their respective + `operator==`. + - Integer and floating-point numbers are automatically converted before + comparison. Floating-point numbers are compared indirectly: two + floating-point numbers `f1` and `f2` are considered equal if neither + `f1 > f2` nor `f2 > f1` holds. Note than two NaN values are always + treated as unequal. + - Two JSON null values are equal. + + @note NaN values never compare equal to themselves or to other NaN values. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are equal + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__equal} + + @since version 1.0.0 + */ + friend bool operator==(const_reference lhs, const_reference rhs) noexcept; + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs == json(rhs)); + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept + { + return (json(lhs) == rhs); + } + + /*! + @brief comparison: not equal + + Compares two JSON values for inequality by calculating `not (lhs == rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are not equal + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__notequal} + + @since version 1.0.0 + */ + friend bool operator!=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs == rhs); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs != json(rhs)); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept + { + return (json(lhs) != rhs); + } + + /*! + @brief comparison: less than + + Compares whether one JSON value @a lhs is less than another JSON value @a + rhs according to the following rules: + - If @a lhs and @a rhs have the same type, the values are compared using + the default `<` operator. + - Integer and floating-point numbers are automatically converted before + comparison + - In case @a lhs and @a rhs have different types, the values are ignored + and the order of the types is considered, see + @ref operator<(const value_t, const value_t). + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__less} + + @since version 1.0.0 + */ + friend bool operator<(const_reference lhs, const_reference rhs) noexcept; + + /*! + @brief comparison: less than + @copydoc operator<(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs < json(rhs)); + } + + /*! + @brief comparison: less than + @copydoc operator<(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept + { + return (json(lhs) < rhs); + } + + /*! + @brief comparison: less than or equal + + Compares whether one JSON value @a lhs is less than or equal to another + JSON value by calculating `not (rhs < lhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than or equal to @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greater} + + @since version 1.0.0 + */ + friend bool operator<=(const_reference lhs, const_reference rhs) noexcept + { + return !(rhs < lhs); + } + + /*! + @brief comparison: less than or equal + @copydoc operator<=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs <= json(rhs)); + } + + /*! + @brief comparison: less than or equal + @copydoc operator<=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept + { + return (json(lhs) <= rhs); + } + + /*! + @brief comparison: greater than + + Compares whether one JSON value @a lhs is greater than another + JSON value by calculating `not (lhs <= rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than to @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__lessequal} + + @since version 1.0.0 + */ + friend bool operator>(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs <= rhs); + } + + /*! + @brief comparison: greater than + @copydoc operator>(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs > json(rhs)); + } + + /*! + @brief comparison: greater than + @copydoc operator>(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept + { + return (json(lhs) > rhs); + } + + /*! + @brief comparison: greater than or equal + + Compares whether one JSON value @a lhs is greater than or equal to another + JSON value by calculating `not (lhs < rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than or equal to @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greaterequal} + + @since version 1.0.0 + */ + friend bool operator>=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs < rhs); + } + + /*! + @brief comparison: greater than or equal + @copydoc operator>=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs >= json(rhs)); + } + + /*! + @brief comparison: greater than or equal + @copydoc operator>=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept + { + return (json(lhs) >= rhs); + } + + /// @} + + /////////////////// + // serialization // + /////////////////// + + /// @name serialization + /// @{ + + public: + /*! + @brief serialize to stream + + Serialize the given JSON value @a j to the output stream @a o. The JSON + value will be serialized using the @ref dump member function. + + - The indentation of the output can be controlled with the member variable + `width` of the output stream @a o. For instance, using the manipulator + `std::setw(4)` on @a o sets the indentation level to `4` and the + serialization result is the same as calling `dump(4)`. + + - The indentation characrer can be controlled with the member variable + `fill` of the output stream @a o. For instance, the manipulator + `std::setfill('\\t')` sets indentation to use a tab character rather than + the default space character. + + @param[in,out] o stream to serialize to + @param[in] j JSON value to serialize + + @return the stream @a o + + @complexity Linear. + + @liveexample{The example below shows the serialization with different + parameters to `width` to adjust the indentation level.,operator_serialize} + + @since version 1.0.0; indentaction character added in version 3.0.0 + */ + friend llvm::raw_ostream& operator<<(llvm::raw_ostream& o, const json& j); + + /// @} + + + ///////////////////// + // deserialization // + ///////////////////// + + /// @name deserialization + /// @{ + + /*! + @brief deserialize from string literal + + @tparam CharT character/literal type with size of 1 byte + @param[in] s string literal to read a serialized JSON value from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + @note String containers like `std::string` can be parsed + with @ref parse(const ContiguousContainer&, const parser_callback_t) + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__string__parser_callback_t} + + @sa @ref parse(wpi::raw_istream&, const parser_callback_t) for a version + that reads from an input stream + + @since version 1.0.0 (originally for std::string) + */ + static json parse(llvm::StringRef s, + const parser_callback_t cb = nullptr); + + /*! + @brief deserialize from stream + + @param[in,out] i stream to read a serialized JSON value from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + @throw parse_error.111 if input stream is in a bad state + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__raw_istream__parser_callback_t} + + @sa @ref parse(const CharT, const parser_callback_t) for a version + that reads from a string + + @since version 1.0.0 + */ + static json parse(wpi::raw_istream& i, + const parser_callback_t cb = nullptr); + + /*! + @brief deserialize from stream + + Deserializes an input stream to a JSON value. + + @param[in,out] i input stream to read a serialized JSON value from + @param[in,out] j JSON value to write the deserialized input to + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + @throw parse_error.111 if input stream is in a bad state + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below shows how a JSON value is constructed by + reading a serialization from a stream.,operator_deserialize} + + @sa parse(wpi::raw_istream&, const parser_callback_t) for a variant with a + parser callback function to filter values while parsing + + @since version 1.0.0 + */ + friend wpi::raw_istream& operator>>(wpi::raw_istream& i, json& j); + + /// @} + + /////////////////////////// + // convenience functions // + /////////////////////////// + + /*! + @brief return the type as string + + Returns the type name as string to be used in error messages - usually to + indicate that a function was called on a wrong JSON type. + + @return basically a string representation of a the @a m_type member + + @complexity Constant. + + @liveexample{The following code exemplifies `type_name()` for all JSON + types.,type_name} + + @since version 1.0.0, public since 2.1.0 + */ + std::string type_name() const; + + private: + ////////////////////// + // member variables // + ////////////////////// + + /// the type of the current element + value_t m_type = value_t::null; + + /// the value of the current element + json_value m_value = {}; + + + private: + /////////////// + // iterators // + /////////////// + + /*! + @brief an iterator for primitive JSON types + + This class models an iterator for primitive JSON types (boolean, number, + 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, + end_value (`1`) models past the end. + */ + class primitive_iterator_t + { + public: + + difference_type get_value() const noexcept + { + return m_it; + } + /// set iterator to a defined beginning + void set_begin() noexcept + { + m_it = begin_value; + } + + /// set iterator to a defined past the end + void set_end() noexcept + { + m_it = end_value; + } + + /// return whether the iterator can be dereferenced + constexpr bool is_begin() const noexcept + { + return (m_it == begin_value); + } + + /// return whether the iterator is at end + constexpr bool is_end() const noexcept + { + return (m_it == end_value); + } + + friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it == rhs.m_it; + } + + friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return !(lhs == rhs); + } + + friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it < rhs.m_it; + } + + friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it <= rhs.m_it; + } + + friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it > rhs.m_it; + } + + friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it >= rhs.m_it; + } + + primitive_iterator_t operator+(difference_type i) + { + auto result = *this; + result += i; + return result; + } + + friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it - rhs.m_it; + } + + friend llvm::raw_ostream& operator<<(llvm::raw_ostream& os, primitive_iterator_t it) + { + return os << it.m_it; + } + + primitive_iterator_t& operator++() + { + ++m_it; + return *this; + } + + primitive_iterator_t operator++(int) + { + auto result = *this; + m_it++; + return result; + } + + primitive_iterator_t& operator--() + { + --m_it; + return *this; + } + + primitive_iterator_t operator--(int) + { + auto result = *this; + m_it--; + return result; + } + + primitive_iterator_t& operator+=(difference_type n) + { + m_it += n; + return *this; + } + + primitive_iterator_t& operator-=(difference_type n) + { + m_it -= n; + return *this; + } + + private: + static constexpr difference_type begin_value = 0; + static constexpr difference_type end_value = begin_value + 1; + + /// iterator as signed integer type + difference_type m_it = std::numeric_limits::denorm_min(); + }; + + /*! + @brief an iterator value + + @note This structure could easily be a union, but MSVC currently does not + allow unions members with complex constructors, see + https://github.com/nlohmann/json/pull/105. + */ + struct internal_iterator + { + /// iterator for JSON objects + typename object_t::iterator object_iterator; + /// iterator for JSON arrays + typename array_t::iterator array_iterator; + /// generic iterator for all other types + primitive_iterator_t primitive_iterator; + + /// create an uninitialized internal_iterator + internal_iterator() noexcept + : object_iterator(), array_iterator(), primitive_iterator() + {} + }; + + /// proxy class for the iterator_wrapper functions + template + class iteration_proxy + { + private: + /// helper class for iteration + class iteration_proxy_internal + { + private: + /// the iterator + IteratorType anchor; + /// an index for arrays (used to create key names) + size_t array_index = 0; + + public: + explicit iteration_proxy_internal(IteratorType it) noexcept + : anchor(it) + {} + + /// dereference operator (needed for range-based for) + iteration_proxy_internal& operator*() + { + return *this; + } + + /// increment operator (needed for range-based for) + iteration_proxy_internal& operator++() + { + ++anchor; + ++array_index; + + return *this; + } + + /// inequality operator (needed for range-based for) + bool operator!= (const iteration_proxy_internal& o) const + { + return anchor != o.anchor; + } + + /// return key of the iterator + std::string key() const + { + assert(anchor.m_object != nullptr); + + switch (anchor.m_object->type()) + { + // use integer array index as key + case value_t::array: + { + return std::to_string(array_index); + } + + // use key from the object + case value_t::object: + { + return anchor.key(); + } + + // use an empty key for all primitive types + default: + { + return ""; + } + } + } + + /// return value of the iterator + typename IteratorType::reference value() const + { + return anchor.value(); + } + }; + + /// the container to iterate + typename IteratorType::reference container; + + public: + /// construct iteration proxy from a container + explicit iteration_proxy(typename IteratorType::reference cont) + : container(cont) + {} + + /// return iterator begin (needed for range-based for) + iteration_proxy_internal begin() noexcept + { + return iteration_proxy_internal(container.begin()); + } + + /// return iterator end (needed for range-based for) + iteration_proxy_internal end() noexcept + { + return iteration_proxy_internal(container.end()); + } + }; + + public: + /*! + @brief a template for a random access iterator for the @ref json class + + This class implements a both iterators (iterator and const_iterator) for the + @ref json class. + + @note An iterator is called *initialized* when a pointer to a JSON value + has been set (e.g., by a constructor or a copy assignment). If the + iterator is default-constructed, it is *uninitialized* and most + methods are undefined. **The library uses assertions to detect calls + on uninitialized iterators.** + + @requirement The class satisfies the following concept requirements: + - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): + The iterator that can be moved to point (forward and backward) to any + element in constant time. + + @since version 1.0.0, simplified in version 2.0.9 + */ + template + class iter_impl : public std::iterator + { + /// allow json to access private members + friend class json; + friend class JsonTest; + + // make sure U is json or const json + static_assert(std::is_same::value + || std::is_same::value, + "iter_impl only accepts (const) json"); + + public: + /// the type of the values when the iterator is dereferenced + using value_type = typename json::value_type; + /// a type to represent differences between iterators + using difference_type = typename json::difference_type; + /// defines a pointer to the type iterated over (value_type) + using pointer = typename std::conditional::value, + typename json::const_pointer, + typename json::pointer>::type; + /// defines a reference to the type iterated over (value_type) + using reference = typename std::conditional::value, + typename json::const_reference, + typename json::reference>::type; + /// the category of the iterator + using iterator_category = std::bidirectional_iterator_tag; + + /// default constructor + iter_impl() noexcept : m_object(nullptr) {} + + /*! + @brief constructor for a given JSON instance + @param[in] object pointer to a JSON object for this iterator + @pre object != nullptr + @post The iterator is initialized; i.e. `m_object != nullptr`. + */ + explicit iter_impl(pointer object) noexcept + : m_object(object) + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + m_it.object_iterator = typename object_t::iterator(); + break; + } + + case json::value_t::array: + { + m_it.array_iterator = typename array_t::iterator(); + break; + } + + default: + { + m_it.primitive_iterator = primitive_iterator_t(); + break; + } + } + } + + /*! + @note The conventional copy constructor and copy assignment are + implicitly defined. + Combined with the following converting constructor and assigment, + they support: copy from iterator to iterator, + copy from const iterator to const iterator, + and conversion from iterator to const iterator. + However conversion from const iterator to iterator is not defined. + */ + + /*! + @brief converting constructor + @param[in] other non-const iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl(const iter_impl& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in,out] other non-const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl& other) noexcept + { + m_object = other.m_object; + m_it = other.m_it; + return *this; + } + + private: + /*! + @brief set the iterator to the first value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_begin() noexcept + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + m_it.object_iterator = m_object->m_value.object->begin(); + break; + } + + case json::value_t::array: + { + m_it.array_iterator = m_object->m_value.array->begin(); + break; + } + + case json::value_t::null: + { + // set to end so begin()==end() is true: null is empty + m_it.primitive_iterator.set_end(); + break; + } + + default: + { + m_it.primitive_iterator.set_begin(); + break; + } + } + } + + /*! + @brief set the iterator past the last value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_end() noexcept + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + m_it.object_iterator = m_object->m_value.object->end(); + break; + } + + case json::value_t::array: + { + m_it.array_iterator = m_object->m_value.array->end(); + break; + } + + default: + { + m_it.primitive_iterator.set_end(); + break; + } + } + } + + public: + /*! + @brief return a reference to the value pointed to by the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator*() const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + assert(m_it.object_iterator != m_object->m_value.object->end()); + return m_it.object_iterator->second; + } + + case json::value_t::array: + { + assert(m_it.array_iterator != m_object->m_value.array->end()); + return *m_it.array_iterator; + } + + case json::value_t::null: + { + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + + default: + { + if (m_it.primitive_iterator.is_begin()) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + } + } + + /*! + @brief dereference the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + pointer operator->() const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + assert(m_it.object_iterator != m_object->m_value.object->end()); + return &(m_it.object_iterator->second); + } + + case json::value_t::array: + { + assert(m_it.array_iterator != m_object->m_value.array->end()); + return &*m_it.array_iterator; + } + + default: + { + if (m_it.primitive_iterator.is_begin()) + { + return m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + } + } + + /*! + @brief post-increment (it++) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator++(int) + { + auto result = *this; + ++(*this); + return result; + } + + /*! + @brief pre-increment (++it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator++() + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + ++m_it.object_iterator; + break; + } + + case json::value_t::array: + { + ++m_it.array_iterator; + break; + } + + default: + { + ++m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief post-decrement (it--) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator--(int) + { + auto result = *this; + --(*this); + return result; + } + + /*! + @brief pre-decrement (--it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator--() + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + JSON_THROW(invalid_iterator::create(209, "cannot decrement object iterators")); + break; + } + + case json::value_t::array: + { + std::advance(m_it.array_iterator, -1); + break; + } + + default: + { + --m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief comparison: equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator==(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (m_object != other.m_object) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); + } + + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + return (m_it.object_iterator == other.m_it.object_iterator); + } + + case json::value_t::array: + { + return (m_it.array_iterator == other.m_it.array_iterator); + } + + default: + { + return (m_it.primitive_iterator == other.m_it.primitive_iterator); + } + } + } + + /*! + @brief comparison: not equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator!=(const iter_impl& other) const + { + return !operator==(other); + } + + /*! + @brief comparison: smaller + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (m_object != other.m_object) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); + } + + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); + } + + case json::value_t::array: + { + return (m_it.array_iterator < other.m_it.array_iterator); + } + + default: + { + return (m_it.primitive_iterator < other.m_it.primitive_iterator); + } + } + } + + /*! + @brief comparison: less than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<=(const iter_impl& other) const + { + return !(other.operator < (*this)); + } + + /*! + @brief comparison: greater than + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>(const iter_impl& other) const + { + return !operator<=(other); + } + + /*! + @brief comparison: greater than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>=(const iter_impl& other) const + { + return !operator<(other); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator+=(difference_type i) + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); + } + + case json::value_t::array: + { + std::advance(m_it.array_iterator, i); + break; + } + + default: + { + m_it.primitive_iterator += i; + break; + } + } + + return *this; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator-=(difference_type i) + { + return operator+=(-i); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator+(difference_type i) const + { + auto result = *this; + result += i; + return result; + } + + /*! + @brief addition of distance and iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + friend iter_impl operator+(difference_type i, const iter_impl& it) + { + auto result = it; + result += i; + return result; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator-(difference_type i) const + { + auto result = *this; + result -= i; + return result; + } + + /*! + @brief return difference + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + difference_type operator-(const iter_impl& other) const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); + } + + case json::value_t::array: + { + return m_it.array_iterator - other.m_it.array_iterator; + } + + default: + { + return m_it.primitive_iterator - other.m_it.primitive_iterator; + } + } + } + + /*! + @brief access to successor + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator[](difference_type n) const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case json::value_t::object: + { + JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); + } + + case json::value_t::array: + { + return *std::next(m_it.array_iterator, n); + } + + case json::value_t::null: + { + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + + default: + { + if (m_it.primitive_iterator.get_value() == -n) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + } + } + + /*! + @brief return the key of an object iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + llvm::StringRef key() const + { + assert(m_object != nullptr); + + if (m_object->is_object()) + { + return m_it.object_iterator->first(); + } + + JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); + } + + /*! + @brief return the value of an iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference value() const + { + return operator*(); + } + + private: + /// associated JSON instance + pointer m_object; + /// the actual iterator of the associated instance + struct internal_iterator m_it = internal_iterator(); + }; + + ////////////////////////////////////////// + // binary serialization/deserialization // + ////////////////////////////////////////// + + /// @name binary serialization/deserialization support + /// @{ + + public: + /*! + @brief create a CBOR serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the CBOR (Concise + Binary Object Representation) serialization format. CBOR is a binary + serialization format which aims to be more compact than JSON itself, yet + more efficient to parse. + + The library uses the following mapping from JSON values types to + CBOR types according to the CBOR specification (RFC 7049): + + JSON value type | value/range | CBOR type | first byte + --------------- | ------------------------------------------ | ---------------------------------- | --------------- + null | `null` | Null | 0xf6 + boolean | `true` | True | 0xf5 + boolean | `false` | False | 0xf4 + number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3b + number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3a + number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 + number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 + number_integer | -24..-1 | Negative integer | 0x20..0x37 + number_integer | 0..23 | Integer | 0x00..0x17 + number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 + number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 + number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a + number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b + number_unsigned | 0..23 | Integer | 0x00..0x17 + number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 + number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 + number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a + number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b + number_float | *any value* | Double-Precision Float | 0xfb + string | *length*: 0..23 | UTF-8 string | 0x60..0x77 + string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 + string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 + string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7a + string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7b + array | *size*: 0..23 | array | 0x80..0x97 + array | *size*: 23..255 | array (1 byte follow) | 0x98 + array | *size*: 256..65535 | array (2 bytes follow) | 0x99 + array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9a + array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9b + object | *size*: 0..23 | map | 0xa0..0xb7 + object | *size*: 23..255 | map (1 byte follow) | 0xb8 + object | *size*: 256..65535 | map (2 bytes follow) | 0xb9 + object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xba + object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xbb + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a CBOR value. + + @note The following CBOR types are not used in the conversion: + - byte strings (0x40..0x5f) + - UTF-8 strings terminated by "break" (0x7f) + - arrays terminated by "break" (0x9f) + - maps terminated by "break" (0xbf) + - date/time (0xc0..0xc1) + - bignum (0xc2..0xc3) + - decimal fraction (0xc4) + - bigfloat (0xc5) + - tagged items (0xc6..0xd4, 0xd8..0xdb) + - expected conversions (0xd5..0xd7) + - simple values (0xe0..0xf3, 0xf8) + - undefined (0xf7) + - half and single-precision floats (0xf9-0xfa) + - break (0xff) + + @param[in,out] os output stream + @param[in] j JSON value to serialize + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in CBOR format.,to_cbor} + + @sa http://cbor.io + @sa @ref from_cbor(const std::vector&, const size_t) for the + analogous deserialization + @sa @ref to_msgpack(const json& for the related MessagePack format + + @since version 2.0.9 + */ + static void to_cbor(llvm::raw_ostream& os, const json& j); + static llvm::StringRef to_cbor(const json& j, llvm::SmallVectorImpl buf); + static std::string to_cbor(const json& j); + + /*! + @brief create a MessagePack serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the MessagePack + serialization format. MessagePack is a binary serialization format which + aims to be more compact than JSON itself, yet more efficient to parse. + + The library uses the following mapping from JSON values types to + MessagePack types according to the MessagePack specification: + + JSON value type | value/range | MessagePack type | first byte + --------------- | --------------------------------- | ---------------- | ---------- + null | `null` | nil | 0xc0 + boolean | `true` | true | 0xc3 + boolean | `false` | false | 0xc2 + number_integer | -9223372036854775808..-2147483649 | int64 | 0xd3 + number_integer | -2147483648..-32769 | int32 | 0xd2 + number_integer | -32768..-129 | int16 | 0xd1 + number_integer | -128..-33 | int8 | 0xd0 + number_integer | -32..-1 | negative fixint | 0xe0..0xff + number_integer | 0..127 | positive fixint | 0x00..0x7f + number_integer | 128..255 | uint 8 | 0xcc + number_integer | 256..65535 | uint 16 | 0xcd + number_integer | 65536..4294967295 | uint 32 | 0xce + number_integer | 4294967296..18446744073709551615 | uint 64 | 0xcf + number_unsigned | 0..127 | positive fixint | 0x00..0x7f + number_unsigned | 128..255 | uint 8 | 0xcc + number_unsigned | 256..65535 | uint 16 | 0xcd + number_unsigned | 65536..4294967295 | uint 32 | 0xce + number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xcf + number_float | *any value* | float 64 | 0xcb + string | *length*: 0..31 | fixstr | 0xa0..0xbf + string | *length*: 32..255 | str 8 | 0xd9 + string | *length*: 256..65535 | str 16 | 0xda + string | *length*: 65536..4294967295 | str 32 | 0xdb + array | *size*: 0..15 | fixarray | 0x90..0x9f + array | *size*: 16..65535 | array 16 | 0xdc + array | *size*: 65536..4294967295 | array 32 | 0xdd + object | *size*: 0..15 | fix map | 0x80..0x8f + object | *size*: 16..65535 | map 16 | 0xde + object | *size*: 65536..4294967295 | map 32 | 0xdf + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a MessagePack value. + + @note The following values can **not** be converted to a MessagePack value: + - strings with more than 4294967295 bytes + - arrays with more than 4294967295 elements + - objects with more than 4294967295 elements + + @note The following MessagePack types are not used in the conversion: + - bin 8 - bin 32 (0xc4..0xc6) + - ext 8 - ext 32 (0xc7..0xc9) + - float 32 (0xca) + - fixext 1 - fixext 16 (0xd4..0xd8) + + @note Any MessagePack output created @ref to_msgpack can be successfully + parsed by @ref from_msgpack. + + @param[in,out] os output stream + @param[in] j JSON value to serialize + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in MessagePack format.,to_msgpack} + + @sa http://msgpack.org + @sa @ref from_msgpack(const std::vector&, const size_t) for the + analogous deserialization + @sa @ref to_cbor(const json& for the related CBOR format + + @since version 2.0.9 + */ + static void to_msgpack(llvm::raw_ostream& os, const json& j); + static llvm::StringRef to_msgpack(const json& j, llvm::SmallVectorImpl buf); + static std::string to_msgpack(const json& j); + + /*! + @brief create a JSON value from a byte vector in CBOR format + + Deserializes a given byte vector @a v to a JSON value using the CBOR + (Concise Binary Object Representation) serialization format. + + The library maps CBOR types to JSON value types as follows: + + CBOR type | JSON value type | first byte + ---------------------- | --------------- | ---------- + Integer | number_unsigned | 0x00..0x17 + Unsigned integer | number_unsigned | 0x18 + Unsigned integer | number_unsigned | 0x19 + Unsigned integer | number_unsigned | 0x1a + Unsigned integer | number_unsigned | 0x1b + Negative integer | number_integer | 0x20..0x37 + Negative integer | number_integer | 0x38 + Negative integer | number_integer | 0x39 + Negative integer | number_integer | 0x3a + Negative integer | number_integer | 0x3b + Negative integer | number_integer | 0x40..0x57 + UTF-8 string | string | 0x60..0x77 + UTF-8 string | string | 0x78 + UTF-8 string | string | 0x79 + UTF-8 string | string | 0x7a + UTF-8 string | string | 0x7b + UTF-8 string | string | 0x7f + array | array | 0x80..0x97 + array | array | 0x98 + array | array | 0x99 + array | array | 0x9a + array | array | 0x9b + array | array | 0x9f + map | object | 0xa0..0xb7 + map | object | 0xb8 + map | object | 0xb9 + map | object | 0xba + map | object | 0xbb + map | object | 0xbf + False | `false` | 0xf4 + True | `true` | 0xf5 + Nill | `null` | 0xf6 + Half-Precision Float | number_float | 0xf9 + Single-Precision Float | number_float | 0xfa + Double-Precision Float | number_float | 0xfb + + @warning The mapping is **incomplete** in the sense that not all CBOR + types can be converted to a JSON value. The following CBOR types + are not supported and will yield parse errors (parse_error.112): + - byte strings (0x40..0x5f) + - date/time (0xc0..0xc1) + - bignum (0xc2..0xc3) + - decimal fraction (0xc4) + - bigfloat (0xc5) + - tagged items (0xc6..0xd4, 0xd8..0xdb) + - expected conversions (0xd5..0xd7) + - simple values (0xe0..0xf3, 0xf8) + - undefined (0xf7) + + @warning CBOR allows map keys of any type, whereas JSON only allows + strings as keys in object values. Therefore, CBOR maps with keys + other than UTF-8 strings are rejected (parse_error.113). + + @note Any CBOR output created @ref to_cbor can be successfully parsed by + @ref from_cbor. + + @param[in] is an input stream in CBOR format + @return deserialized JSON value + + @throw parse_error.110 if the given vector ends prematurely + @throw parse_error.112 if unsupported features from CBOR were + used in the given vector @a v or if the input is not valid CBOR + @throw parse_error.113 if a string was expected as map key, but not found + + @complexity Linear in the size of the byte vector @a v. + + @liveexample{The example shows the deserialization of a byte vector in CBOR + format to a JSON value.,from_cbor} + + @sa http://cbor.io + @sa @ref to_cbor(const json&) for the analogous serialization + @sa @ref from_msgpack(const std::vector&, const size_t) for the + related MessagePack format + + @since version 2.0.9, parameter @a start_index since 2.1.1 + */ + static json from_cbor(wpi::raw_istream& is); + static json from_cbor(llvm::StringRef s); + + /*! + @brief create a JSON value from a byte vector in MessagePack format + + Deserializes a given byte vector @a v to a JSON value using the MessagePack + serialization format. + + The library maps MessagePack types to JSON value types as follows: + + MessagePack type | JSON value type | first byte + ---------------- | --------------- | ---------- + positive fixint | number_unsigned | 0x00..0x7f + fixmap | object | 0x80..0x8f + fixarray | array | 0x90..0x9f + fixstr | string | 0xa0..0xbf + nil | `null` | 0xc0 + false | `false` | 0xc2 + true | `true` | 0xc3 + float 32 | number_float | 0xca + float 64 | number_float | 0xcb + uint 8 | number_unsigned | 0xcc + uint 16 | number_unsigned | 0xcd + uint 32 | number_unsigned | 0xce + uint 64 | number_unsigned | 0xcf + int 8 | number_integer | 0xd0 + int 16 | number_integer | 0xd1 + int 32 | number_integer | 0xd2 + int 64 | number_integer | 0xd3 + str 8 | string | 0xd9 + str 16 | string | 0xda + str 32 | string | 0xdb + array 16 | array | 0xdc + array 32 | array | 0xdd + map 16 | object | 0xde + map 32 | object | 0xdf + negative fixint | number_integer | 0xe0-0xff + + @warning The mapping is **incomplete** in the sense that not all + MessagePack types can be converted to a JSON value. The following + MessagePack types are not supported and will yield parse errors: + - bin 8 - bin 32 (0xc4..0xc6) + - ext 8 - ext 32 (0xc7..0xc9) + - fixext 1 - fixext 16 (0xd4..0xd8) + + @note Any MessagePack output created @ref to_msgpack can be successfully + parsed by @ref from_msgpack. + + @param[in] is an input stream in MessagePack format + @return deserialized JSON value + + @throw parse_error.110 if the given vector ends prematurely + @throw parse_error.112 if unsupported features from MessagePack were + used in the given vector @a v or if the input is not valid MessagePack + @throw parse_error.113 if a string was expected as map key, but not found + + @complexity Linear in the size of the byte vector @a v. + + @liveexample{The example shows the deserialization of a byte vector in + MessagePack format to a JSON value.,from_msgpack} + + @sa http://msgpack.org + @sa @ref to_msgpack(const json&) for the analogous serialization + @sa @ref from_cbor(const std::vector&, const size_t) for the + related CBOR format + + @since version 2.0.9, parameter @a start_index since 2.1.1 + */ + static json from_msgpack(wpi::raw_istream& is); + static json from_msgpack(llvm::StringRef s); + + /// @} + + public: + /*! + @brief JSON Pointer + + A JSON pointer defines a string syntax for identifying a specific value + within a JSON document. It can be used with functions `at` and + `operator[]`. Furthermore, JSON pointers are the base for JSON patches. + + @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) + + @since version 2.0.0 + */ + class json_pointer + { + /// allow json to access private members + friend class json; + friend class JsonTest; + + public: + /*! + @brief create JSON pointer + + Create a JSON pointer according to the syntax described in + [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). + + @param[in] s string representing the JSON pointer; if omitted, the + empty string is assumed which references the whole JSON + value + + @throw parse_error.107 if the given JSON pointer @a s is nonempty and + does not begin with a slash (`/`); see example below + + @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s + is not followed by `0` (representing `~`) or `1` (representing `/`); + see example below + + @liveexample{The example shows the construction several valid JSON + pointers as well as the exceptional behavior.,json_pointer} + + @since version 2.0.0 + */ + explicit json_pointer(const std::string& s = "") + : reference_tokens(split(s)) + {} + + /*! + @brief return a string representation of the JSON pointer + + @invariant For each JSON pointer `ptr`, it holds: + @code {.cpp} + ptr == json_pointer(ptr.to_string()); + @endcode + + @return a string representation of the JSON pointer + + @liveexample{The example shows the result of `to_string`., + json_pointer__to_string} + + @since version 2.0.0 + */ + std::string to_string() const noexcept; + + /// @copydoc to_string() + operator std::string() const + { + return to_string(); + } + + private: + /*! + @brief remove and return last reference pointer + @throw out_of_range.405 if JSON pointer has no parent + */ + std::string pop_back() + { + if (is_root()) + { + JSON_THROW(out_of_range::create(405, "JSON pointer has no parent")); + } + + auto last = reference_tokens.back(); + reference_tokens.pop_back(); + return last; + } + + /// return whether pointer points to the root document + bool is_root() const + { + return reference_tokens.empty(); + } + + json_pointer top() const + { + if (is_root()) + { + JSON_THROW(out_of_range::create(405, "JSON pointer has no parent")); + } + + json_pointer result = *this; + result.reference_tokens = {reference_tokens[0]}; + return result; + } + + /*! + @brief create and return a reference to the pointed to value + + @complexity Linear in the number of reference tokens. + + @throw parse_error.109 if array index is not a number + @throw type_error.313 if value cannot be unflattened + */ + reference get_and_create(reference j) const; + + /*! + @brief return a reference to the pointed to value + + @note This version does not throw if a value is not present, but tries + to create nested values instead. For instance, calling this function + with pointer `"/this/that"` on a null value is equivalent to calling + `operator[]("this").operator[]("that")` on that value, effectively + changing the null value to an object. + + @param[in] ptr a JSON value + + @return reference to the JSON value pointed to by the JSON pointer + + @complexity Linear in the length of the JSON pointer. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + reference get_unchecked(pointer ptr) const; + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + reference get_checked(pointer ptr) const; + + /*! + @brief return a const reference to the pointed to value + + @param[in] ptr a JSON value + + @return const reference to the JSON value pointed to by the JSON + pointer + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const_reference get_unchecked(const_pointer ptr) const; + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const_reference get_checked(const_pointer ptr) const; + + /*! + @brief split the string input to reference tokens + + @note This function is only called by the json_pointer constructor. + All exceptions below are documented there. + + @throw parse_error.107 if the pointer is not empty or begins with '/' + @throw parse_error.108 if character '~' is not followed by '0' or '1' + */ + static std::vector split(const std::string& reference_string); + + /*! + @brief replace all occurrences of a substring by another string + + @param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t + @param[in] f the substring to replace with @a t + @param[in] t the string to replace @a f + + @pre The search string @a f must not be empty. **This precondition is + enforced with an assertion.** + + @since version 2.0.0 + */ + static void replace_substring(std::string& s, + const std::string& f, + const std::string& t); + + /// escape tilde and slash + static std::string escape(std::string s); + + /// unescape tilde and slash + static void unescape(std::string& s); + + /*! + @param[in] reference_string the reference string to the current value + @param[in] value the value to consider + @param[in,out] result the result object to insert values to + + @note Empty objects or arrays are flattened to `null`. + */ + static void flatten(const std::string& reference_string, + const json& value, + json& result); + + /*! + @param[in] value flattened JSON + + @return unflattened JSON + + @throw parse_error.109 if array index is not a number + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + @throw type_error.313 if value cannot be unflattened + */ + static json unflatten(const json& value); + + friend bool operator==(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return lhs.reference_tokens == rhs.reference_tokens; + } + + friend bool operator!=(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return !(lhs == rhs); + } + + /// the reference tokens + std::vector reference_tokens {}; + }; + + ////////////////////////// + // JSON Pointer support // + ////////////////////////// + + /// @name JSON Pointer functions + /// @{ + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. Similar to @ref operator[]( + llvm::StringRef), `null` values are created in arrays and objects if + necessary. + + In particular: + - If the JSON pointer points to an object key that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. + - If the JSON pointer points to an array index that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. All indices between the current maximum and the given + index are also filled with `null`. + - The special value `-` is treated as a synonym for the index past the + end. + + @param[in] ptr a JSON pointer + + @return reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + + @liveexample{The behavior is shown in the example.,operatorjson_pointer} + + @since version 2.0.0 + */ + reference operator[](const json_pointer& ptr) + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. The function does not change the JSON + value; no `null` values are created. In particular, the the special value + `-` yields an exception. + + @param[in] ptr JSON pointer to the desired element + + @return const reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + + @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} + + @since version 2.0.0 + */ + const_reference operator[](const json_pointer& ptr) const + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a reference to the element at with specified JSON pointer @a ptr, + with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @throw parse_error.106 if an array index in the passed JSON pointer @a ptr + begins with '0'. See example below. + + @throw parse_error.109 if an array index in the passed JSON pointer @a ptr + is not a number. See example below. + + @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr + is out of range. See example below. + + @throw out_of_range.402 if the array index '-' is used in the passed JSON + pointer @a ptr. As `at` provides checked access (and no elements are + implicitly inserted), the index '-' is always invalid. See example below. + + @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. + See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 2.0.0 + + @liveexample{The behavior is shown in the example.,at_json_pointer} + */ + reference at(const json_pointer& ptr) + { + return ptr.get_checked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a const reference to the element at with specified JSON pointer @a + ptr, with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @throw parse_error.106 if an array index in the passed JSON pointer @a ptr + begins with '0'. See example below. + + @throw parse_error.109 if an array index in the passed JSON pointer @a ptr + is not a number. See example below. + + @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr + is out of range. See example below. + + @throw out_of_range.402 if the array index '-' is used in the passed JSON + pointer @a ptr. As `at` provides checked access (and no elements are + implicitly inserted), the index '-' is always invalid. See example below. + + @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. + See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 2.0.0 + + @liveexample{The behavior is shown in the example.,at_json_pointer_const} + */ + const_reference at(const json_pointer& ptr) const + { + return ptr.get_checked(this); + } + + /*! + @brief return flattened JSON value + + The function creates a JSON object whose keys are JSON pointers (see [RFC + 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all + primitive. The original JSON value can be restored using the @ref + unflatten() function. + + @return an object that maps JSON pointers to primitive values + + @note Empty objects and arrays are flattened to `null` and will not be + reconstructed correctly by the @ref unflatten() function. + + @complexity Linear in the size the JSON value. + + @liveexample{The following code shows how a JSON object is flattened to an + object whose keys consist of JSON pointers.,flatten} + + @sa @ref unflatten() for the reverse function + + @since version 2.0.0 + */ + json flatten() const + { + json result(value_t::object); + json_pointer::flatten("", *this, result); + return result; + } + + /*! + @brief unflatten a previously flattened JSON value + + The function restores the arbitrary nesting of a JSON value that has been + flattened before using the @ref flatten() function. The JSON value must + meet certain constraints: + 1. The value must be an object. + 2. The keys must be JSON pointers (see + [RFC 6901](https://tools.ietf.org/html/rfc6901)) + 3. The mapped values must be primitive JSON types. + + @return the original JSON from a flattened version + + @note Empty objects and arrays are flattened by @ref flatten() to `null` + values and can not unflattened to their original type. Apart from + this example, for a JSON value `j`, the following is always true: + `j == j.flatten().unflatten()`. + + @complexity Linear in the size the JSON value. + + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitve + + @liveexample{The following code shows how a flattened JSON object is + unflattened into the original nested JSON object.,unflatten} + + @sa @ref flatten() for the reverse function + + @since version 2.0.0 + */ + json unflatten() const + { + return json_pointer::unflatten(*this); + } + + /// @} +}; + +} // namespace wpi + + +/////////////////////// +// nonmember support // +/////////////////////// + +// specialization of std::swap, and std::hash +namespace std +{ +/*! +@brief exchanges the values of two JSON objects + +@since version 1.0.0 +*/ +template<> +inline void swap(wpi::json& j1, + wpi::json& j2) noexcept( + is_nothrow_move_constructible::value && + is_nothrow_move_assignable::value + ) +{ + j1.swap(j2); +} + +/// hash value for JSON objects +template<> +struct hash +{ + /*! + @brief return a hash value for a JSON object + + @since version 1.0.0 + */ + std::size_t operator()(const wpi::json& j) const; +}; + +/// specialization for std::less +template <> +struct less<::wpi::detail::value_t> +{ + /*! + @brief compare two value_t enum values + @since version 3.0.0 + */ + bool operator()(wpi::detail::value_t lhs, + wpi::detail::value_t rhs) const noexcept + { + return wpi::detail::operator<(lhs, rhs); + } +}; + +} // namespace std + +/*! +@brief user-defined string literal for JSON values + +This operator implements a user-defined string literal for JSON objects. It +can be used by adding `"_json"` to a string literal and returns a JSON object +if no parse error occurred. + +@param[in] s a string representation of a JSON object +@param[in] n the length of string @a s +@return a JSON object + +@since version 1.0.0 +*/ +inline wpi::json operator "" _json(const char* s, std::size_t n) +{ + return wpi::json::parse(llvm::StringRef(s, n)); +} + +/*! +@brief user-defined string literal for JSON pointer + +This operator implements a user-defined string literal for JSON Pointers. It +can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer +object if no parse error occurred. + +@param[in] s a string representation of a JSON Pointer +@param[in] n the length of string @a s +@return a JSON pointer object + +@since version 2.0.0 +*/ +inline wpi::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) +{ + return wpi::json::json_pointer(std::string(s, n)); +} + +#ifndef WPI_JSON_IMPLEMENTATION + +// restore GCC/clang diagnostic settings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic pop +#endif +#if defined(__clang__) + #pragma GCC diagnostic pop +#endif + +// clean up +#undef JSON_CATCH +#undef JSON_THROW +#undef JSON_TRY +#undef JSON_LIKELY +#undef JSON_UNLIKELY + +#endif // WPI_JSON_IMPLEMENTATION + +#endif diff --git a/src/test/native/cpp/json/unit-algorithms.cpp b/src/test/native/cpp/json/unit-algorithms.cpp new file mode 100644 index 0000000000..f1a87453a9 --- /dev/null +++ b/src/test/native/cpp/json/unit-algorithms.cpp @@ -0,0 +1,310 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +#include + +class JsonAlgorithmsTest : public ::testing::Test { + protected: + json j_array = {13, 29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz"}; + json j_object = {{"one", 1}, {"two", 2}}; +}; + +// non-modifying sequence operations +TEST_F(JsonAlgorithmsTest, AllOf) +{ + EXPECT_TRUE(std::all_of(j_array.begin(), j_array.end(), [](const json & value) + { + return value.size() > 0; + })); + EXPECT_TRUE(std::all_of(j_object.begin(), j_object.end(), [](const json & value) + { + return value.type() == json::value_t::number_integer; + })); +} + +TEST_F(JsonAlgorithmsTest, AnyOf) +{ + EXPECT_TRUE(std::any_of(j_array.begin(), j_array.end(), [](const json & value) + { + return value.is_string() && value.get() == "foo"; + })); + EXPECT_TRUE(std::any_of(j_object.begin(), j_object.end(), [](const json & value) + { + return value.get() > 1; + })); +} + +TEST_F(JsonAlgorithmsTest, NoneOf) +{ + EXPECT_TRUE(std::none_of(j_array.begin(), j_array.end(), [](const json & value) + { + return value.size() == 0; + })); + EXPECT_TRUE(std::none_of(j_object.begin(), j_object.end(), [](const json & value) + { + return value.get() <= 0; + })); +} + +TEST_F(JsonAlgorithmsTest, ForEachReading) +{ + int sum = 0; + + std::for_each(j_array.cbegin(), j_array.cend(), [&sum](const json & value) + { + if (value.is_number()) + { + sum += static_cast(value); + } + }); + + EXPECT_EQ(sum, 45); +} + +TEST_F(JsonAlgorithmsTest, ForEachWriting) +{ + auto add17 = [](json & value) + { + if (value.is_array()) + { + value.push_back(17); + } + }; + + std::for_each(j_array.begin(), j_array.end(), add17); + + EXPECT_EQ(j_array[6], json({1, 2, 3, 17})); +} + +TEST_F(JsonAlgorithmsTest, Count) +{ + EXPECT_EQ(std::count(j_array.begin(), j_array.end(), json(true)), 1); +} + +TEST_F(JsonAlgorithmsTest, CountIf) +{ + auto count1 = std::count_if(j_array.begin(), j_array.end(), [](const json & value) + { + return (value.is_number()); + }); + EXPECT_EQ(count1, 3); + auto count2 = std::count_if(j_array.begin(), j_array.end(), [](const json&) + { + return true; + }); + EXPECT_EQ(count2, 9); +} + +TEST_F(JsonAlgorithmsTest, Mismatch) +{ + json j_array2 = {13, 29, 3, {{"one", 1}, {"two", 2}, {"three", 3}}, true, false, {1, 2, 3}, "foo", "baz"}; + auto res = std::mismatch(j_array.begin(), j_array.end(), j_array2.begin()); + EXPECT_EQ(*res.first, json({{"one", 1}, {"two", 2}})); + EXPECT_EQ(*res.second, json({{"one", 1}, {"two", 2}, {"three", 3}})); +} + +TEST_F(JsonAlgorithmsTest, EqualOperatorEquals) +{ + EXPECT_TRUE(std::equal(j_array.begin(), j_array.end(), j_array.begin())); + EXPECT_TRUE(std::equal(j_object.begin(), j_object.end(), j_object.begin())); + EXPECT_FALSE(std::equal(j_array.begin(), j_array.end(), j_object.begin())); +} + +TEST_F(JsonAlgorithmsTest, EqualUserComparison) +{ + // compare objects only by size of its elements + json j_array2 = {13, 29, 3, {"Hello", "World"}, true, false, {{"one", 1}, {"two", 2}, {"three", 3}}, "foo", "baz"}; + EXPECT_FALSE(std::equal(j_array.begin(), j_array.end(), j_array2.begin())); + EXPECT_TRUE(std::equal(j_array.begin(), j_array.end(), j_array2.begin(), + [](const json & a, const json & b) + { + return (a.size() == b.size()); + })); +} + +TEST_F(JsonAlgorithmsTest, Find) +{ + auto it = std::find(j_array.begin(), j_array.end(), json(false)); + EXPECT_EQ(std::distance(j_array.begin(), it), 5); +} + +TEST_F(JsonAlgorithmsTest, FindIf) +{ + auto it = std::find_if(j_array.begin(), j_array.end(), + [](const json & value) + { + return value.is_boolean(); + }); + EXPECT_EQ(std::distance(j_array.begin(), it), 4); +} + +TEST_F(JsonAlgorithmsTest, FindIfNot) +{ + auto it = std::find_if_not(j_array.begin(), j_array.end(), + [](const json & value) + { + return value.is_number(); + }); + EXPECT_EQ(std::distance(j_array.begin(), it), 3); +} + +TEST_F(JsonAlgorithmsTest, AdjacentFind) +{ + EXPECT_EQ(std::adjacent_find(j_array.begin(), j_array.end()), j_array.end()); + auto it = std::adjacent_find(j_array.begin(), j_array.end(), + [](const json & v1, const json & v2) + { + return v1.type() == v2.type(); + }); + EXPECT_EQ(it, j_array.begin()); +} + +// modifying sequence operations +TEST_F(JsonAlgorithmsTest, Reverse) +{ + std::reverse(j_array.begin(), j_array.end()); + EXPECT_EQ(j_array, json({"baz", "foo", {1, 2, 3}, false, true, {{"one", 1}, {"two", 2}}, 3, 29, 13})); +} + +TEST_F(JsonAlgorithmsTest, Rotate) +{ + std::rotate(j_array.begin(), j_array.begin() + 1, j_array.end()); + EXPECT_EQ(j_array, json({29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz", 13})); +} + +TEST_F(JsonAlgorithmsTest, Partition) +{ + auto it = std::partition(j_array.begin(), j_array.end(), [](const json & v) + { + return v.is_string(); + }); + EXPECT_EQ(std::distance(j_array.begin(), it), 2); + EXPECT_FALSE(it[2].is_string()); +} + +// sorting operations +TEST_F(JsonAlgorithmsTest, SortOperatorEquals) +{ + json j = {13, 29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz", nullptr}; + std::sort(j.begin(), j.end()); + EXPECT_EQ(j, json({nullptr, false, true, 3, 13, 29, {{"one", 1}, {"two", 2}}, {1, 2, 3}, "baz", "foo"})); +} + +TEST_F(JsonAlgorithmsTest, SortUserComparison) +{ + json j = {3, {{"one", 1}, {"two", 2}}, {1, 2, 3}, nullptr}; + std::sort(j.begin(), j.end(), [](const json & a, const json & b) + { + return a.size() < b.size(); + }); + EXPECT_EQ(j, json({nullptr, 3, {{"one", 1}, {"two", 2}}, {1, 2, 3}})); +} + +TEST_F(JsonAlgorithmsTest, SortObject) +{ + json j({{"one", 1}, {"two", 2}}); + EXPECT_THROW_MSG(std::sort(j.begin(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); +} + +TEST_F(JsonAlgorithmsTest, PartialSort) +{ + json j = {13, 29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz", nullptr}; + std::partial_sort(j.begin(), j.begin() + 4, j.end()); + EXPECT_EQ(j, json({nullptr, false, true, 3, {{"one", 1}, {"two", 2}}, 29, {1, 2, 3}, "foo", "baz", 13})); +} + +// set operations +TEST_F(JsonAlgorithmsTest, Merge) +{ + json j1 = {2, 4, 6, 8}; + json j2 = {1, 2, 3, 5, 7}; + json j3; + + std::merge(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3)); + EXPECT_EQ(j3, json({1, 2, 2, 3, 4, 5, 6, 7, 8})); +} + +TEST_F(JsonAlgorithmsTest, SetDifference) +{ + json j1 = {1, 2, 3, 4, 5, 6, 7, 8}; + json j2 = {1, 2, 3, 5, 7}; + json j3; + + std::set_difference(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3)); + EXPECT_EQ(j3, json({4, 6, 8})); +} + +TEST_F(JsonAlgorithmsTest, SetIntersection) +{ + json j1 = {1, 2, 3, 4, 5, 6, 7, 8}; + json j2 = {1, 2, 3, 5, 7}; + json j3; + + std::set_intersection(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3)); + EXPECT_EQ(j3, json({1, 2, 3, 5, 7})); +} + +TEST_F(JsonAlgorithmsTest, SetUnion) +{ + json j1 = {2, 4, 6, 8}; + json j2 = {1, 2, 3, 5, 7}; + json j3; + + std::set_union(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3)); + EXPECT_EQ(j3, json({1, 2, 3, 4, 5, 6, 7, 8})); +} + +TEST_F(JsonAlgorithmsTest, SetSymmetricDifference) +{ + json j1 = {2, 4, 6, 8}; + json j2 = {1, 2, 3, 5, 7}; + json j3; + + std::set_symmetric_difference(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3)); + EXPECT_EQ(j3, json({1, 3, 4, 5, 6, 7, 8})); +} + +TEST_F(JsonAlgorithmsTest, HeapOperations) +{ + std::make_heap(j_array.begin(), j_array.end()); + EXPECT_TRUE(std::is_heap(j_array.begin(), j_array.end())); + std::sort_heap(j_array.begin(), j_array.end()); + EXPECT_EQ(j_array, json({false, true, 3, 13, 29, {{"one", 1}, {"two", 2}}, {1, 2, 3}, "baz", "foo"})); +} diff --git a/src/test/native/cpp/json/unit-capacity.cpp b/src/test/native/cpp/json/unit-capacity.cpp new file mode 100644 index 0000000000..8f5433ec42 --- /dev/null +++ b/src/test/native/cpp/json/unit-capacity.cpp @@ -0,0 +1,528 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonEmptyTest, Boolean) +{ + json j = true; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, String) +{ + json j = "hello world"; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, ArrayEmpty) +{ + json j = json::array(); + json j_const(j); + + // result of empty + { + EXPECT_TRUE(j.empty()); + EXPECT_TRUE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, ArrayFilled) +{ + json j = {1, 2, 3}; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, ObjectEmpty) +{ + json j = json::object(); + json j_const(j); + + // result of empty + { + EXPECT_TRUE(j.empty()); + EXPECT_TRUE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, ObjectFilled) +{ + json j = {{"one", 1}, {"two", 2}, {"three", 3}}; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, NumberInteger) +{ + json j = 23; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, NumberUnsigned) +{ + json j = 23u; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, NumberFloat) +{ + json j = 23.42; + json j_const(j); + + // result of empty + { + EXPECT_FALSE(j.empty()); + EXPECT_FALSE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonEmptyTest, Null) +{ + json j = nullptr; + json j_const(j); + + // result of empty + { + EXPECT_TRUE(j.empty()); + EXPECT_TRUE(j_const.empty()); + } + + // definition of empty + { + EXPECT_EQ(j.empty(), (j.begin() == j.end())); + EXPECT_EQ(j_const.empty(), (j_const.begin() == j_const.end())); + } +} + +TEST(JsonSizeTest, Boolean) +{ + json j = true; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 1u); + EXPECT_EQ(j_const.size(), 1u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, String) +{ + json j = "hello world"; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 1u); + EXPECT_EQ(j_const.size(), 1u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, ArrayEmpty) +{ + json j = json::array(); + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 0u); + EXPECT_EQ(j_const.size(), 0u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, ArrayFilled) +{ + json j = {1, 2, 3}; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 3u); + EXPECT_EQ(j_const.size(), 3u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, ObjectEmpty) +{ + json j = json::object(); + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 0u); + EXPECT_EQ(j_const.size(), 0u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, ObjectFilled) +{ + json j = {{"one", 1}, {"two", 2}, {"three", 3}}; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 3u); + EXPECT_EQ(j_const.size(), 3u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, NumberInteger) +{ + json j = 23; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 1u); + EXPECT_EQ(j_const.size(), 1u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, NumberUnsigned) +{ + json j = 23u; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 1u); + EXPECT_EQ(j_const.size(), 1u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, NumberFloat) +{ + json j = 23.42; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 1u); + EXPECT_EQ(j_const.size(), 1u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonSizeTest, Null) +{ + json j = nullptr; + json j_const(j); + + // result of size + { + EXPECT_EQ(j.size(), 0u); + EXPECT_EQ(j_const.size(), 0u); + } + + // definition of size + { + EXPECT_EQ(std::distance(j.begin(), j.end()), static_cast(j.size())); + EXPECT_EQ(std::distance(j_const.begin(), j_const.end()), + static_cast(j_const.size())); + } +} + +TEST(JsonMaxSizeTest, Boolean) +{ + json j = true; + json j_const(j); + + // result of max_size + { + EXPECT_EQ(j.max_size(), 1u); + EXPECT_EQ(j_const.max_size(), 1u); + } +} + +TEST(JsonMaxSizeTest, String) +{ + json j = "hello world"; + json j_const(j); + + // result of max_size + { + EXPECT_EQ(j.max_size(), 1u); + EXPECT_EQ(j_const.max_size(), 1u); + } +} + +TEST(JsonMaxSizeTest, ArrayEmpty) +{ + json j = json::array(); + json j_const(j); + + // result of max_size + { + EXPECT_GE(j.max_size(), j.size()); + EXPECT_GE(j_const.max_size(), j_const.size()); + } +} + +TEST(JsonMaxSizeTest, ArrayFilled) +{ + json j = {1, 2, 3}; + json j_const(j); + + // result of max_size + { + EXPECT_GE(j.max_size(), j.size()); + EXPECT_GE(j_const.max_size(), j_const.size()); + } +} + +TEST(JsonMaxSizeTest, ObjectEmpty) +{ + json j = json::object(); + json j_const(j); + + // result of max_size + { + EXPECT_GE(j.max_size(), j.size()); + EXPECT_GE(j_const.max_size(), j_const.size()); + } +} + +TEST(JsonMaxSizeTest, ObjectFilled) +{ + json j = {{"one", 1}, {"two", 2}, {"three", 3}}; + json j_const(j); + + // result of max_size + { + EXPECT_GE(j.max_size(), j.size()); + EXPECT_GE(j_const.max_size(), j_const.size()); + } +} + +TEST(JsonMaxSizeTest, NumberInteger) +{ + json j = 23; + json j_const(j); + + // result of max_size + { + EXPECT_EQ(j.max_size(), 1u); + EXPECT_EQ(j_const.max_size(), 1u); + } +} + +TEST(JsonMaxSizeTest, NumberUnsigned) +{ + json j = 23u; + json j_const(j); + + // result of max_size + { + EXPECT_EQ(j.max_size(), 1u); + EXPECT_EQ(j_const.max_size(), 1u); + } +} + +TEST(JsonMaxSizeTest, NumberFloat) +{ + json j = 23.42; + json j_const(j); + + // result of max_size + { + EXPECT_EQ(j.max_size(), 1u); + EXPECT_EQ(j_const.max_size(), 1u); + } +} + +TEST(JsonMaxSizeTest, Null) +{ + json j = nullptr; + json j_const(j); + + // result of max_size + { + EXPECT_EQ(j.max_size(), 0u); + EXPECT_EQ(j_const.max_size(), 0u); + } +} diff --git a/src/test/native/cpp/json/unit-cbor.cpp b/src/test/native/cpp/json/unit-cbor.cpp new file mode 100644 index 0000000000..67b61df2be --- /dev/null +++ b/src/test/native/cpp/json/unit-cbor.cpp @@ -0,0 +1,1689 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +#include + +TEST(CborDiscardedTest, Case) +{ + // discarded values are not serialized + json j = json::value_t::discarded; + const auto result = json::to_cbor(j); + ASSERT_TRUE(result.empty()); +} + +TEST(CborNullTest, Case) +{ + json j = nullptr; + std::string expected = "\xf6"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +TEST(CborBooleanTest, True) +{ + json j = true; + std::string expected = "\xf5"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +TEST(CborBooleanTest, False) +{ + json j = false; + std::string expected = "\xf4"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// -9223372036854775808..-4294967297 +class CborSignedNeg8Test : public ::testing::TestWithParam {}; +TEST_P(CborSignedNeg8Test, Case) +{ + // create JSON value with integer number + json j = GetParam(); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x3b)); + uint64_t positive = static_cast(-1 - GetParam()); + expected.push_back(static_cast((positive >> 56) & 0xff)); + expected.push_back(static_cast((positive >> 48) & 0xff)); + expected.push_back(static_cast((positive >> 40) & 0xff)); + expected.push_back(static_cast((positive >> 32) & 0xff)); + expected.push_back(static_cast((positive >> 24) & 0xff)); + expected.push_back(static_cast((positive >> 16) & 0xff)); + expected.push_back(static_cast((positive >> 8) & 0xff)); + expected.push_back(static_cast(positive & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 9u); + + // check individual bytes + EXPECT_EQ(result[0], 0x3b); + uint64_t restored = (static_cast(static_cast(result[1])) << 070) + + (static_cast(static_cast(result[2])) << 060) + + (static_cast(static_cast(result[3])) << 050) + + (static_cast(static_cast(result[4])) << 040) + + (static_cast(static_cast(result[5])) << 030) + + (static_cast(static_cast(result[6])) << 020) + + (static_cast(static_cast(result[7])) << 010) + + static_cast(static_cast(result[8])); + EXPECT_EQ(restored, positive); + EXPECT_EQ(-1 - static_cast(restored), GetParam()); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +static const int64_t neg8_numbers[] = { + INT64_MIN, + -1000000000000000000, + -100000000000000000, + -10000000000000000, + -1000000000000000, + -100000000000000, + -10000000000000, + -1000000000000, + -100000000000, + -10000000000, + -4294967297, +}; + +INSTANTIATE_TEST_CASE_P(CborSignedNeg8Tests, CborSignedNeg8Test, + ::testing::ValuesIn(neg8_numbers)); + +// -4294967296..-65537 +class CborSignedNeg4Test : public ::testing::TestWithParam {}; +TEST_P(CborSignedNeg4Test, Case) +{ + // create JSON value with integer number + json j = GetParam(); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x3a)); + uint32_t positive = static_cast(static_cast(-1 - GetParam()) & 0x00000000ffffffff); + expected.push_back(static_cast((positive >> 24) & 0xff)); + expected.push_back(static_cast((positive >> 16) & 0xff)); + expected.push_back(static_cast((positive >> 8) & 0xff)); + expected.push_back(static_cast(positive & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 5u); + + // check individual bytes + EXPECT_EQ(result[0], 0x3a); + uint32_t restored = (static_cast(static_cast(result[1])) << 030) + + (static_cast(static_cast(result[2])) << 020) + + (static_cast(static_cast(result[3])) << 010) + + static_cast(static_cast(result[4])); + EXPECT_EQ(restored, positive); + EXPECT_EQ(-1ll - restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +static const int64_t neg4_numbers[] = { + -65537, + -100000, + -1000000, + -10000000, + -100000000, + -1000000000, + -4294967296, +}; + +INSTANTIATE_TEST_CASE_P(CborSignedNeg4Tests, CborSignedNeg4Test, + ::testing::ValuesIn(neg4_numbers)); + +// -65536..-257 +TEST(CborSignedTest, Neg2) +{ + for (int32_t i = -65536; i <= -257; ++i) { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x39)); + uint16_t positive = static_cast(-1 - i); + expected.push_back(static_cast((positive >> 8) & 0xff)); + expected.push_back(static_cast(positive & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], 0x39); + uint16_t restored = static_cast(static_cast(result[1]) * 256 + static_cast(result[2])); + EXPECT_EQ(restored, positive); + EXPECT_EQ(-1 - restored, i); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// -9263 (int 16) +TEST(CborSignedTest, NegInt16) +{ + json j = -9263; + std::string expected = "\x39\x24\x2e"; + + const auto result = json::to_cbor(j); + ASSERT_EQ(result, expected); + + int16_t restored = static_cast(-1 - ((result[1] << 8) + result[2])); + EXPECT_EQ(restored, -9263); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// -256..-24 +TEST(CborSignedTest, Neg1) +{ + for (auto i = -256; i < -24; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(0x38); + expected.push_back(static_cast(-1 - i)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 2u); + + // check individual bytes + EXPECT_EQ(result[0], 0x38); + EXPECT_EQ(static_cast(-1 - static_cast(result[1])), i); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// -24..-1 +TEST(CborSignedTest, Neg0) +{ + for (auto i = -24; i <= -1; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x20 - 1 - static_cast(i))); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 1u); + + // check individual bytes + EXPECT_EQ(static_cast(0x20 - 1 - result[0]), i); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 0..23 +TEST(CborSignedTest, Pos0) +{ + for (size_t i = 0; i <= 23; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(i); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 1u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(i)); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 24..255 +TEST(CborSignedTest, Pos1) +{ + for (size_t i = 24; i <= 255; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(i); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x18)); + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 2u); + + // check individual bytes + EXPECT_EQ(result[0], 0x18); + EXPECT_EQ(result[1], static_cast(i)); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 256..65535 +TEST(CborSignedTest, Pos2) +{ + for (size_t i = 256; i <= 65535; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(i); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x19)); + expected.push_back(static_cast((i >> 8) & 0xff)); + expected.push_back(static_cast(i & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], 0x19); + uint16_t restored = static_cast(static_cast(result[1]) * 256 + static_cast(result[2])); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 65536..4294967295 +class CborSignedPos4Test : public ::testing::TestWithParam {}; +TEST_P(CborSignedPos4Test, Case) +{ + // create JSON value with integer number + json j = -1; + j.get_ref() = + static_cast(GetParam()); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(0x1a); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 5u); + + // check individual bytes + EXPECT_EQ(result[0], 0x1a); + uint32_t restored = (static_cast(static_cast(result[1])) << 030) + + (static_cast(static_cast(result[2])) << 020) + + (static_cast(static_cast(result[3])) << 010) + + static_cast(static_cast(result[4])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +static const uint32_t pos4_numbers[] = { + 65536u, + 77777u, + 1048576u, +}; + +INSTANTIATE_TEST_CASE_P(CborSignedPos4Tests, CborSignedPos4Test, + ::testing::ValuesIn(pos4_numbers)); + +// 4294967296..4611686018427387903 +class CborSignedPos8Test : public ::testing::TestWithParam {}; +TEST_P(CborSignedPos8Test, Case) +{ + // create JSON value with integer number + json j = -1; + j.get_ref() = + static_cast(GetParam()); + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(0x1b); + expected.push_back(static_cast((GetParam() >> 070) & 0xff)); + expected.push_back(static_cast((GetParam() >> 060) & 0xff)); + expected.push_back(static_cast((GetParam() >> 050) & 0xff)); + expected.push_back(static_cast((GetParam() >> 040) & 0xff)); + expected.push_back(static_cast((GetParam() >> 030) & 0xff)); + expected.push_back(static_cast((GetParam() >> 020) & 0xff)); + expected.push_back(static_cast((GetParam() >> 010) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 9u); + + // check individual bytes + EXPECT_EQ(result[0], 0x1b); + uint64_t restored = (static_cast(static_cast(result[1])) << 070) + + (static_cast(static_cast(result[2])) << 060) + + (static_cast(static_cast(result[3])) << 050) + + (static_cast(static_cast(result[4])) << 040) + + (static_cast(static_cast(result[5])) << 030) + + (static_cast(static_cast(result[6])) << 020) + + (static_cast(static_cast(result[7])) << 010) + + static_cast(static_cast(result[8])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +static const uint64_t pos8_numbers[] = { + 4294967296ul, + 4611686018427387903ul +}; + +INSTANTIATE_TEST_CASE_P(CborSignedPos8Tests, CborSignedPos8Test, + ::testing::ValuesIn(pos8_numbers)); + +/* +// -32768..-129 (int 16) +{ + for (int16_t i = -32768; i <= -129; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(0xd1); + expected.push_back(static_cast((i >> 8) & 0xff)); + expected.push_back(static_cast(i & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result == expected); + ASSERT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], 0xd1); + int16_t restored = (result[1] << 8) + result[2]; + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} +*/ + +// 0..23 (Integer) +TEST(CborUnsignedTest, Pos0) +{ + for (size_t i = 0; i <= 23; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with unsigned integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 1u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(i)); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 24..255 (one-byte uint8_t) +TEST(CborUnsignedTest, Pos1) +{ + for (size_t i = 24; i <= 255; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with unsigned integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(0x18); + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 2u); + + // check individual bytes + EXPECT_EQ(result[0], 0x18); + uint8_t restored = static_cast(result[1]); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 256..65535 (two-byte uint16_t) +TEST(CborUnsignedTest, Pos2) +{ + for (size_t i = 256; i <= 65535; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with unsigned integer number + json j = i; + + // check type + ASSERT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(0x19); + expected.push_back(static_cast((i >> 8) & 0xff)); + expected.push_back(static_cast(i & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], 0x19); + uint16_t restored = static_cast(static_cast(result[1]) * 256 + static_cast(result[2])); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// 65536..4294967295 (four-byte uint32_t) +class CborUnsignedPos4Test : public ::testing::TestWithParam {}; +TEST_P(CborUnsignedPos4Test, Case) +{ + // create JSON value with unsigned integer number + json j = GetParam(); + + // check type + ASSERT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(0x1a); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 5u); + + // check individual bytes + EXPECT_EQ(result[0], 0x1a); + uint32_t restored = (static_cast(static_cast(result[1])) << 030) + + (static_cast(static_cast(result[2])) << 020) + + (static_cast(static_cast(result[3])) << 010) + + static_cast(static_cast(result[4])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +INSTANTIATE_TEST_CASE_P(CborUnsignedPos4Tests, CborUnsignedPos4Test, + ::testing::ValuesIn(pos4_numbers)); + +// 4294967296..4611686018427387903 (eight-byte uint64_t) +class CborUnsignedPos8Test : public ::testing::TestWithParam {}; +TEST_P(CborUnsignedPos8Test, Case) +{ + // create JSON value with integer number + json j = GetParam(); + + // check type + ASSERT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(0x1b); + expected.push_back(static_cast((GetParam() >> 070) & 0xff)); + expected.push_back(static_cast((GetParam() >> 060) & 0xff)); + expected.push_back(static_cast((GetParam() >> 050) & 0xff)); + expected.push_back(static_cast((GetParam() >> 040) & 0xff)); + expected.push_back(static_cast((GetParam() >> 030) & 0xff)); + expected.push_back(static_cast((GetParam() >> 020) & 0xff)); + expected.push_back(static_cast((GetParam() >> 010) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), 9u); + + // check individual bytes + EXPECT_EQ(result[0], 0x1b); + uint64_t restored = (static_cast(static_cast(result[1])) << 070) + + (static_cast(static_cast(result[2])) << 060) + + (static_cast(static_cast(result[3])) << 050) + + (static_cast(static_cast(result[4])) << 040) + + (static_cast(static_cast(result[5])) << 030) + + (static_cast(static_cast(result[6])) << 020) + + (static_cast(static_cast(result[7])) << 010) + + static_cast(static_cast(result[8])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +INSTANTIATE_TEST_CASE_P(CborUnsignedPos8Tests, CborUnsignedPos8Test, + ::testing::ValuesIn(pos8_numbers)); + +// 3.1415925 +TEST(CborFloatTest, Number) +{ + double v = 3.1415925; + json j = v; + std::string expected = "\xfb\x40\x09\x21\xfb\x3f\xa6\xde\xfc"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + EXPECT_EQ(json::from_cbor(result), v); +} + +TEST(CborFloatTest, HalfInfinity) +{ + json j = json::from_cbor(llvm::StringRef("\xf9\x7c\x00", 3)); + json::number_float_t d = j; + EXPECT_FALSE(std::isfinite(d)); + EXPECT_EQ(j.dump(), "null"); +} + +TEST(CborFloatTest, HalfNaN) +{ + json j = json::from_cbor("\xf9\x7c\x01"); + json::number_float_t d = j; + EXPECT_TRUE(std::isnan(d)); + EXPECT_EQ(j.dump(), "null"); +} + +// N = 0..23 +TEST(CborStringTest, String1) +{ + for (size_t N = 0; N <= 0x17; ++N) + { + SCOPED_TRACE(N); + + // create JSON value with string containing of N * 'x' + const auto s = std::string(N, 'x'); + json j = s; + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0x60 + N)); + expected.append(s); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), N + 1); + // check that no null byte is appended + if (N > 0) + { + EXPECT_NE(result.back(), '\x00'); + } + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// N = 24..255 +TEST(CborStringTest, String2) +{ + for (size_t N = 24; N <= 255; ++N) + { + SCOPED_TRACE(N); + + // create JSON value with string containing of N * 'x' + const auto s = std::string(N, 'x'); + json j = s; + + // create expected byte vector + std::string expected; + expected.push_back(0x78); + expected.push_back(static_cast(N)); + expected.append(s); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), N + 2); + // check that no null byte is appended + EXPECT_NE(result.back(), '\x00'); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); + } +} + +// N = 256..65535 +class CborString3Test : public ::testing::TestWithParam {}; +TEST_P(CborString3Test, Case) +{ + // create JSON value with string containing of N * 'x' + const auto s = std::string(GetParam(), 'x'); + json j = s; + + // create expected byte vector + std::string expected; + expected.push_back(0x79); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + expected.append(s); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), GetParam() + 3); + // check that no null byte is appended + EXPECT_NE(result.back(), '\x00'); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +static size_t string3_lens[] = { + 256u, + 999u, + 1025u, + 3333u, + 2048u, + 65535u +}; + +INSTANTIATE_TEST_CASE_P(CborString3Tests, CborString3Test, + ::testing::ValuesIn(string3_lens)); + +// N = 65536..4294967295 +class CborString5Test : public ::testing::TestWithParam {}; +TEST_P(CborString5Test, Case) +{ + // create JSON value with string containing of N * 'x' + const auto s = std::string(GetParam(), 'x'); + json j = s; + + // create expected byte vector + std::string expected; + expected.push_back(0x7a); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + expected.append(s); + + // compare result + size + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + ASSERT_EQ(result.size(), GetParam() + 5); + // check that no null byte is appended + EXPECT_NE(result.back(), '\x00'); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +static size_t string5_lens[] = { + 65536u, + 77777u, + 1048576u +}; + +INSTANTIATE_TEST_CASE_P(CborString5Tests, CborString5Test, + ::testing::ValuesIn(string5_lens)); + +TEST(CborArrayTest, Empty) +{ + json j = json::array(); + std::string expected = "\x80"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// [null] +TEST(CborArrayTest, Null) +{ + json j = {nullptr}; + std::string expected = "\x81\xf6"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// [1,2,3,4,5] +TEST(CborArrayTest, Simple) +{ + json j = json::parse("[1,2,3,4,5]"); + std::string expected = "\x85\x01\x02\x03\x04\x05"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// [[[[]]]] +TEST(CborArrayTest, NestEmpty) +{ + json j = json::parse("[[[[]]]]"); + std::string expected = "\x81\x81\x81\x80"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// array with uint16_t elements +TEST(CborArrayTest, UInt16) +{ + json j(257, nullptr); + std::string expected(j.size() + 3, static_cast(0xf6)); // all null + expected[0] = static_cast(0x99); // array 16 bit + expected[1] = 0x01; // size (0x0101), byte 0 + expected[2] = 0x01; // size (0x0101), byte 1 + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// array with uint32_t elements +TEST(CborArrayTest, UInt32) +{ + json j(65793, nullptr); + std::string expected(j.size() + 5, static_cast(0xf6)); // all null + expected[0] = static_cast(0x9a); // array 32 bit + expected[1] = 0x00; // size (0x00010101), byte 0 + expected[2] = 0x01; // size (0x00010101), byte 1 + expected[3] = 0x01; // size (0x00010101), byte 2 + expected[4] = 0x01; // size (0x00010101), byte 3 + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +/* +// array with uint64_t elements +TEST(CborArrayTest, UInt64) +{ + json j(4294967296, nullptr); + std::string expected(j.size() + 9, static_cast(0xf6)); // all null + expected[0] = 0x9b; // array 64 bit + expected[1] = 0x00; // size (0x0000000100000000), byte 0 + expected[2] = 0x00; // size (0x0000000100000000), byte 1 + expected[3] = 0x00; // size (0x0000000100000000), byte 2 + expected[4] = 0x01; // size (0x0000000100000000), byte 3 + expected[5] = 0x00; // size (0x0000000100000000), byte 4 + expected[6] = 0x00; // size (0x0000000100000000), byte 5 + expected[7] = 0x00; // size (0x0000000100000000), byte 6 + expected[8] = 0x00; // size (0x0000000100000000), byte 7 + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} +*/ + +TEST(CborObjectTest, Empty) +{ + json j = json::object(); + std::string expected = "\xa0"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// {"":null} +TEST(CborObjectTest, EmptyKey) +{ + json j = {{"", nullptr}}; + std::string expected = "\xa1\x60\xf6"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// {"a": {"b": {"c": {}}}} +TEST(CborObjectTest, NestedEmpty) +{ + json j = json::parse("{\"a\": {\"b\": {\"c\": {}}}}"); + std::string expected = "\xa1\x61\x61\xa1\x61\x62\xa1\x61\x63\xa0"; + const auto result = json::to_cbor(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// object with uint8_t elements +TEST(CborObjectTest, UInt8) +{ + json j; + for (auto i = 0; i < 255; ++i) + { + // format i to a fixed width of 5 + // each entry will need 7 bytes: 6 for string, 1 for null + std::stringstream ss; + ss << std::setw(5) << std::setfill('0') << i; + j.emplace(ss.str(), nullptr); + } + + const auto result = json::to_cbor(j); + + // Checking against an expected vector byte by byte is + // difficult, because no assumption on the order of key/value + // pairs are made. We therefore only check the prefix (type and + // size and the overall size. The rest is then handled in the + // roundtrip check. + ASSERT_EQ(result.size(), 1787u); // 1 type, 1 size, 255*7 content + EXPECT_EQ(result[0], static_cast(0xb8)); // map 8 bit + EXPECT_EQ(result[1], static_cast(0xff)); // size byte (0xff) + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// object with uint16_t elements +TEST(CborObjectTest, UInt16) +{ + json j; + for (auto i = 0; i < 256; ++i) + { + // format i to a fixed width of 5 + // each entry will need 7 bytes: 6 for string, 1 for null + std::stringstream ss; + ss << std::setw(5) << std::setfill('0') << i; + j.emplace(ss.str(), nullptr); + } + + const auto result = json::to_cbor(j); + + // Checking against an expected vector byte by byte is + // difficult, because no assumption on the order of key/value + // pairs are made. We therefore only check the prefix (type and + // size and the overall size. The rest is then handled in the + // roundtrip check. + ASSERT_EQ(result.size(), 1795u); // 1 type, 2 size, 256*7 content + EXPECT_EQ(result[0], static_cast(0xb9)); // map 16 bit + EXPECT_EQ(result[1], 0x01); // byte 0 of size (0x0100) + EXPECT_EQ(result[2], 0x00); // byte 1 of size (0x0100) + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// object with uint32_t elements +TEST(CborObjectTest, UInt32) +{ + json j; + for (auto i = 0; i < 65536; ++i) + { + // format i to a fixed width of 5 + // each entry will need 7 bytes: 6 for string, 1 for null + std::stringstream ss; + ss << std::setw(5) << std::setfill('0') << i; + j.emplace(ss.str(), nullptr); + } + + const auto result = json::to_cbor(j); + + // Checking against an expected vector byte by byte is + // difficult, because no assumption on the order of key/value + // pairs are made. We therefore only check the prefix (type and + // size and the overall size. The rest is then handled in the + // roundtrip check. + ASSERT_EQ(result.size(), 458757u); // 1 type, 4 size, 65536*7 content + EXPECT_EQ(result[0], static_cast(0xba)); // map 32 bit + EXPECT_EQ(result[1], 0x00); // byte 0 of size (0x00010000) + EXPECT_EQ(result[2], 0x01); // byte 1 of size (0x00010000) + EXPECT_EQ(result[3], 0x00); // byte 2 of size (0x00010000) + EXPECT_EQ(result[4], 0x00); // byte 3 of size (0x00010000) + + // roundtrip + EXPECT_EQ(json::from_cbor(result), j); +} + +// 0x7b (string) +TEST(CborAdditionalDeserializationTest, Case7b) +{ + std::string given("\x7b\x00\x00\x00\x00\x00\x00\x00\x01\x61", 10); + json j = json::from_cbor(given); + EXPECT_EQ(j, "a"); +} + +// 0x9b (array) +TEST(CborAdditionalDeserializationTest, Case9b) +{ + std::string given("\x9b\x00\x00\x00\x00\x00\x00\x00\x01\xf4", 10); + json j = json::from_cbor(given); + EXPECT_EQ(j, json::parse("[false]")); +} + +// 0xbb (map) +TEST(CborAdditionalDeserializationTest, Casebb) +{ + std::string given("\xbb\x00\x00\x00\x00\x00\x00\x00\x01\x60\xf4", 11); + json j = json::from_cbor(given); + EXPECT_EQ(j, json::parse("{\"\": false}")); +} + +TEST(CborErrorTest, TooShortByteVector) +{ + EXPECT_THROW_MSG(json::from_cbor("\x18"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor("\x19"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x19\x00", 2)), json::parse_error, + "[json.exception.parse_error.110] parse error at 3: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor("\x1a"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1a\x00", 2)), json::parse_error, + "[json.exception.parse_error.110] parse error at 3: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1a\x00\x00", 3)), json::parse_error, + "[json.exception.parse_error.110] parse error at 4: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1a\x00\x00\x00", 4)), json::parse_error, + "[json.exception.parse_error.110] parse error at 5: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor("\x1b"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00", 2)), json::parse_error, + "[json.exception.parse_error.110] parse error at 3: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00\x00", 3)), json::parse_error, + "[json.exception.parse_error.110] parse error at 4: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00\x00\x00", 4)), json::parse_error, + "[json.exception.parse_error.110] parse error at 5: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00\x00\x00\x00", 5)), json::parse_error, + "[json.exception.parse_error.110] parse error at 6: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00\x00\x00\x00\x00", 6)), json::parse_error, + "[json.exception.parse_error.110] parse error at 7: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00\x00\x00\x00\x00\x00", 7)), json::parse_error, + "[json.exception.parse_error.110] parse error at 8: unexpected end of input"); + EXPECT_THROW_MSG(json::from_cbor(llvm::StringRef("\x1b\x00\x00\x00\x00\x00\x00\x00", 8)), json::parse_error, + "[json.exception.parse_error.110] parse error at 9: unexpected end of input"); +} + +TEST(CborErrorTest, UnsupportedBytesConcrete) +{ + EXPECT_THROW_MSG(json::from_cbor("\x1c"), json::parse_error, + "[json.exception.parse_error.112] parse error at 1: error reading CBOR; last byte: 0x1c"); + EXPECT_THROW_MSG(json::from_cbor("\xf8"), json::parse_error, + "[json.exception.parse_error.112] parse error at 1: error reading CBOR; last byte: 0xf8"); +} + +class CborUnsupportedBytesTest : public ::testing::TestWithParam { +}; +TEST_P(CborUnsupportedBytesTest, Case) +{ + EXPECT_THROW(json::from_cbor(GetParam()), json::parse_error); +} + +static const char* unsupported_bytes_cases[] = { + // ? + "\x1c\x1d\x1e\x1f", + // ? + "\x3c\x3d\x3e\x3f", + // byte strings + "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x50\x51\x52\x53\x54\x55\x56\x57", + // byte strings + "\x58\x59\x5a\x5b", + // ? + "\x5c\x5d\x5e", + // byte string + "\x5f", + // ? + "\x7c\x7d\x7e", + // ? + "\x9c\x9d\x9e", + // ? + "\xbc\xbd\xbe", + // date/time + "\xc0\xc1", + // bignum + "\xc2\xc3", + // fraction + "\xc4", + // bigfloat + "\xc5", + // tagged item + "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4", + // expected conversion + "\xd5\xd6\xd7", + // more tagged items + "\xd8\xd9\xda\xdb", + // ? + "\xdc\xdd\xde\xdf", + // (simple value) + "\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3", + // undefined + "\xf7", + // simple value + "\xf8", +}; + +INSTANTIATE_TEST_CASE_P(CborUnsupportedBytesTests, CborUnsupportedBytesTest, + ::testing::ValuesIn(unsupported_bytes_cases)); +#if 0 +// use this testcase outside [hide] to run it with Valgrind +TEST(CborRoundtripTest, Sample) +{ + std::string filename = "test/data/json_testsuite/sample.json"; + + // parse JSON file + std::ifstream f_json(filename); + json j1 = json::parse(f_json); + + // parse CBOR file + std::ifstream f_cbor(filename + ".cbor", std::ios::binary); + std::vector packed((std::istreambuf_iterator(f_cbor)), + std::istreambuf_iterator()); + json j2; + j2 = json::from_cbor(packed); + + // compare parsed JSON values + EXPECT_EQ(j1, j2); + + // check with different start index + packed.insert(packed.begin(), 5, 0xff); + EXPECT_EQ(j1, json::from_cbor(packed, 5)); +} + +/* +The following test cases were found during a two-day session with +AFL-Fuzz. As a result, empty byte vectors and excessive lengths are +detected. +*/ +class CborRegressionFuzzTest : public ::testing::TestWithParam {}; +TEST_P(CborRegressionFuzzTest, Case) +{ + try + { + // parse CBOR file + std::ifstream f_cbor(GetParam(), std::ios::binary); + std::vector vec1( + (std::istreambuf_iterator(f_cbor)), + std::istreambuf_iterator()); + json j1 = json::from_cbor(vec1); + + try + { + // step 2: round trip + std::string vec2 = json::to_cbor(j1); + + // parse serialization + json j2 = json::from_cbor(vec2); + + // deserializations must match + EXPECT_EQ(j1, j2); + } + catch (const json::parse_error&) + { + // parsing a CBOR serialization must not fail + FAIL(); + } + } + catch (const json::parse_error&) + { + // parse errors are ok, because input may be random bytes + } +} + +static const char* fuzz_test_cases[] = { + "test/data/cbor_regression/test01", + "test/data/cbor_regression/test02", + "test/data/cbor_regression/test03", + "test/data/cbor_regression/test04", + "test/data/cbor_regression/test05", + "test/data/cbor_regression/test06", + "test/data/cbor_regression/test07", + "test/data/cbor_regression/test08", + "test/data/cbor_regression/test09", + "test/data/cbor_regression/test10", + "test/data/cbor_regression/test11", + "test/data/cbor_regression/test12", + "test/data/cbor_regression/test13", + "test/data/cbor_regression/test14", + "test/data/cbor_regression/test15", + "test/data/cbor_regression/test16", + "test/data/cbor_regression/test17", + "test/data/cbor_regression/test18", + "test/data/cbor_regression/test19", + "test/data/cbor_regression/test20", + "test/data/cbor_regression/test21", +}; + +INSTANTIATE_TEST_CASE_P(CborRegressionFuzzTests, CborRegressionFuzzTest, + ::testing::ValuesIn(fuzz_test_cases)); + +class CborRegressionFlynnTest : public ::testing::TestWithParam {}; +TEST_F(CborRegressionFlynnTest, Case) +{ + // parse JSON file + std::ifstream f_json(GetParam()); + json j1 = json::parse(f_json); + + // parse CBOR file + std::ifstream f_cbor(filename + ".cbor", std::ios::binary); + std::vector packed( + (std::istreambuf_iterator(f_cbor)), + std::istreambuf_iterator()); + json j2; + j2 = json::from_cbor(packed); + + // compare parsed JSON values + EXPECT_EQ(j1, j2); +} + +static const char* flynn_test_cases[] = { + "test/data/json_nlohmann_tests/all_unicode.json", + "test/data/json.org/1.json", + "test/data/json.org/2.json", + "test/data/json.org/3.json", + "test/data/json.org/4.json", + "test/data/json.org/5.json", + "test/data/json_roundtrip/roundtrip01.json", + "test/data/json_roundtrip/roundtrip02.json", + "test/data/json_roundtrip/roundtrip03.json", + "test/data/json_roundtrip/roundtrip04.json", + "test/data/json_roundtrip/roundtrip05.json", + "test/data/json_roundtrip/roundtrip06.json", + "test/data/json_roundtrip/roundtrip07.json", + "test/data/json_roundtrip/roundtrip08.json", + "test/data/json_roundtrip/roundtrip09.json", + "test/data/json_roundtrip/roundtrip10.json", + "test/data/json_roundtrip/roundtrip11.json", + "test/data/json_roundtrip/roundtrip12.json", + "test/data/json_roundtrip/roundtrip13.json", + "test/data/json_roundtrip/roundtrip14.json", + "test/data/json_roundtrip/roundtrip15.json", + "test/data/json_roundtrip/roundtrip16.json", + "test/data/json_roundtrip/roundtrip17.json", + "test/data/json_roundtrip/roundtrip18.json", + "test/data/json_roundtrip/roundtrip19.json", + "test/data/json_roundtrip/roundtrip20.json", + "test/data/json_roundtrip/roundtrip21.json", + "test/data/json_roundtrip/roundtrip22.json", + "test/data/json_roundtrip/roundtrip23.json", + "test/data/json_roundtrip/roundtrip24.json", + "test/data/json_roundtrip/roundtrip25.json", + "test/data/json_roundtrip/roundtrip26.json", + "test/data/json_roundtrip/roundtrip27.json", + "test/data/json_roundtrip/roundtrip28.json", + "test/data/json_roundtrip/roundtrip29.json", + "test/data/json_roundtrip/roundtrip30.json", + "test/data/json_roundtrip/roundtrip31.json", + "test/data/json_roundtrip/roundtrip32.json", + "test/data/json_testsuite/sample.json", // kills AppVeyor + "test/data/json_tests/pass1.json", + "test/data/json_tests/pass2.json", + "test/data/json_tests/pass3.json", + "test/data/regression/floats.json", + "test/data/regression/signed_ints.json", + "test/data/regression/unsigned_ints.json", + "test/data/regression/working_file.json", + "test/data/nst_json_testsuite/test_parsing/y_array_arraysWithSpaces.json", + "test/data/nst_json_testsuite/test_parsing/y_array_empty-string.json", + "test/data/nst_json_testsuite/test_parsing/y_array_empty.json", + "test/data/nst_json_testsuite/test_parsing/y_array_ending_with_newline.json", + "test/data/nst_json_testsuite/test_parsing/y_array_false.json", + "test/data/nst_json_testsuite/test_parsing/y_array_heterogeneous.json", + "test/data/nst_json_testsuite/test_parsing/y_array_null.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_1_and_newline.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_leading_space.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_several_null.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_trailing_space.json", + "test/data/nst_json_testsuite/test_parsing/y_number.json", + "test/data/nst_json_testsuite/test_parsing/y_number_0e+1.json", + "test/data/nst_json_testsuite/test_parsing/y_number_0e1.json", + "test/data/nst_json_testsuite/test_parsing/y_number_after_space.json", + "test/data/nst_json_testsuite/test_parsing/y_number_double_close_to_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_number_double_huge_neg_exp.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_huge_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_int_with_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_minus_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_number_negative_int.json", + "test/data/nst_json_testsuite/test_parsing/y_number_negative_one.json", + "test/data/nst_json_testsuite/test_parsing/y_number_negative_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_capital_e.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_capital_e_neg_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_capital_e_pos_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_exponent.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_fraction_exponent.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_neg_exp.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_real_neg_overflow.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_pos_exponent.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_real_pos_overflow.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_underflow.json", + "test/data/nst_json_testsuite/test_parsing/y_number_simple_int.json", + "test/data/nst_json_testsuite/test_parsing/y_number_simple_real.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_too_big_neg_int.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_too_big_pos_int.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_very_big_negative_int.json", + "test/data/nst_json_testsuite/test_parsing/y_object.json", + "test/data/nst_json_testsuite/test_parsing/y_object_basic.json", + "test/data/nst_json_testsuite/test_parsing/y_object_duplicated_key.json", + "test/data/nst_json_testsuite/test_parsing/y_object_duplicated_key_and_value.json", + "test/data/nst_json_testsuite/test_parsing/y_object_empty.json", + "test/data/nst_json_testsuite/test_parsing/y_object_empty_key.json", + "test/data/nst_json_testsuite/test_parsing/y_object_escaped_null_in_key.json", + "test/data/nst_json_testsuite/test_parsing/y_object_extreme_numbers.json", + "test/data/nst_json_testsuite/test_parsing/y_object_long_strings.json", + "test/data/nst_json_testsuite/test_parsing/y_object_simple.json", + "test/data/nst_json_testsuite/test_parsing/y_object_string_unicode.json", + "test/data/nst_json_testsuite/test_parsing/y_object_with_newlines.json", + "test/data/nst_json_testsuite/test_parsing/y_string_1_2_3_bytes_UTF-8_sequences.json", + "test/data/nst_json_testsuite/test_parsing/y_string_UTF-16_Surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_accepted_surrogate_pair.json", + "test/data/nst_json_testsuite/test_parsing/y_string_accepted_surrogate_pairs.json", + "test/data/nst_json_testsuite/test_parsing/y_string_allowed_escapes.json", + "test/data/nst_json_testsuite/test_parsing/y_string_backslash_and_u_escaped_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_string_backslash_doublequotes.json", + "test/data/nst_json_testsuite/test_parsing/y_string_comments.json", + "test/data/nst_json_testsuite/test_parsing/y_string_double_escape_a.json", + "test/data/nst_json_testsuite/test_parsing/y_string_double_escape_n.json", + "test/data/nst_json_testsuite/test_parsing/y_string_escaped_control_character.json", + "test/data/nst_json_testsuite/test_parsing/y_string_escaped_noncharacter.json", + "test/data/nst_json_testsuite/test_parsing/y_string_in_array.json", + "test/data/nst_json_testsuite/test_parsing/y_string_in_array_with_leading_space.json", + "test/data/nst_json_testsuite/test_parsing/y_string_last_surrogates_1_and_2.json", + "test/data/nst_json_testsuite/test_parsing/y_string_newline_uescaped.json", + "test/data/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+10FFFF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+1FFFF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+FFFF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_null_escape.json", + "test/data/nst_json_testsuite/test_parsing/y_string_one-byte-utf-8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_pi.json", + "test/data/nst_json_testsuite/test_parsing/y_string_simple_ascii.json", + "test/data/nst_json_testsuite/test_parsing/y_string_space.json", + "test/data/nst_json_testsuite/test_parsing/y_string_three-byte-utf-8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_two-byte-utf-8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_u+2028_line_sep.json", + "test/data/nst_json_testsuite/test_parsing/y_string_u+2029_par_sep.json", + "test/data/nst_json_testsuite/test_parsing/y_string_uEscape.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unescaped_char_delete.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicodeEscapedBackslash.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_2.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_U+2064_invisible_plus.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_escaped_double_quote.json", + // "test/data/nst_json_testsuite/test_parsing/y_string_utf16.json", + "test/data/nst_json_testsuite/test_parsing/y_string_utf8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_with_del_character.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_false.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_int.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_negative_real.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_null.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_string.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_true.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_string_empty.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_trailing_newline.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_true_in_array.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_whitespace_array.json", +}; + +INSTANTIATE_TEST_CASE_P(CborRegressionFlynnTests, CborRegressionFlynnTest, + ::testing::ValuesIn(flynn_test_cases)); + +#endif +TEST(CborFirstBytesTest, Unsupported) +{ + // these bytes will fail immediately with exception parse_error.112 + std::set unsupported = + { + //// types not supported by this library + + // byte strings + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + // byte strings + 0x58, 0x59, 0x5a, 0x5b, 0x5f, + // date/time + 0xc0, 0xc1, + // bignum + 0xc2, 0xc3, + // decimal fracion + 0xc4, + // bigfloat + 0xc5, + // tagged item + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, + 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd8, + 0xd9, 0xda, 0xdb, + // expected conversion + 0xd5, 0xd6, 0xd7, + // simple value + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xef, 0xf0, + 0xf1, 0xf2, 0xf3, + 0xf8, + // undefined + 0xf7, + + //// bytes not specified by CBOR + + 0x1c, 0x1d, 0x1e, 0x1f, + 0x3c, 0x3d, 0x3e, 0x3f, + 0x5c, 0x5d, 0x5e, + 0x7c, 0x7d, 0x7e, + 0x9c, 0x9d, 0x9e, + 0xbc, 0xbd, 0xbe, + 0xdc, 0xdd, 0xde, 0xdf, + 0xee, + 0xfc, 0xfe, 0xfd, + + /// break cannot be the first byte + + 0xff + }; + + for (auto i = 0; i < 256; ++i) + { + const auto byte = static_cast(i); + + try + { + json::from_cbor(llvm::StringRef(&byte, 1)); + } + catch (const json::parse_error& e) + { + // check that parse_error.112 is only thrown if the + // first byte is in the unsupported set + SCOPED_TRACE(e.what()); + if (std::find(unsupported.begin(), unsupported.end(), + static_cast(byte)) != unsupported.end()) + { + EXPECT_EQ(e.id, 112); + } + else + { + EXPECT_NE(e.id, 112); + } + } + } +} + +// examples from RFC 7049 Appendix A +namespace { +struct CborRoundtripTestParam { + const char* plain; + llvm::StringRef encoded; + bool test_encode; +}; +} // anonymous namespace + +class CborRoundtripTest + : public ::testing::TestWithParam { +}; +TEST_P(CborRoundtripTest, Case) +{ + if (GetParam().test_encode) + { + EXPECT_EQ(json::to_cbor(json::parse(GetParam().plain)), GetParam().encoded); + } + EXPECT_EQ(json::parse(GetParam().plain), json::from_cbor(GetParam().encoded)); +} + +static const CborRoundtripTestParam rfc7049_appendix_a_numbers[] = { + {"0", llvm::StringRef("\x00", 1), true}, + {"1", "\x01", true}, + {"10", "\x0a", true}, + {"23", "\x17", true}, + {"24", "\x18\x18", true}, + {"25", "\x18\x19", true}, + {"100", "\x18\x64", true}, + {"1000", "\x19\x03\xe8", true}, + {"1000000", llvm::StringRef("\x1a\x00\x0f\x42\x40", 5), true}, + {"1000000000000", llvm::StringRef("\x1b\x00\x00\x00\xe8\xd4\xa5\x10\x00", 9), true}, + {"18446744073709551615", "\x1b\xff\xff\xff\xff\xff\xff\xff\xff", true}, + // positive bignum is not supported + //{"18446744073709551616", llvm::StringRef("\xc2\x49\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11), true}, + //{"-18446744073709551616", "\x3b\xff\xff\xff\xff\xff\xff\xff\xff", true}, + // negative bignum is not supported + //{"-18446744073709551617", llvm::StringRef("\xc3\x49\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11), true}, + {"-1", "\x20", true}, + {"-10", "\x29", true}, + {"-100", "\x38\x63", true}, + {"-1000", "\x39\x03\xe7", true}, + // half-precision float + {"0.0", llvm::StringRef("\xf9\x00\x00", 3), false}, + // half-precision float + {"-0.0", llvm::StringRef("\xf9\x80\x00", 3), false}, + // half-precision float + {"1.0", llvm::StringRef("\xf9\x3c\x00", 3), false}, + {"1.1", "\xfb\x3f\xf1\x99\x99\x99\x99\x99\x9a", true}, + // half-precision float + {"1.5", llvm::StringRef("\xf9\x3e\x00", 3), false}, + // half-precision float + {"65504.0", "\xf9\x7b\xff", false}, + {"100000.0", llvm::StringRef("\xfa\x47\xc3\x50\x00", 5), false}, + {"3.4028234663852886e+38", "\xfa\x7f\x7f\xff\xff", false}, + {"1.0e+300", llvm::StringRef("\xfb\x7e\x37\xe4\x3c\x88\x00\x75\x9c", 9), true}, + // half-precision float + {"5.960464477539063e-8", llvm::StringRef("\xf9\x00\x01", 3), false}, + // half-precision float + {"0.00006103515625", llvm::StringRef("\xf9\x04\x00", 3), false}, + // half-precision float + {"-4.0", llvm::StringRef("\xf9\xc4\x00", 3), false}, + {"-4.1", "\xfb\xc0\x10\x66\x66\x66\x66\x66\x66", true}, +}; + +INSTANTIATE_TEST_CASE_P(CborRfc7049AppendixANumberTests, CborRoundtripTest, + ::testing::ValuesIn(rfc7049_appendix_a_numbers)); + +static const CborRoundtripTestParam rfc7049_appendix_a_simple_values[] = { + {"false", "\xf4", true}, + {"true", "\xf5", true}, +}; + +INSTANTIATE_TEST_CASE_P(CborRfc7049AppendixASimpleValueTests, CborRoundtripTest, + ::testing::ValuesIn(rfc7049_appendix_a_simple_values)); + +static const CborRoundtripTestParam rfc7049_appendix_a_strings[] = { + {"\"\"", "\x60", true}, + {"\"a\"", "\x61\x61", true}, + {"\"IETF\"", "\x64\x49\x45\x54\x46", true}, + {"\"\\u00fc\"", "\x62\xc3\xbc", true}, + {"\"\\u6c34\"", "\x63\xe6\xb0\xb4", true}, + {"\"\\ud800\\udd51\"", "\x64\xf0\x90\x85\x91", true}, + // indefinite length strings + {"\"streaming\"", "\x7f\x73\x74\x72\x65\x61\x6d\x69\x6e\x67\xff", false}, +}; + +INSTANTIATE_TEST_CASE_P(CborRfc7049AppendixAStringTests, CborRoundtripTest, + ::testing::ValuesIn(rfc7049_appendix_a_strings)); + +static const CborRoundtripTestParam rfc7049_appendix_a_arrays[] = { + {"[]", "\x80", true}, + {"[1, 2, 3]", "\x83\x01\x02\x03", true}, + {"[1, [2, 3], [4, 5]]", "\x83\x01\x82\x02\x03\x82\x04\x05", true}, + {"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]", "\x98\x19\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x18\x18\x19", true}, + // indefinite length arrays + {"[]", "\x9f\xff", false}, + {"[1, [2, 3], [4, 5]] ", "\x9f\x01\x82\x02\x03\x9f\x04\x05\xff\xff", false}, + {"[1, [2, 3], [4, 5]]", "\x9f\x01\x82\x02\x03\x82\x04\x05\xff", false}, + {"[1, [2, 3], [4, 5]]", "\x83\x01\x82\x02\x03\x9f\x04\x05\xff", false}, + {"[1, [2, 3], [4, 5]]", "\x83\x01\x9f\x02\x03\xff\x82\x04\x05", false}, + {"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]", "\x9f\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x18\x18\x19\xff", false}, +}; + +INSTANTIATE_TEST_CASE_P(CborRfc7049AppendixAArrayTests, CborRoundtripTest, + ::testing::ValuesIn(rfc7049_appendix_a_arrays)); + +static const CborRoundtripTestParam rfc7049_appendix_a_objects[] = { + {"{}", "\xa0", true}, + {"{\"a\": 1, \"b\": [2, 3]}", "\xa2\x61\x61\x01\x61\x62\x82\x02\x03", true}, + {"[\"a\", {\"b\": \"c\"}]", "\x82\x61\x61\xa1\x61\x62\x61\x63", true}, + {"{\"a\": \"A\", \"b\": \"B\", \"c\": \"C\", \"d\": \"D\", \"e\": \"E\"}", "\xa5\x61\x61\x61\x41\x61\x62\x61\x42\x61\x63\x61\x43\x61\x64\x61\x44\x61\x65\x61\x45", true}, + // indefinite length objects + {"{\"a\": 1, \"b\": [2, 3]}", "\xbf\x61\x61\x01\x61\x62\x9f\x02\x03\xff\xff", false}, + {"[\"a\", {\"b\": \"c\"}]", "\x82\x61\x61\xbf\x61\x62\x61\x63\xff", false}, + {"{\"Fun\": true, \"Amt\": -2}", "\xbf\x63\x46\x75\x6e\xf5\x63\x41\x6d\x74\x21\xff", false}, +}; + +INSTANTIATE_TEST_CASE_P(CborRfc7049AppendixAObjectTests, CborRoundtripTest, + ::testing::ValuesIn(rfc7049_appendix_a_objects)); diff --git a/src/test/native/cpp/json/unit-comparison.cpp b/src/test/native/cpp/json/unit-comparison.cpp new file mode 100644 index 0000000000..18934a20aa --- /dev/null +++ b/src/test/native/cpp/json/unit-comparison.cpp @@ -0,0 +1,250 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +class JsonComparisonTypesTest : public ::testing::Test { + protected: + std::vector j_types = + { + json::value_t::null, + json::value_t::boolean, + json::value_t::number_integer, + json::value_t::number_unsigned, + json::value_t::number_float, + json::value_t::object, + json::value_t::array, + json::value_t::string + }; +}; + +TEST_F(JsonComparisonTypesTest, Less) +{ + static const std::vector> expected = + { + {false, true, true, true, true, true, true, true}, + {false, false, true, true, true, true, true, true}, + {false, false, false, false, false, true, true, true}, + {false, false, false, false, false, true, true, true}, + {false, false, false, false, false, true, true, true}, + {false, false, false, false, false, false, true, true}, + {false, false, false, false, false, false, false, true}, + {false, false, false, false, false, false, false, false} + }; + + for (size_t i = 0; i < j_types.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_types.size(); ++j) + { + SCOPED_TRACE(j); + // check precomputed values + EXPECT_EQ(operator<(j_types[i], j_types[j]), expected[i][j]); + } + } +} + +class JsonComparisonValuesTest : public ::testing::Test { + protected: + json j_values = + { + nullptr, nullptr, + 17, 42, + 8u, 13u, + 3.14159, 23.42, + "foo", "bar", + true, false, + {1, 2, 3}, {"one", "two", "three"}, + {{"first", 1}, {"second", 2}}, {{"a", "A"}, {"b", {"B"}}} + }; +}; + +TEST_F(JsonComparisonValuesTest, Equal) +{ + static const std::vector> expected = + { + {true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, + {true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, + {false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false}, + {false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false}, + {false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false}, + {false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false}, + {false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false}, + {false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false}, + {false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false}, + {false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false}, + {false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false}, + {false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false}, + {false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false}, + {false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false}, + {false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false}, + {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true} + }; + + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_values.size(); ++j) + { + SCOPED_TRACE(j); + // check precomputed values + EXPECT_EQ(j_values[i] == j_values[j], expected[i][j]); + } + } + + // comparison with discarded elements + json j_discarded(json::value_t::discarded); + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + EXPECT_FALSE(j_values[i] == j_discarded); + EXPECT_FALSE(j_discarded == j_values[i]); + EXPECT_FALSE(j_discarded == j_discarded); + } + + // compare with null pointer + json j_null; + EXPECT_TRUE(j_null == nullptr); + EXPECT_TRUE(nullptr == j_null); +} + +TEST_F(JsonComparisonValuesTest, NotEqual) +{ + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_values.size(); ++j) + { + SCOPED_TRACE(j); + // check definition + EXPECT_EQ(j_values[i] != j_values[j], !(j_values[i] == j_values[j])); + } + } + + // compare with null pointer + json j_null; + EXPECT_FALSE(j_null != nullptr); + EXPECT_FALSE(nullptr != j_null); + EXPECT_EQ(j_null != nullptr, !(j_null == nullptr)); + EXPECT_EQ(nullptr != j_null, !(nullptr == j_null)); +} + +TEST_F(JsonComparisonValuesTest, Less) +{ + static const std::vector> expected = + { + {false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true}, + {false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true}, + {false, false, false, true, false, false, false, true, true, true, false, false, true, true, true, true}, + {false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, true}, + {false, false, true, true, false, true, false, true, true, true, false, false, true, true, true, true}, + {false, false, true, true, false, false, false, true, true, true, false, false, true, true, true, true}, + {false, false, true, true, true, true, false, true, true, true, false, false, true, true, true, true}, + {false, false, false, true, false, false, false, false, true, true, false, false, true, true, true, true}, + {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, + {false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false}, + {false, false, true, true, true, true, true, true, true, true, false, false, true, true, true, true}, + {false, false, true, true, true, true, true, true, true, true, true, false, true, true, true, true}, + {false, false, false, false, false, false, false, false, true, true, false, false, false, true, false, false}, + {false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false}, + {false, false, false, false, false, false, false, false, true, true, false, false, true, true, false, false}, + {false, false, false, false, false, false, false, false, true, true, false, false, true, true, true, false} + }; + + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_values.size(); ++j) + { + SCOPED_TRACE(j); + // check precomputed values + EXPECT_EQ(j_values[i] < j_values[j], expected[i][j]); + } + } + + // comparison with discarded elements + json j_discarded(json::value_t::discarded); + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + EXPECT_FALSE(j_values[i] < j_discarded); + EXPECT_FALSE(j_discarded < j_values[i]); + EXPECT_FALSE(j_discarded < j_discarded); + } +} + +TEST_F(JsonComparisonValuesTest, LessEqual) +{ + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_values.size(); ++j) + { + SCOPED_TRACE(j); + // check definition + EXPECT_EQ(j_values[i] <= j_values[j], !(j_values[j] < j_values[i])); + } + } +} + +TEST_F(JsonComparisonValuesTest, Greater) +{ + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_values.size(); ++j) + { + SCOPED_TRACE(j); + // check definition + EXPECT_EQ(j_values[i] > j_values[j], j_values[j] < j_values[i]); + } + } +} + +TEST_F(JsonComparisonValuesTest, GreaterEqual) +{ + for (size_t i = 0; i < j_values.size(); ++i) + { + SCOPED_TRACE(i); + for (size_t j = 0; j < j_values.size(); ++j) + { + SCOPED_TRACE(j); + // check definition + EXPECT_EQ(j_values[i] >= j_values[j], !(j_values[i] < j_values[j])); + } + } +} diff --git a/src/test/native/cpp/json/unit-concepts.cpp b/src/test/native/cpp/json/unit-concepts.cpp new file mode 100644 index 0000000000..4ce5a5b910 --- /dev/null +++ b/src/test/native/cpp/json/unit-concepts.cpp @@ -0,0 +1,166 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonConceptsTest, ContainerRequirements) +{ + // X: container class: json + // T: type of objects: json + // a, b: values of type X: json + + // TABLE 96 - Container Requirements + + // X::value_type must return T + EXPECT_TRUE((std::is_same::value)); + + // X::reference must return lvalue of T + EXPECT_TRUE((std::is_same::value)); + + // X::const_reference must return const lvalue of T + EXPECT_TRUE((std::is_same::value)); + + // X::iterator must return iterator whose value_type is T + EXPECT_TRUE((std::is_same::value)); + // X::iterator must meet the forward iterator requirements + EXPECT_TRUE((std::is_base_of::iterator_category>::value)); + // X::iterator must be convertible to X::const_iterator + EXPECT_TRUE((std::is_convertible::value)); + + // X::const_iterator must return iterator whose value_type is T + EXPECT_TRUE((std::is_same::value)); + // X::const_iterator must meet the forward iterator requirements + EXPECT_TRUE((std::is_base_of::iterator_category>::value)); + + // X::difference_type must return a signed integer + EXPECT_TRUE((std::is_signed::value)); + // X::difference_type must be identical to X::iterator::difference_type + EXPECT_TRUE((std::is_same::value)); + // X::difference_type must be identical to X::const_iterator::difference_type + EXPECT_TRUE((std::is_same::value)); + + // X::size_type must return an unsigned integer + EXPECT_TRUE((std::is_unsigned::value)); + // X::size_type can represent any non-negative value of X::difference_type + EXPECT_TRUE(static_cast(std::numeric_limits::max()) <= + std::numeric_limits::max()); + + // the expression "X u" has the post-condition "u.empty()" + { + json u; + EXPECT_TRUE(u.empty()); + } + + // the expression "X()" has the post-condition "X().empty()" + EXPECT_TRUE(json().empty()); +} + +TEST(JsonConceptsTest, DefaultConstructible) +{ + EXPECT_TRUE(std::is_nothrow_default_constructible::value); +} + +TEST(JsonConceptsTest, MoveConstructible) +{ + EXPECT_TRUE(std::is_nothrow_move_constructible::value); +} + +TEST(JsonConceptsTest, CopyConstructible) +{ + EXPECT_TRUE(std::is_copy_constructible::value); +} + +TEST(JsonConceptsTest, MoveAssignable) +{ + EXPECT_TRUE(std::is_nothrow_move_assignable::value); +} + +TEST(JsonConceptsTest, CopyAssignable) +{ + EXPECT_TRUE(std::is_copy_assignable::value); +} + +TEST(JsonConceptsTest, Destructible) +{ + EXPECT_TRUE(std::is_nothrow_destructible::value); +} + +TEST(JsonConceptsTest, StandardLayoutType) +{ + EXPECT_TRUE(std::is_standard_layout::value); +} + +TEST(JsonIteratorConceptsTest, CopyConstructible) +{ + EXPECT_TRUE(std::is_nothrow_copy_constructible::value); + EXPECT_TRUE(std::is_nothrow_copy_constructible::value); +} + +TEST(JsonIteratorConceptsTest, CopyAssignable) +{ + // STL iterators used by json::iterator don't pass this test in Debug mode +#if !defined(_MSC_VER) || (_ITERATOR_DEBUG_LEVEL == 0) + EXPECT_TRUE(std::is_nothrow_copy_assignable::value); + EXPECT_TRUE(std::is_nothrow_copy_assignable::value); +#endif +} + +TEST(JsonIteratorConceptsTest, Destructible) +{ + EXPECT_TRUE(std::is_nothrow_destructible::value); + EXPECT_TRUE(std::is_nothrow_destructible::value); +} + +TEST(JsonIteratorConceptsTest, Swappable) +{ + json j {1, 2, 3}; + json::iterator it1 = j.begin(); + json::iterator it2 = j.end(); + std::swap(it1, it2); + EXPECT_EQ(it1, j.end()); + EXPECT_EQ(it2, j.begin()); +} + +TEST(JsonIteratorConceptsTest, SwappableConst) +{ + json j {1, 2, 3}; + json::const_iterator it1 = j.cbegin(); + json::const_iterator it2 = j.cend(); + std::swap(it1, it2); + EXPECT_EQ(it1, j.end()); + EXPECT_EQ(it2, j.begin()); +} diff --git a/src/test/native/cpp/json/unit-constructor1.cpp b/src/test/native/cpp/json/unit-constructor1.cpp new file mode 100644 index 0000000000..5b67976955 --- /dev/null +++ b/src/test/native/cpp/json/unit-constructor1.cpp @@ -0,0 +1,1071 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "unit-json.h" +using wpi::json; +using wpi::JsonTest; + +class JsonConstructTypeTest : public ::testing::TestWithParam {}; +TEST_P(JsonConstructTypeTest, Case) +{ + auto t = GetParam(); + json j(t); + EXPECT_EQ(j.type(), t); +} + +static const json::value_t construct_type_cases[] = { + json::value_t::null, + json::value_t::discarded, + json::value_t::object, + json::value_t::array, + json::value_t::boolean, + json::value_t::string, + json::value_t::number_integer, + json::value_t::number_unsigned, + json::value_t::number_float, +}; + +INSTANTIATE_TEST_CASE_P(JsonConstructTypeTests, JsonConstructTypeTest, + ::testing::ValuesIn(construct_type_cases)); + + +TEST(JsonConstructNullTest, NoParameter) +{ + json j{}; + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonConstructNullTest, Parameter) +{ + json j(nullptr); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonConstructObjectExplicitTest, Empty) +{ + json::object_t o; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); +} + +TEST(JsonConstructObjectExplicitTest, Filled) +{ + json::object_t o {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); +} + +class JsonConstructObjectImplicitTest : public ::testing::Test { + public: + JsonConstructObjectImplicitTest() : j_reference(o_reference) {} + + protected: + json::object_t o_reference {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j_reference; +}; + +// std::map +TEST_F(JsonConstructObjectImplicitTest, StdMapStringJson) +{ + std::map o {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j, j_reference); +} + +// std::pair +TEST_F(JsonConstructObjectImplicitTest, StdPairStringT) +{ + std::pair p{"first", "second"}; + json j(p); + + EXPECT_EQ(j.get(), p); + + std::pair p2{"first", 1}; + // use char const* + json j2(std::make_pair("first", 1)); + + EXPECT_EQ(j2.get(), p2); +} + +// std::map +TEST_F(JsonConstructObjectImplicitTest, StdMapStringString) +{ + std::map m; + m["a"] = "b"; + m["c"] = "d"; + m["e"] = "f"; + + json j(m); + EXPECT_EQ(j.get(), m); +} + +// std::map +TEST_F(JsonConstructObjectImplicitTest, StdMapCharPointerJson) +{ + std::map o {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j, j_reference); +} + +// std::multimap +TEST_F(JsonConstructObjectImplicitTest, StdMultiMapStringJson) +{ + std::multimap o {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j, j_reference); +} + +// std::unordered_map +TEST_F(JsonConstructObjectImplicitTest, StdUnorderedMapStringJson) +{ + std::unordered_map o {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j, j_reference); +} + +// std::unordered_multimap +TEST_F(JsonConstructObjectImplicitTest, StdUnorderedMultiMapStringJson) +{ + std::unordered_multimap o {{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}; + json j(o); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j, j_reference); +} + +// associative container literal +TEST_F(JsonConstructObjectImplicitTest, AssociativeContainerLiteral) +{ + json j({{"a", json(1)}, {"b", json(1u)}, {"c", json(2.2)}, {"d", json(false)}, {"e", json("string")}, {"f", json()}}); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j, j_reference); +} + +TEST(JsonConstructArrayExplicitTest, Empty) +{ + json::array_t a; + json j(a); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructArrayExplicitTest, Filled) +{ + json::array_t a {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j(a); + EXPECT_EQ(j.type(), json::value_t::array); +} + +template +class JsonConstructArrayTest : public ::testing::Test { + public: + JsonConstructArrayTest() : j_reference(a_reference) {} + + protected: + json::array_t a_reference {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j_reference; +}; + +typedef ::testing::Types, std::forward_list, + std::array, std::vector, + std::deque> + JsonConstructArrayTestTypes; +TYPED_TEST_CASE(JsonConstructArrayTest, JsonConstructArrayTestTypes); + +// clang warns on missing braces on the TypeParam initializer line below. +// Suppress this warning. +#if defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-braces" +#endif +TYPED_TEST(JsonConstructArrayTest, Implicit) +{ + TypeParam a {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j(a); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, this->j_reference); +} +#if defined(__clang__) +#pragma GCC diagnostic pop +#endif + +// std::set +TEST(JsonConstructArraySetTest, StdSet) +{ + std::set a {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j(a); + EXPECT_EQ(j.type(), json::value_t::array); + // we cannot really check for equality here +} + +// std::unordered_set +TEST(JsonConstructArraySetTest, StdUnorderedSet) +{ + std::unordered_set a {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j(a); + EXPECT_EQ(j.type(), json::value_t::array); + // we cannot really check for equality here +} + +// sequence container literal +TEST(JsonConstructArrayContainerTest, Case) +{ + json::array_t a_reference {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j_reference(a_reference); + + json j({json(1), json(1u), json(2.2), json(false), json("string"), json()}); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, j_reference); +} + +TEST(JsonConstructStringExplicitTest, Empty) +{ + json::string_t s; + json j(s); + EXPECT_EQ(j.type(), json::value_t::string); +} + +TEST(JsonConstructStringExplicitTest, Filled) +{ + json::string_t s {"Hello world"}; + json j(s); + EXPECT_EQ(j.type(), json::value_t::string); +} + +class JsonConstructStringTest : public ::testing::Test { + public: + JsonConstructStringTest() : j_reference(s_reference) {} + + protected: + json::string_t s_reference {"Hello world"}; + json j_reference; +}; + +// std::string +TEST_F(JsonConstructStringTest, StdString) +{ + std::string s {"Hello world"}; + json j(s); + EXPECT_EQ(j.type(), json::value_t::string); + EXPECT_EQ(j, j_reference); +} + +// char[] +TEST_F(JsonConstructStringTest, CharArray) +{ + char s[] {"Hello world"}; + json j(s); + EXPECT_EQ(j.type(), json::value_t::string); + EXPECT_EQ(j, j_reference); +} + +// const char* +TEST_F(JsonConstructStringTest, ConstCharPointer) +{ + const char* s {"Hello world"}; + json j(s); + EXPECT_EQ(j.type(), json::value_t::string); + EXPECT_EQ(j, j_reference); +} + +// string literal +TEST_F(JsonConstructStringTest, StringLiteral) +{ + json j("Hello world"); + EXPECT_EQ(j.type(), json::value_t::string); + EXPECT_EQ(j, j_reference); +} + +TEST(JsonConstructBooleanExplicitTest, Empty) +{ + json::boolean_t b{}; + json j(b); + EXPECT_EQ(j.type(), json::value_t::boolean); +} + +TEST(JsonConstructBooleanExplicitTest, True) +{ + json j(true); + EXPECT_EQ(j.type(), json::value_t::boolean); +} + +TEST(JsonConstructBooleanExplicitTest, False) +{ + json j(false); + EXPECT_EQ(j.type(), json::value_t::boolean); +} + +TEST(JsonConstructIntegerExplicitTest, Uninitialized) +{ + json::number_integer_t n{}; + json j(n); + EXPECT_EQ(j.type(), json::value_t::number_integer); +} + +TEST(JsonConstructIntegerExplicitTest, Initialized) +{ + json::number_integer_t n(42); + json j(n); + EXPECT_EQ(j.type(), json::value_t::number_integer); +} + +template +class JsonConstructIntegerTest : public ::testing::Test { + public: + JsonConstructIntegerTest() + : j_reference(n_reference), j_unsigned_reference(n_unsigned_reference) {} + + protected: + json::number_integer_t n_reference = 42; + json j_reference; + json::number_unsigned_t n_unsigned_reference = 42u; + json j_unsigned_reference; +}; + +typedef ::testing::Types< + short + , unsigned short + , int + , unsigned int + , long + , unsigned long + , long long + , unsigned long long + , int8_t + , int16_t + , int32_t + , int64_t +#if 0 + , int8_fast_t + , int16_fast_t + , int32_fast_t + , int64_fast_t + , int8_least_t + , int16_least_t + , int32_least_t + , int64_least_t +#endif + , uint8_t + , uint16_t + , uint32_t + , uint64_t +#if 0 + , uint8_fast_t + , uint16_fast_t + , uint32_fast_t + , uint64_fast_t + , uint8_least_t + , uint16_least_t + , uint32_least_t + , uint64_least_t +#endif + > JsonConstructIntegerTestTypes; + +TYPED_TEST_CASE(JsonConstructIntegerTest, JsonConstructIntegerTestTypes); + +TYPED_TEST(JsonConstructIntegerTest, Implicit) +{ + TypeParam n = 42; + json j(n); + if (std::is_unsigned::value) + { + EXPECT_EQ(j.type(), json::value_t::number_unsigned); + EXPECT_EQ(j, this->j_unsigned_reference); + } + else + { + EXPECT_EQ(j.type(), json::value_t::number_integer); + EXPECT_EQ(j, this->j_reference); + } +} + +class JsonConstructIntegerLiteralTest : public ::testing::Test { + public: + JsonConstructIntegerLiteralTest() + : j_reference(n_reference), j_unsigned_reference(n_unsigned_reference) {} + + protected: + json::number_integer_t n_reference = 42; + json j_reference; + json::number_unsigned_t n_unsigned_reference = 42u; + json j_unsigned_reference; +}; + +TEST_F(JsonConstructIntegerLiteralTest, None) +{ + json j(42); + EXPECT_EQ(j.type(), json::value_t::number_integer); + EXPECT_EQ(j, j_reference); +} + +TEST_F(JsonConstructIntegerLiteralTest, U) +{ + json j(42u); + EXPECT_EQ(j.type(), json::value_t::number_unsigned); + EXPECT_EQ(j, j_unsigned_reference); +} + +TEST_F(JsonConstructIntegerLiteralTest, L) +{ + json j(42l); + EXPECT_EQ(j.type(), json::value_t::number_integer); + EXPECT_EQ(j, j_reference); +} + +TEST_F(JsonConstructIntegerLiteralTest, UL) +{ + json j(42ul); + EXPECT_EQ(j.type(), json::value_t::number_unsigned); + EXPECT_EQ(j, j_unsigned_reference); +} + +TEST_F(JsonConstructIntegerLiteralTest, LL) +{ + json j(42ll); + EXPECT_EQ(j.type(), json::value_t::number_integer); + EXPECT_EQ(j, j_reference); +} + +TEST_F(JsonConstructIntegerLiteralTest, ULL) +{ + json j(42ull); + EXPECT_EQ(j.type(), json::value_t::number_unsigned); + EXPECT_EQ(j, j_unsigned_reference); +} + +TEST(JsonConstructFloatExplicitTest, Uninitialized) +{ + json::number_float_t n{}; + json j(n); + EXPECT_EQ(j.type(), json::value_t::number_float); +} + +TEST(JsonConstructFloatExplicitTest, Initialized) +{ + json::number_float_t n(42.23); + json j(n); + EXPECT_EQ(j.type(), json::value_t::number_float); +} + +TEST(JsonConstructFloatExplicitTest, Infinity) +{ + // infinity is stored properly, but serialized to null + json::number_float_t n(std::numeric_limits::infinity()); + json j(n); + EXPECT_EQ(j.type(), json::value_t::number_float); + + // check round trip of infinity + json::number_float_t d = j; + EXPECT_EQ(d, n); + + // check that inf is serialized to null + EXPECT_EQ(j.dump(), "null"); +} + +template +class JsonConstructFloatTest : public ::testing::Test { + public: + JsonConstructFloatTest() : j_reference(n_reference) {} + + protected: + json::number_float_t n_reference {42.23}; + json j_reference; +}; + +typedef ::testing::Types + JsonConstructFloatTestTypes; + +TYPED_TEST_CASE(JsonConstructFloatTest, JsonConstructFloatTestTypes); + +TYPED_TEST(JsonConstructFloatTest, Implicit) +{ + TypeParam n = 42.23f; + json j(n); + EXPECT_EQ(j.type(), json::value_t::number_float); + EXPECT_LT(std::fabs(JsonTest::GetValue(j).number_float - + JsonTest::GetValue(this->j_reference).number_float), + 0.001); +} + +class JsonConstructFloatLiteralTest : public ::testing::Test { + public: + JsonConstructFloatLiteralTest() : j_reference(n_reference) {} + + protected: + json::number_float_t n_reference {42.23}; + json j_reference; +}; + +TEST_F(JsonConstructFloatLiteralTest, None) +{ + json j(42.23); + EXPECT_EQ(j.type(), json::value_t::number_float); + EXPECT_LT(std::fabs(JsonTest::GetValue(j).number_float - + JsonTest::GetValue(this->j_reference).number_float), + 0.001); +} + +TEST_F(JsonConstructFloatLiteralTest, F) +{ + json j(42.23f); + EXPECT_EQ(j.type(), json::value_t::number_float); + EXPECT_LT(std::fabs(JsonTest::GetValue(j).number_float - + JsonTest::GetValue(this->j_reference).number_float), + 0.001); +} + +#if 0 +TEST_F(JsonConstructFloatLiteralTest, L) +{ + json j(42.23l); + EXPECT_EQ(j.type(), json::value_t::number_float); + EXPECT_LT(std::fabs(JsonTest::GetValue(j).number_float - + JsonTest::GetValue(this->j_reference).number_float), + 0.001); +} +#endif + +TEST(JsonConstructInitializerEmptyTest, Explicit) +{ + std::initializer_list l; + json j(l); + EXPECT_EQ(j.type(), json::value_t::object); +} + +TEST(JsonConstructInitializerEmptyTest, Implicit) +{ + json j {}; + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonConstructInitializerOneTest, ExplicitArray) +{ + std::initializer_list l = {json(json::array_t())}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitArray) +{ + json j {json::array_t()}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ExplicitObject) +{ + std::initializer_list l = {json(json::object_t())}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitObject) +{ + json j {json::object_t()}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ExplicitString) +{ + std::initializer_list l = {json("Hello world")}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitString) +{ + json j {"Hello world"}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ExplicitBoolean) +{ + std::initializer_list l = {json(true)}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitBoolean) +{ + json j {true}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ExplicitInteger) +{ + std::initializer_list l = {json(1)}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitInteger) +{ + json j {1}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ExplicitUnsigned) +{ + std::initializer_list l = {json(1u)}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitUnsigned) +{ + json j {1u}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ExplicitFloat) +{ + std::initializer_list l = {json(42.23)}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerOneTest, ImplicitFloat) +{ + json j {42.23}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerManyTest, Explicit) +{ + std::initializer_list l = {1, 1u, 42.23, true, nullptr, json::object_t(), json::array_t()}; + json j(l); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerManyTest, Implicit) +{ + json j {1, 1u, 42.23, true, nullptr, json::object_t(), json::array_t()}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerImplicitTest, Object) +{ + json j { {"one", 1}, {"two", 1u}, {"three", 2.2}, {"four", false} }; + EXPECT_EQ(j.type(), json::value_t::object); +} + +TEST(JsonConstructInitializerImplicitTest, Array) +{ + json j { {"one", 1}, {"two", 1u}, {"three", 2.2}, {"four", false}, 13 }; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerExplicitTest, EmptyObject) +{ + json j = json::object(); + EXPECT_EQ(j.type(), json::value_t::object); +} + +TEST(JsonConstructInitializerExplicitTest, Object) +{ + json j = json::object({ {"one", 1}, {"two", 1u}, {"three", 2.2}, {"four", false} }); + EXPECT_EQ(j.type(), json::value_t::object); +} + +TEST(JsonConstructInitializerExplicitTest, ObjectError) +{ + EXPECT_THROW_MSG(json::object({ {"one", 1}, {"two", 1u}, {"three", 2.2}, {"four", false}, 13 }), + json::type_error, + "[json.exception.type_error.301] cannot create object from initializer list"); +} + +// std::pair with error +TEST(JsonConstructInitializerPairErrorTest, WrongFieldNumber) +{ + json j{{"too", "much"}, {"string", "fields"}}; + EXPECT_THROW_MSG((j.get>()), json::other_error, + "[json.exception.other_error.502] conversion " + "to std::pair requires the object to have " + "exactly one field, but it has 2"); +} + +TEST(JsonConstructInitializerPairErrorTest, WrongJsonType) +{ + json j(42); + EXPECT_THROW_MSG((j.get>()), json::type_error, + "[json.exception.type_error.302] type must be object, but is number"); +} + +TEST(JsonConstructInitializerTest, EmptyArray) +{ + json j = json::array(); + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConstructInitializerTest, Array) +{ + json j = json::array({ {"one", 1}, {"two", 1u}, {"three", 2.2}, {"four", false} }); + EXPECT_EQ(j.type(), json::value_t::array); +} + +// create an array of n copies of a given value +TEST(JsonConstructArrayCopyTest, Case) +{ + json v = {1, "foo", 34.23, {1, 2, 3}, {{"A", 1}, {"B", 2u}}}; + json arr(3, v); + EXPECT_EQ(arr.size(), 3u); + for (auto& x : arr) + { + EXPECT_EQ(x, v); + } +} + +// create a JSON container from an iterator range +TEST(JsonConstructIteratorTest, ObjectBeginEnd) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json j_new(jobject.begin(), jobject.end()); + EXPECT_EQ(j_new, jobject); +#else + EXPECT_THROW(json(jobject.begin(), jobject.end()), json::invalid_iterator); +#endif +} + +TEST(JsonConstructIteratorTest, ObjectBeginEndConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json j_new(jobject.cbegin(), jobject.cend()); + EXPECT_EQ(j_new, jobject); +#else + EXPECT_THROW(json(jobject.cbegin(), jobject.cend()), json::invalid_iterator); +#endif +} + +TEST(JsonConstructIteratorTest, ObjectBeginBegin) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json j_new(jobject.begin(), jobject.begin()); + EXPECT_EQ(j_new, json::object()); +#else + EXPECT_THROW(json(jobject.begin(), jobject.end()), json::invalid_iterator); +#endif +} + +TEST(JsonConstructIteratorTest, ObjectBeginBeginConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json j_new(jobject.cbegin(), jobject.cbegin()); + EXPECT_EQ(j_new, json::object()); +#else + EXPECT_THROW(json(jobject.cbegin(), jobject.cend()), json::invalid_iterator); +#endif +} +#if 0 +TEST(JsonConstructIteratorTest, ObjectSubrange) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; + json j_new(jobject.find("b"), jobject.find("e")); + EXPECT_EQ(j_new, json({{"b", 1}, {"c", 17u}, {"d", false}})); +} +#endif +TEST(JsonConstructIteratorTest, ObjectIncompatibleIterators) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; + json jobject2 = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + EXPECT_THROW_MSG(json(jobject.begin(), jobject2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); + EXPECT_THROW_MSG(json(jobject2.begin(), jobject.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); +} + +TEST(JsonConstructIteratorTest, ObjectIncompatibleIteratorsConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; + json jobject2 = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + EXPECT_THROW_MSG(json(jobject.cbegin(), jobject2.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); + EXPECT_THROW_MSG(json(jobject2.cbegin(), jobject.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); +} + +TEST(JsonConstructIteratorTest, ArrayBeginEnd) +{ + json jarray = {1, 2, 3, 4, 5}; + json j_new(jarray.begin(), jarray.end()); + EXPECT_EQ(j_new, jarray); +} + +TEST(JsonConstructIteratorTest, ArrayBeginEndConst) +{ + json jarray = {1, 2, 3, 4, 5}; + json j_new(jarray.cbegin(), jarray.cend()); + EXPECT_EQ(j_new, jarray); +} + +TEST(JsonConstructIteratorTest, ArrayBeginBegin) +{ + json jarray = {1, 2, 3, 4, 5}; + json j_new(jarray.begin(), jarray.begin()); + EXPECT_EQ(j_new, json::array()); +} + +TEST(JsonConstructIteratorTest, ArrayBeginBeginConst) +{ + json jarray = {1, 2, 3, 4, 5}; + json j_new(jarray.cbegin(), jarray.cbegin()); + EXPECT_EQ(j_new, json::array()); +} + +TEST(JsonConstructIteratorTest, ArraySubrange) +{ + json jarray = {1, 2, 3, 4, 5}; + json j_new(jarray.begin() + 1, jarray.begin() + 3); + EXPECT_EQ(j_new, json({2, 3})); +} + +TEST(JsonConstructIteratorTest, ArraySubrangeConst) +{ + json jarray = {1, 2, 3, 4, 5}; + json j_new(jarray.cbegin() + 1, jarray.cbegin() + 3); + EXPECT_EQ(j_new, json({2, 3})); +} + +TEST(JsonConstructIteratorTest, ArrayIncompatibleIterators) +{ + json jarray = {1, 2, 3, 4}; + json jarray2 = {2, 3, 4, 5}; + EXPECT_THROW_MSG(json(jarray.begin(), jarray2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); + EXPECT_THROW_MSG(json(jarray2.begin(), jarray.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); +} + +TEST(JsonConstructIteratorTest, ArrayIncompatibleIteratorsConst) +{ + json jarray = {1, 2, 3, 4}; + json jarray2 = {2, 3, 4, 5}; + EXPECT_THROW_MSG(json(jarray.cbegin(), jarray2.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); + EXPECT_THROW_MSG(json(jarray2.cbegin(), jarray.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.201] iterators are not compatible"); +} + +TEST(JsonConstructTwoValidIteratorTest, Null) +{ + json j; + EXPECT_THROW_MSG(json(j.begin(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.206] cannot construct with iterators from null"); +} + +TEST(JsonConstructTwoValidIteratorTest, NullConst) +{ + json j; + EXPECT_THROW_MSG(json(j.cbegin(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.206] cannot construct with iterators from null"); +} + +TEST(JsonConstructTwoValidIteratorTest, String) +{ + json j = "foo"; + json j_new(j.begin(), j.end()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, StringConst) +{ + json j = "bar"; + json j_new(j.cbegin(), j.cend()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, Boolean) +{ + json j = false; + json j_new(j.begin(), j.end()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, BooleanConst) +{ + json j = true; + json j_new(j.cbegin(), j.cend()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, Integer) +{ + json j = 17; + json j_new(j.begin(), j.end()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, IntegerConst) +{ + json j = 17; + json j_new(j.cbegin(), j.cend()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, Unsigned) +{ + json j = 17u; + json j_new(j.begin(), j.end()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, UnsignedConst) +{ + json j = 17u; + json j_new(j.cbegin(), j.cend()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, Float) +{ + json j = 23.42; + json j_new(j.begin(), j.end()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoValidIteratorTest, FloatConst) +{ + json j = 23.42; + json j_new(j.cbegin(), j.cend()); + EXPECT_EQ(j, j_new); +} + +TEST(JsonConstructTwoInvalidIteratorTest, String) +{ + json j = "foo"; + EXPECT_THROW_MSG(json(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, StringConst) +{ + json j = "bar"; + EXPECT_THROW_MSG(json(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, Boolean) +{ + json j = false; + EXPECT_THROW_MSG(json(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, BooleanConst) +{ + json j = true; + EXPECT_THROW_MSG(json(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, Integer) +{ + json j = 17; + EXPECT_THROW_MSG(json(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, IntegerConst) +{ + json j = 17; + EXPECT_THROW_MSG(json(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, Unsigned) +{ + json j = 17u; + EXPECT_THROW_MSG(json(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, UnsignedConst) +{ + json j = 17u; + EXPECT_THROW_MSG(json(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, Float) +{ + json j = 23.42; + EXPECT_THROW_MSG(json(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonConstructTwoInvalidIteratorTest, FloatConst) +{ + json j = 23.42; + EXPECT_THROW_MSG(json(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(json(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} diff --git a/src/test/native/cpp/json/unit-constructor2.cpp b/src/test/native/cpp/json/unit-constructor2.cpp new file mode 100644 index 0000000000..39f1301546 --- /dev/null +++ b/src/test/native/cpp/json/unit-constructor2.cpp @@ -0,0 +1,185 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonCopyConstructorTest, Object) +{ + json j {{"foo", 1}, {"bar", false}}; + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, Array) +{ + json j {"foo", 1, 42.23, false}; + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, Null) +{ + json j(nullptr); + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, Boolean) +{ + json j(true); + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, String) +{ + json j("Hello world"); + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, Integer) +{ + json j(42); + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, Unsigned) +{ + json j(42u); + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonCopyConstructorTest, Float) +{ + json j(42.23); + json k(j); + EXPECT_EQ(j, k); +} + +TEST(JsonMoveConstructorTest, Case) +{ + json j {{"foo", "bar"}, {"baz", {1, 2, 3, 4}}, {"a", 42u}, {"b", 42.23}, {"c", nullptr}}; + EXPECT_EQ(j.type(), json::value_t::object); + json k(std::move(j)); + EXPECT_EQ(k.type(), json::value_t::object); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonCopyAssignmentTest, Object) +{ + json j {{"foo", 1}, {"bar", false}}; + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, Array) +{ + json j {"foo", 1, 42.23, false}; + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, Null) +{ + json j(nullptr); + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, Boolean) +{ + json j(true); + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, String) +{ + json j("Hello world"); + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, Integer) +{ + json j(42); + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, Unsigned) +{ + json j(42u); + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonCopyAssignmentTest, Float) +{ + json j(42.23); + json k; + k = j; + EXPECT_EQ(j, k); +} + +TEST(JsonDestructorTest, Object) +{ + auto j = new json {{"foo", 1}, {"bar", false}}; + delete j; +} + +TEST(JsonDestructorTest, Array) +{ + auto j = new json {"foo", 1, 1u, false, 23.42}; + delete j; +} + +TEST(JsonDestructorTest, String) +{ + auto j = new json("Hello world"); + delete j; +} diff --git a/src/test/native/cpp/json/unit-convenience.cpp b/src/test/native/cpp/json/unit-convenience.cpp new file mode 100644 index 0000000000..51646f9838 --- /dev/null +++ b/src/test/native/cpp/json/unit-convenience.cpp @@ -0,0 +1,121 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "llvm/SmallString.h" + +#include "unit-json.h" + +#include "support/json_serializer.h" + +using wpi::json; + +class JsonTypeNameTest + : public ::testing::TestWithParam> {}; +TEST_P(JsonTypeNameTest, Case) +{ + EXPECT_EQ(json(GetParam().first).type_name(), GetParam().second); +} + +static const std::pair type_name_cases[] = { + {json::value_t::null, "null"}, + {json::value_t::object, "object"}, + {json::value_t::array, "array"}, + {json::value_t::number_integer, "number"}, + {json::value_t::number_unsigned, "number"}, + {json::value_t::number_float, "number"}, + {json::value_t::boolean, "boolean"}, + {json::value_t::string, "string"}, + {json::value_t::discarded, "discarded"}, +}; + +INSTANTIATE_TEST_CASE_P(JsonTypeNameTests, JsonTypeNameTest, + ::testing::ValuesIn(type_name_cases)); + +class JsonStringEscapeTest + : public ::testing::TestWithParam> {}; +TEST_P(JsonStringEscapeTest, Case) +{ + llvm::SmallString<32> buf; + llvm::raw_svector_ostream ss(buf); + json::serializer s(ss); + s.dump_escaped(GetParam().first); + EXPECT_EQ(ss.str(), llvm::StringRef(GetParam().second)); +} + +static const std::pair string_escape_cases[] = { + {"\"", "\\\""}, + {"\\", "\\\\"}, + {"\b", "\\b"}, + {"\f", "\\f"}, + {"\n", "\\n"}, + {"\r", "\\r"}, + {"\t", "\\t"}, + + {"\x01", "\\u0001"}, + {"\x02", "\\u0002"}, + {"\x03", "\\u0003"}, + {"\x04", "\\u0004"}, + {"\x05", "\\u0005"}, + {"\x06", "\\u0006"}, + {"\x07", "\\u0007"}, + {"\x08", "\\b"}, + {"\x09", "\\t"}, + {"\x0a", "\\n"}, + {"\x0b", "\\u000b"}, + {"\x0c", "\\f"}, + {"\x0d", "\\r"}, + {"\x0e", "\\u000e"}, + {"\x0f", "\\u000f"}, + {"\x10", "\\u0010"}, + {"\x11", "\\u0011"}, + {"\x12", "\\u0012"}, + {"\x13", "\\u0013"}, + {"\x14", "\\u0014"}, + {"\x15", "\\u0015"}, + {"\x16", "\\u0016"}, + {"\x17", "\\u0017"}, + {"\x18", "\\u0018"}, + {"\x19", "\\u0019"}, + {"\x1a", "\\u001a"}, + {"\x1b", "\\u001b"}, + {"\x1c", "\\u001c"}, + {"\x1d", "\\u001d"}, + {"\x1e", "\\u001e"}, + {"\x1f", "\\u001f"}, +}; + +INSTANTIATE_TEST_CASE_P(JsonStringEscapeTests, JsonStringEscapeTest, + ::testing::ValuesIn(string_escape_cases)); diff --git a/src/test/native/cpp/json/unit-conversions.cpp b/src/test/native/cpp/json/unit-conversions.cpp new file mode 100644 index 0000000000..08c04f4e78 --- /dev/null +++ b/src/test/native/cpp/json/unit-conversions.cpp @@ -0,0 +1,560 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; +using wpi::JsonTest; + +#include +//#include +#include +#include +#include +#include + +template +class JsonGetObjectTest : public ::testing::Test { + public: + JsonGetObjectTest() : j(o_reference) {} + + protected: + json::object_t o_reference = {{"object", json::object()}, {"array", {1, 2, 3, 4}}, {"number", 42}, {"boolean", false}, {"null", nullptr}, {"string", "Hello world"} }; + json j; +}; + +typedef ::testing::Types< + json::object_t + , std::map + , std::multimap + , std::unordered_map + , std::unordered_multimap + > JsonGetObjectTestTypes; +TYPED_TEST_CASE(JsonGetObjectTest, JsonGetObjectTestTypes); + +TYPED_TEST(JsonGetObjectTest, Explicit) +{ + TypeParam o = (this->j).template get(); + EXPECT_EQ(json(o), this->j); +} + +TYPED_TEST(JsonGetObjectTest, Implicit) +{ + TypeParam o = this->j; + EXPECT_EQ(json(o), this->j); +} + +// exception in case of a non-object type +TEST(JsonGetObjectExceptionTest, TypeError) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is null"); + EXPECT_THROW_MSG(json(json::value_t::array).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is array"); + EXPECT_THROW_MSG(json(json::value_t::string).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is string"); + EXPECT_THROW_MSG(json(json::value_t::boolean).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is boolean"); + EXPECT_THROW_MSG(json(json::value_t::number_integer).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_unsigned).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_float).get(), json::type_error, + "[json.exception.type_error.302] type must be object, but is number"); +} + +template +class JsonGetArrayTest : public ::testing::Test { + public: + JsonGetArrayTest() : j(a_reference) {} + + protected: + json::array_t a_reference {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j; +}; + +typedef ::testing::Types, + /*std::forward_list,*/ std::vector, + std::deque> + JsonGetArrayTestTypes; +TYPED_TEST_CASE(JsonGetArrayTest, JsonGetArrayTestTypes); + +TYPED_TEST(JsonGetArrayTest, Explicit) +{ + TypeParam a = (this->j).template get(); + EXPECT_EQ(json(a), this->j); +} + +TYPED_TEST(JsonGetArrayTest, Implicit) +{ + TypeParam a = this->j; + EXPECT_EQ(json(a), this->j); +} + +#if !defined(JSON_NOEXCEPTION) +// reserve is called on containers that supports it +TEST(JsonGetArrayAdditionalTest, ExplicitStdVectorReserve) +{ + json::array_t a_reference {json(1), json(1u), json(2.2), json(false), json("string"), json()}; + json j(a_reference); + + // making the call to from_json throw in order to check capacity + std::vector v; + EXPECT_THROW(wpi::from_json(j, v), json::type_error); + EXPECT_EQ(v.capacity(), j.size()); + + // make sure all values are properly copied + std::vector v2 = json({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + EXPECT_EQ(v2.size(), 10u); +} +#endif + +// built-in arrays +TEST(JsonGetArrayAdditionalTest, ExplicitBuiltinArray) +{ + const char str[] = "a string"; + const int nbs[] = {0, 1, 2}; + + json j2 = nbs; + json j3 = str; + + auto v = j2.get>(); + auto s = j3.get(); + EXPECT_TRUE(std::equal(v.begin(), v.end(), std::begin(nbs))); + EXPECT_EQ(s, str); +} +#if 0 +TEST(JsonGetArrayExceptionTest, ForwardList) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get>(), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); +} +#endif +TEST(JsonGetArrayExceptionTest, StdVector) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get>(), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); +} + +// exception in case of a non-array type +TEST(JsonGetArrayExceptionTest, TypeError) +{ + EXPECT_THROW_MSG(json(json::value_t::object).get>(), json::type_error, + "[json.exception.type_error.302] type must be array, but is object"); + EXPECT_THROW_MSG(json(json::value_t::null).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); + EXPECT_THROW_MSG(json(json::value_t::object).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is object"); + EXPECT_THROW_MSG(json(json::value_t::string).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is string"); + EXPECT_THROW_MSG(json(json::value_t::boolean).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is boolean"); + EXPECT_THROW_MSG(json(json::value_t::number_integer).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_unsigned).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_float).get(), json::type_error, + "[json.exception.type_error.302] type must be array, but is number"); +} + +template +class JsonGetStringTest : public ::testing::Test { + public: + JsonGetStringTest() : j(s_reference) {} + + protected: + json::string_t s_reference {"Hello world"}; + json j; +}; + +typedef ::testing::Types JsonGetStringTestTypes; +TYPED_TEST_CASE(JsonGetStringTest, JsonGetStringTestTypes); + +TYPED_TEST(JsonGetStringTest, Explicit) +{ + TypeParam s = (this->j).template get(); + EXPECT_EQ(json(s), this->j); +} + +TYPED_TEST(JsonGetStringTest, Implicit) +{ + TypeParam s = this->j; + EXPECT_EQ(json(s), this->j); +} + +// exception in case of a non-string type +TEST(JsonGetStringExceptionTest, TypeError) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is null"); + EXPECT_THROW_MSG(json(json::value_t::object).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is object"); + EXPECT_THROW_MSG(json(json::value_t::array).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is array"); + EXPECT_THROW_MSG(json(json::value_t::boolean).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is boolean"); + EXPECT_THROW_MSG(json(json::value_t::number_integer).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_unsigned).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_float).get(), json::type_error, + "[json.exception.type_error.302] type must be string, but is number"); +} + +template +class JsonGetBooleanTest : public ::testing::Test { + public: + JsonGetBooleanTest() : j(b_reference) {} + + protected: + json::boolean_t b_reference {true}; + json j; +}; + +typedef ::testing::Types JsonGetBooleanTestTypes; +TYPED_TEST_CASE(JsonGetBooleanTest, JsonGetBooleanTestTypes); + +TYPED_TEST(JsonGetBooleanTest, Explicit) +{ + TypeParam b = (this->j).template get(); + EXPECT_EQ(json(b), this->j); +} + +TYPED_TEST(JsonGetBooleanTest, Implicit) +{ + TypeParam b = this->j; + EXPECT_EQ(json(b), this->j); +} + +// exception in case of a non-string type +TEST(JsonGetBooleanExceptionTest, TypeError) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is null"); + EXPECT_THROW_MSG(json(json::value_t::object).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is object"); + EXPECT_THROW_MSG(json(json::value_t::array).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is array"); + EXPECT_THROW_MSG(json(json::value_t::string).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is string"); + EXPECT_THROW_MSG(json(json::value_t::number_integer).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_unsigned).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is number"); + EXPECT_THROW_MSG(json(json::value_t::number_float).get(), json::type_error, + "[json.exception.type_error.302] type must be boolean, but is number"); +} + +template +class JsonGetIntegerTest : public ::testing::Test { + public: + JsonGetIntegerTest() : j(n_reference), j_unsigned(n_unsigned_reference) {} + + protected: + json::number_integer_t n_reference {42}; + json j; + json::number_unsigned_t n_unsigned_reference {42u}; + json j_unsigned; +}; + +typedef ::testing::Types< + short + , unsigned short + , int + , unsigned int + , long + , unsigned long + , long long + , unsigned long long + , int8_t + , int16_t + , int32_t + , int64_t +#if 0 + , int8_fast_t + , int16_fast_t + , int32_fast_t + , int64_fast_t + , int8_least_t + , int16_least_t + , int32_least_t + , int64_least_t +#endif + , uint8_t + , uint16_t + , uint32_t + , uint64_t +#if 0 + , uint8_fast_t + , uint16_fast_t + , uint32_fast_t + , uint64_fast_t + , uint8_least_t + , uint16_least_t + , uint32_least_t + , uint64_least_t +#endif + > JsonGetIntegerTestTypes; + +TYPED_TEST_CASE(JsonGetIntegerTest, JsonGetIntegerTestTypes); + +TYPED_TEST(JsonGetIntegerTest, Explicit) +{ + TypeParam n = (this->j).template get(); + EXPECT_EQ(json(n), this->j); +} + +TYPED_TEST(JsonGetIntegerTest, Implicit) +{ + if (std::is_unsigned::value) + { + TypeParam n = this->j_unsigned; + EXPECT_EQ(json(n), this->j_unsigned); + } + else + { + TypeParam n = this->j; + EXPECT_EQ(json(n), this->j); + } +} + +// exception in case of a non-number type +TEST(JsonGetIntegerExceptionTest, TypeError) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is null"); + EXPECT_THROW_MSG(json(json::value_t::object).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is object"); + EXPECT_THROW_MSG(json(json::value_t::array).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is array"); + EXPECT_THROW_MSG(json(json::value_t::string).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is string"); + EXPECT_THROW_MSG(json(json::value_t::boolean).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is boolean"); + + EXPECT_NO_THROW(json(json::value_t::number_float).get()); + EXPECT_NO_THROW(json(json::value_t::number_float).get()); +} + +template +class JsonGetFloatTest : public ::testing::Test { + public: + JsonGetFloatTest() : j(n_reference) {} + + protected: + json::number_float_t n_reference {42.23}; + json j; +}; + +typedef ::testing::Types + JsonGetFloatTestTypes; + +TYPED_TEST_CASE(JsonGetFloatTest, JsonGetFloatTestTypes); + +TYPED_TEST(JsonGetFloatTest, Explicit) +{ + TypeParam n = (this->j).template get(); + EXPECT_LT(std::fabs(JsonTest::GetValue(json(n)).number_float - + JsonTest::GetValue(this->j).number_float), 0.001); +} + +TYPED_TEST(JsonGetFloatTest, Implicit) +{ + TypeParam n = this->j; + EXPECT_LT(std::fabs(JsonTest::GetValue(json(n)).number_float - + JsonTest::GetValue(this->j).number_float), 0.001); +} + +// exception in case of a non-string type +TEST(JsonGetFloatExceptionTest, TypeError) +{ + EXPECT_THROW_MSG(json(json::value_t::null).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is null"); + EXPECT_THROW_MSG(json(json::value_t::object).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is object"); + EXPECT_THROW_MSG(json(json::value_t::array).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is array"); + EXPECT_THROW_MSG(json(json::value_t::string).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is string"); + EXPECT_THROW_MSG(json(json::value_t::boolean).get(), json::type_error, + "[json.exception.type_error.302] type must be number, but is boolean"); + + EXPECT_NO_THROW(json(json::value_t::number_integer).get()); + EXPECT_NO_THROW(json(json::value_t::number_unsigned).get()); +} + +TEST(JsonGetEnumTest, Case) +{ + enum c_enum { value_1, value_2 }; + enum class cpp_enum { value_1, value_2 }; + + EXPECT_EQ(json(value_1).get(), value_1); + EXPECT_EQ(json(cpp_enum::value_1).get(), cpp_enum::value_1); +} + +class JsonObjectConversionTest : public ::testing::Test { + protected: + json j1 = {{"one", 1}, {"two", 2}, {"three", 3}}; + json j2 = {{"one", 1u}, {"two", 2u}, {"three", 3u}}; + json j3 = {{"one", 1.1}, {"two", 2.2}, {"three", 3.3}}; + json j4 = {{"one", true}, {"two", false}, {"three", true}}; + json j5 = {{"one", "eins"}, {"two", "zwei"}, {"three", "drei"}}; +}; + +TEST_F(JsonObjectConversionTest, StdMap) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + //auto m5 = j5.get>(); +} + +TEST_F(JsonObjectConversionTest, StdUnorderedMap) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + //auto m5 = j5.get>(); + //CHECK(m5["one"] == "eins"); +} + +TEST_F(JsonObjectConversionTest, StdMultiMap) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + //auto m5 = j5.get>(); + //CHECK(m5["one"] == "eins"); +} + +TEST_F(JsonObjectConversionTest, StdUnorderedMultiMap) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + //auto m5 = j5.get>(); + //CHECK(m5["one"] == "eins"); +} + +// exception in case of a non-object type +TEST_F(JsonObjectConversionTest, Exception) +{ + EXPECT_THROW_MSG((json().get>()), json::type_error, + "[json.exception.type_error.302] type must be object, but is null"); +} + +class JsonArrayConversionTest : public ::testing::Test { + protected: + json j1 = {1, 2, 3, 4}; + json j2 = {1u, 2u, 3u, 4u}; + json j3 = {1.2, 2.3, 3.4, 4.5}; + json j4 = {true, false, true}; + json j5 = {"one", "two", "three"}; +}; + +TEST_F(JsonArrayConversionTest, StdList) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + auto m5 = j5.get>(); +} + +#if 0 +TEST_F(JsonArrayConversionTest, StdForwardList) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + auto m5 = j5.get>(); +} +#endif + +TEST_F(JsonArrayConversionTest, StdVector) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + auto m5 = j5.get>(); +} + +TEST_F(JsonArrayConversionTest, StdDeque) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j2.get>(); + auto m4 = j4.get>(); + auto m5 = j5.get>(); +} + +TEST_F(JsonArrayConversionTest, StdSet) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + auto m5 = j5.get>(); +} + +TEST_F(JsonArrayConversionTest, StdUnorderedSet) +{ + auto m1 = j1.get>(); + auto m2 = j2.get>(); + auto m3 = j3.get>(); + auto m4 = j4.get>(); + auto m5 = j5.get>(); +} + +// exception in case of a non-object type +TEST_F(JsonArrayConversionTest, Exception) +{ + EXPECT_THROW_MSG((json().get>()), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); + EXPECT_THROW_MSG((json().get>()), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); + EXPECT_THROW_MSG((json().get>()), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); + EXPECT_THROW_MSG((json().get>()), json::type_error, + "[json.exception.type_error.302] type must be array, but is null"); + // does type really must be an array? or it rather must not be null? + // that's what I thought when other test like this one broke +} diff --git a/src/test/native/cpp/json/unit-deserialization.cpp b/src/test/native/cpp/json/unit-deserialization.cpp new file mode 100644 index 0000000000..5475155f81 --- /dev/null +++ b/src/test/native/cpp/json/unit-deserialization.cpp @@ -0,0 +1,138 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +#include "support/raw_istream.h" +using wpi::json; + +#include + +TEST(JsonDeserializationTest, SuccessfulStream) +{ + std::string s = "[\"foo\",1,2,3,false,{\"one\":1}]"; + wpi::raw_mem_istream ss(s.data(), s.size()); + json j = json::parse(ss); + ASSERT_EQ(j, json({"foo", 1, 2, 3, false, {{"one", 1}}})); +} + +TEST(JsonDeserializationTest, SuccessfulStringLiteral) +{ + auto s = "[\"foo\",1,2,3,false,{\"one\":1}]"; + json j = json::parse(s); + ASSERT_EQ(j, json({"foo", 1, 2, 3, false, {{"one", 1}}})); +} + +TEST(JsonDeserializationTest, SuccessfulStdString) +{ + std::string s = "[\"foo\",1,2,3,false,{\"one\":1}]"; + json j = json::parse(s); + ASSERT_EQ(j, json({"foo", 1, 2, 3, false, {{"one", 1}}})); +} + +TEST(JsonDeserializationTest, SuccessfulStreamOperator) +{ + std::string s = "[\"foo\",1,2,3,false,{\"one\":1}]"; + wpi::raw_mem_istream ss(s.data(), s.size()); + json j; + ss >> j; + ASSERT_EQ(j, json({"foo", 1, 2, 3, false, {{"one", 1}}})); +} + +TEST(JsonDeserializationTest, SuccessfulUserStringLiteral) +{ + ASSERT_EQ("[\"foo\",1,2,3,false,{\"one\":1}]"_json, json({"foo", 1, 2, 3, false, {{"one", 1}}})); +} + +TEST(JsonDeserializationTest, UnsuccessfulStream) +{ + std::string s = "[\"foo\",1,2,3,false,{\"one\":1}"; + wpi::raw_mem_istream ss(s.data(), s.size()); + ASSERT_THROW_MSG(json::parse(ss), json::parse_error, + "[json.exception.parse_error.101] parse error at 29: syntax error - unexpected end of input; expected ']'"); +} + +TEST(JsonDeserializationTest, UnsuccessfulStdString) +{ + std::string s = "[\"foo\",1,2,3,false,{\"one\":1}"; + ASSERT_THROW_MSG(json::parse(s), json::parse_error, + "[json.exception.parse_error.101] parse error at 29: syntax error - unexpected end of input; expected ']'"); +} + +TEST(JsonDeserializationTest, UnsuccessfulStreamOperator) +{ + std::string s = "[\"foo\",1,2,3,false,{\"one\":1}"; + wpi::raw_mem_istream ss(s.data(), s.size()); + json j; + ASSERT_THROW_MSG(ss >> j, json::parse_error, + "[json.exception.parse_error.101] parse error at 29: syntax error - unexpected end of input; expected ']'"); +} + +TEST(JsonDeserializationTest, UnsuccessfulUserStringLiteral) +{ + ASSERT_THROW_MSG("[\"foo\",1,2,3,false,{\"one\":1}"_json, json::parse_error, + "[json.exception.parse_error.101] parse error at 29: syntax error - unexpected end of input; expected ']'"); +} + +// these cases are required for 100% line coverage +class JsonDeserializationErrorTest + : public ::testing::TestWithParam {}; + +TEST_P(JsonDeserializationErrorTest, ErrorCase) +{ + ASSERT_THROW(json::parse(GetParam()), json::parse_error); +} + +static const char* error_cases[] = { + "\"aaaaaa\\u", + "\"aaaaaa\\u1", + "\"aaaaaa\\u11111111", + "\"aaaaaau11111111\\", + "\"\x7F\xC1", + "\"\x7F\xDF\x7F", + "\"\x7F\xDF\xC0", + "\"\x7F\xE0\x9F", + "\"\x7F\xEF\xC0", + "\"\x7F\xED\x7F", + "\"\x7F\xF0\x8F", + "\"\x7F\xF0\xC0", + "\"\x7F\xF3\x7F", + "\"\x7F\xF3\xC0", + "\"\x7F\xF4\x7F", +}; + +INSTANTIATE_TEST_CASE_P(JsonDeserializationErrorTests, + JsonDeserializationErrorTest, + ::testing::ValuesIn(error_cases)); diff --git a/src/test/native/cpp/json/unit-element_access1.cpp b/src/test/native/cpp/json/unit-element_access1.cpp new file mode 100644 index 0000000000..a97d6b66be --- /dev/null +++ b/src/test/native/cpp/json/unit-element_access1.cpp @@ -0,0 +1,873 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +class JsonElementArrayAccessTestBase { + public: + JsonElementArrayAccessTestBase() : j_const(j) {} + + protected: + json j = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; + const json j_const; +}; + +class JsonElementArrayAccessTest : public ::testing::Test, + public JsonElementArrayAccessTestBase {}; + +TEST_F(JsonElementArrayAccessTest, AtWithinBounds) +{ + EXPECT_EQ(j.at(0), json(1)); + EXPECT_EQ(j.at(1), json(1u)); + EXPECT_EQ(j.at(2), json(true)); + EXPECT_EQ(j.at(3), json(nullptr)); + EXPECT_EQ(j.at(4), json("string")); + EXPECT_EQ(j.at(5), json(42.23)); + EXPECT_EQ(j.at(6), json::object()); + EXPECT_EQ(j.at(7), json({1, 2, 3})); + + EXPECT_EQ(j_const.at(0), json(1)); + EXPECT_EQ(j_const.at(1), json(1u)); + EXPECT_EQ(j_const.at(2), json(true)); + EXPECT_EQ(j_const.at(3), json(nullptr)); + EXPECT_EQ(j_const.at(4), json("string")); + EXPECT_EQ(j_const.at(5), json(42.23)); + EXPECT_EQ(j_const.at(6), json::object()); + EXPECT_EQ(j_const.at(7), json({1, 2, 3})); +} + +TEST_F(JsonElementArrayAccessTest, AtOutsideBounds) +{ + EXPECT_THROW_MSG(j.at(8), json::out_of_range, + "[json.exception.out_of_range.401] array index 8 is out of range"); + EXPECT_THROW_MSG(j_const.at(8), json::out_of_range, + "[json.exception.out_of_range.401] array index 8 is out of range"); +} + +TEST(JsonElementNonArrayAtAccessTest, Null) +{ + json j_nonarray(json::value_t::null); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with null"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with null"); +} + +TEST(JsonElementNonArrayAtAccessTest, Boolean) +{ + json j_nonarray(json::value_t::boolean); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with boolean"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with boolean"); +} + +TEST(JsonElementNonArrayAtAccessTest, String) +{ + json j_nonarray(json::value_t::string); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with string"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with string"); +} + +TEST(JsonElementNonArrayAtAccessTest, Object) +{ + json j_nonarray(json::value_t::object); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with object"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with object"); +} + +TEST(JsonElementNonArrayAtAccessTest, Integer) +{ + json j_nonarray(json::value_t::number_integer); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); +} + +TEST(JsonElementNonArrayAtAccessTest, Unsigned) +{ + json j_nonarray(json::value_t::number_unsigned); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); +} + +TEST(JsonElementNonArrayAtAccessTest, Float) +{ + json j_nonarray(json::value_t::number_float); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); + EXPECT_THROW_MSG(j_nonarray_const.at(0), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); +} + +TEST_F(JsonElementArrayAccessTest, FrontAndBack) +{ + EXPECT_EQ(j.front(), json(1)); + EXPECT_EQ(j_const.front(), json(1)); + EXPECT_EQ(j.back(), json({1, 2, 3})); + EXPECT_EQ(j_const.back(), json({1, 2, 3})); +} + +TEST_F(JsonElementArrayAccessTest, OperatorWithinBounds) +{ + EXPECT_EQ(j[0], json(1)); + EXPECT_EQ(j[1], json(1u)); + EXPECT_EQ(j[2], json(true)); + EXPECT_EQ(j[3], json(nullptr)); + EXPECT_EQ(j[4], json("string")); + EXPECT_EQ(j[5], json(42.23)); + EXPECT_EQ(j[6], json::object()); + EXPECT_EQ(j[7], json({1, 2, 3})); + + EXPECT_EQ(j_const[0], json(1)); + EXPECT_EQ(j_const[1], json(1u)); + EXPECT_EQ(j_const[2], json(true)); + EXPECT_EQ(j_const[3], json(nullptr)); + EXPECT_EQ(j_const[4], json("string")); + EXPECT_EQ(j_const[5], json(42.23)); + EXPECT_EQ(j_const[6], json::object()); + EXPECT_EQ(j_const[7], json({1, 2, 3})); +} + +TEST(JsonElementNonArrayOperatorAccessTest, NullStandard) +{ + json j_nonarray(json::value_t::null); + const json j_nonarray_const(j_nonarray); + EXPECT_NO_THROW(j_nonarray[0]); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with null"); +} + +// implicit transformation to properly filled array +TEST(JsonElementNonArrayOperatorAccessTest, NullImplicitFilled) +{ + json j_nonarray; + j_nonarray[3] = 42; + EXPECT_EQ(j_nonarray, json({nullptr, nullptr, nullptr, 42})); +} + +TEST(JsonElementNonArrayOperatorAccessTest, Boolean) +{ + json j_nonarray(json::value_t::boolean); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with boolean"); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with boolean"); +} + +TEST(JsonElementNonArrayOperatorAccessTest, String) +{ + json j_nonarray(json::value_t::string); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with string"); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with string"); +} + +TEST(JsonElementNonArrayOperatorAccessTest, Object) +{ + json j_nonarray(json::value_t::object); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with object"); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with object"); +} + +TEST(JsonElementNonArrayOperatorAccessTest, Integer) +{ + json j_nonarray(json::value_t::number_integer); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); +} + +TEST(JsonElementNonArrayOperatorAccessTest, Unsigned) +{ + json j_nonarray(json::value_t::number_unsigned); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); +} + +TEST(JsonElementNonArrayOperatorAccessTest, Float) +{ + json j_nonarray(json::value_t::number_float); + const json j_nonarray_const(j_nonarray); + EXPECT_THROW_MSG(j_nonarray[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_nonarray_const[0], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); +} + +class JsonElementArrayRemoveTest : public ::testing::Test, + public JsonElementArrayAccessTestBase {}; + + +// remove element by index +TEST_F(JsonElementArrayRemoveTest, Index0) +{ + j.erase(0); + EXPECT_EQ(j, json({1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index1) +{ + j.erase(1); + EXPECT_EQ(j, json({1, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index2) +{ + j.erase(2); + EXPECT_EQ(j, json({1, 1u, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index3) +{ + j.erase(3); + EXPECT_EQ(j, json({1, 1u, true, "string", 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index4) +{ + j.erase(4); + EXPECT_EQ(j, json({1, 1u, true, nullptr, 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index5) +{ + j.erase(5); + EXPECT_EQ(j, json({1, 1u, true, nullptr, "string", json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index6) +{ + j.erase(6); + EXPECT_EQ(j, json({1, 1u, true, nullptr, "string", 42.23, {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, Index7) +{ + j.erase(7); + EXPECT_EQ(j, json({1, 1u, true, nullptr, "string", 42.23, json::object()})); +} + +TEST_F(JsonElementArrayRemoveTest, Index8) +{ + EXPECT_THROW_MSG(j.erase(8), json::out_of_range, + "[json.exception.out_of_range.401] array index 8 is out of range"); +} + +// erase(begin()) +TEST_F(JsonElementArrayRemoveTest, Begin) +{ + j.erase(j.begin()); + EXPECT_EQ(j, json({1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, BeginConst) +{ + j.erase(j.cbegin()); + EXPECT_EQ(j, json({1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +// erase(begin(), end()) +TEST_F(JsonElementArrayRemoveTest, BeginEnd) +{ + j.erase(j.begin(), j.end()); + EXPECT_EQ(j, json::array()); +} +TEST_F(JsonElementArrayRemoveTest, BeginEndConst) +{ + j.erase(j.cbegin(), j.cend()); + EXPECT_EQ(j, json::array()); +} + +// erase(begin(), begin()) +TEST_F(JsonElementArrayRemoveTest, BeginBegin) +{ + j.erase(j.begin(), j.begin()); + EXPECT_EQ(j, json({1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, BeginBeginConst) +{ + j.erase(j.cbegin(), j.cbegin()); + EXPECT_EQ(j, json({1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); +} + +// erase at offset +TEST_F(JsonElementArrayRemoveTest, Offset) +{ + json::iterator it = j.begin() + 4; + j.erase(it); + EXPECT_EQ(j, json({1, 1u, true, nullptr, 42.23, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, OffsetConst) +{ + json::const_iterator it = j.cbegin() + 4; + j.erase(it); + EXPECT_EQ(j, json({1, 1u, true, nullptr, 42.23, json::object(), {1, 2, 3}})); +} + +// erase subrange +TEST_F(JsonElementArrayRemoveTest, Subrange) +{ + j.erase(j.begin() + 3, j.begin() + 6); + EXPECT_EQ(j, json({1, 1u, true, json::object(), {1, 2, 3}})); +} + +TEST_F(JsonElementArrayRemoveTest, SubrangeConst) +{ + j.erase(j.cbegin() + 3, j.cbegin() + 6); + EXPECT_EQ(j, json({1, 1u, true, json::object(), {1, 2, 3}})); +} + +// different arrays +TEST_F(JsonElementArrayRemoveTest, Different) +{ + json j2 = {"foo", "bar"}; + EXPECT_THROW_MSG(j.erase(j2.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(j.erase(j.begin(), j2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(j.erase(j2.begin(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(j.erase(j2.begin(), j2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); +} + +TEST_F(JsonElementArrayRemoveTest, DifferentConst) +{ + json j2 = {"foo", "bar"}; + EXPECT_THROW_MSG(j.erase(j2.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(j.erase(j.cbegin(), j2.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(j.erase(j2.cbegin(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(j.erase(j2.cbegin(), j2.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); +} + +// remove element by index in non-array type +TEST(JsonElementNonArrayIndexRemoveTest, Null) +{ + json j_nonobject(json::value_t::null); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with null"); +} + +TEST(JsonElementNonArrayIndexRemoveTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with boolean"); +} + +TEST(JsonElementNonArrayIndexRemoveTest, String) +{ + json j_nonobject(json::value_t::string); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with string"); +} + +TEST(JsonElementNonArrayIndexRemoveTest, Object) +{ + json j_nonobject(json::value_t::object); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with object"); +} + +TEST(JsonElementNonArrayIndexRemoveTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with number"); +} + +TEST(JsonElementNonArrayIndexRemoveTest, Unsigned) +{ + json j_nonobject(json::value_t::number_unsigned); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with number"); +} + +TEST(JsonElementNonArrayIndexRemoveTest, Float) +{ + json j_nonobject(json::value_t::number_float); + EXPECT_THROW_MSG(j_nonobject.erase(0), json::type_error, + "[json.exception.type_error.307] cannot use erase() with number"); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, Null) +{ + json j; + EXPECT_THROW_MSG(j.front(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(j.back(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, NullConst) +{ + const json j{}; + EXPECT_THROW_MSG(j.front(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(j.back(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, String) +{ + json j = "foo"; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, StringConst) +{ + const json j = "bar"; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, Boolean) +{ + json j = false; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, BooleanConst) +{ + const json j = true; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, Integer) +{ + json j = 17; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, IntegerConst) +{ + const json j = 17; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, Unsigned) +{ + json j = 17u; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, UnsignedConst) +{ + const json j = 17u; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, Float) +{ + json j = 23.42; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayFrontBackAccessTest, FloatConst) +{ + const json j = 23.42; + EXPECT_EQ(j.front(), j); + EXPECT_EQ(j.back(), j); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, Null) +{ + json j; + EXPECT_THROW_MSG(j.erase(j.begin()), json::type_error, + "[json.exception.type_error.307] cannot use erase() with null"); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, NullConst) +{ + json j; + EXPECT_THROW_MSG(j.erase(j.cbegin()), json::type_error, + "[json.exception.type_error.307] cannot use erase() with null"); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, String) +{ + json j = "foo"; + j.erase(j.begin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, StringConst) +{ + json j = "bar"; + j.erase(j.cbegin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, Boolean) +{ + json j = false; + j.erase(j.begin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, BooleanConst) +{ + json j = true; + j.erase(j.cbegin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, Integer) +{ + json j = 17; + j.erase(j.begin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, IntegerConst) +{ + json j = 17; + j.erase(j.cbegin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, Unsigned) +{ + json j = 17u; + j.erase(j.begin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, UnsignedConst) +{ + json j = 17u; + j.erase(j.cbegin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, Float) +{ + json j = 23.42; + j.erase(j.begin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneValidIteratorRemoveTest, FloatConst) +{ + json j = 23.42; + j.erase(j.cbegin()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, String) +{ + json j = "foo"; + EXPECT_THROW_MSG(j.erase(j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, StringConst) +{ + json j = "bar"; + EXPECT_THROW_MSG(j.erase(j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, Boolean) +{ + json j = false; + EXPECT_THROW_MSG(j.erase(j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, BooleanConst) +{ + json j = true; + EXPECT_THROW_MSG(j.erase(j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, Integer) +{ + json j = 17; + EXPECT_THROW_MSG(j.erase(j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, IntegerConst) +{ + json j = 17; + EXPECT_THROW_MSG(j.erase(j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, Unsigned) +{ + json j = 17u; + EXPECT_THROW_MSG(j.erase(j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, UnsignedConst) +{ + json j = 17u; + EXPECT_THROW_MSG(j.erase(j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, Float) +{ + json j = 23.42; + EXPECT_THROW_MSG(j.erase(j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayOneInvalidIteratorRemoveTest, FloatConst) +{ + json j = 23.42; + EXPECT_THROW_MSG(j.erase(j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.205] iterator out of range"); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, Null) +{ + json j; + EXPECT_THROW_MSG(j.erase(j.begin(), j.end()), json::type_error, + "[json.exception.type_error.307] cannot use erase() with null"); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, NullConst) +{ + json j; + EXPECT_THROW_MSG(j.erase(j.cbegin(), j.cend()), json::type_error, + "[json.exception.type_error.307] cannot use erase() with null"); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, String) +{ + json j = "foo"; + j.erase(j.begin(), j.end()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, StringConst) +{ + json j = "bar"; + j.erase(j.cbegin(), j.cend()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, Boolean) +{ + json j = false; + j.erase(j.begin(), j.end()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, BooleanConst) +{ + json j = true; + j.erase(j.cbegin(), j.cend()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, Integer) +{ + json j = 17; + j.erase(j.begin(), j.end()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, IntegerConst) +{ + json j = 17; + j.erase(j.cbegin(), j.cend()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, Unsigned) +{ + json j = 17u; + j.erase(j.begin(), j.end()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, UnsignedConst) +{ + json j = 17u; + j.erase(j.cbegin(), j.cend()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, Float) +{ + json j = 23.42; + j.erase(j.begin(), j.end()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoValidIteratorRemoveTest, FloatConst) +{ + json j = 23.42; + j.erase(j.cbegin(), j.cend()); + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, String) +{ + json j = "foo"; + EXPECT_THROW_MSG(j.erase(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, StringConst) +{ + json j = "bar"; + EXPECT_THROW_MSG(j.erase(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, Boolean) +{ + json j = false; + EXPECT_THROW_MSG(j.erase(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, BooleanConst) +{ + json j = true; + EXPECT_THROW_MSG(j.erase(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, Integer) +{ + json j = 17; + EXPECT_THROW_MSG(j.erase(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, IntegerConst) +{ + json j = 17; + EXPECT_THROW_MSG(j.erase(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, Unsigned) +{ + json j = 17u; + EXPECT_THROW_MSG(j.erase(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, UnsignedConst) +{ + json j = 17u; + EXPECT_THROW_MSG(j.erase(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, Float) +{ + json j = 23.42; + EXPECT_THROW_MSG(j.erase(j.end(), j.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.begin(), j.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} + +TEST(JsonElementNonArrayTwoInvalidIteratorRemoveTest, FloatConst) +{ + json j = 23.42; + EXPECT_THROW_MSG(j.erase(j.cend(), j.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); + EXPECT_THROW_MSG(j.erase(j.cbegin(), j.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.204] iterators out of range"); +} diff --git a/src/test/native/cpp/json/unit-element_access2.cpp b/src/test/native/cpp/json/unit-element_access2.cpp new file mode 100644 index 0000000000..4b6412326e --- /dev/null +++ b/src/test/native/cpp/json/unit-element_access2.cpp @@ -0,0 +1,923 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +class JsonElementObjectAccessTestBase { + public: + JsonElementObjectAccessTestBase() : j_const(j) {} + + protected: + json j = {{"integer", 1}, {"unsigned", 1u}, {"floating", 42.23}, {"null", nullptr}, {"string", "hello world"}, {"boolean", true}, {"object", json::object()}, {"array", {1, 2, 3}}}; + const json j_const; +}; + +class JsonElementObjectAccessTest : public ::testing::Test, + public JsonElementObjectAccessTestBase {}; + +TEST_F(JsonElementObjectAccessTest, AtWithinBounds) +{ + EXPECT_EQ(j.at("integer"), json(1)); + EXPECT_EQ(j.at("unsigned"), json(1u)); + EXPECT_EQ(j.at("boolean"), json(true)); + EXPECT_EQ(j.at("null"), json(nullptr)); + EXPECT_EQ(j.at("string"), json("hello world")); + EXPECT_EQ(j.at("floating"), json(42.23)); + EXPECT_EQ(j.at("object"), json::object()); + EXPECT_EQ(j.at("array"), json({1, 2, 3})); + + EXPECT_EQ(j_const.at("integer"), json(1)); + EXPECT_EQ(j_const.at("unsigned"), json(1u)); + EXPECT_EQ(j_const.at("boolean"), json(true)); + EXPECT_EQ(j_const.at("null"), json(nullptr)); + EXPECT_EQ(j_const.at("string"), json("hello world")); + EXPECT_EQ(j_const.at("floating"), json(42.23)); + EXPECT_EQ(j_const.at("object"), json::object()); + EXPECT_EQ(j_const.at("array"), json({1, 2, 3})); +} + +TEST_F(JsonElementObjectAccessTest, AtOutsideBounds) +{ + EXPECT_THROW_MSG(j.at("foo"), json::out_of_range, + "[json.exception.out_of_range.403] key 'foo' not found"); + EXPECT_THROW_MSG(j_const.at("foo"), json::out_of_range, + "[json.exception.out_of_range.403] key 'foo' not found"); +} + +TEST(JsonElementNonObjectAtAccessTest, Null) +{ + json j_nonobject(json::value_t::null); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with null"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with null"); +} + +TEST(JsonElementNonObjectAtAccessTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with boolean"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with boolean"); +} + +TEST(JsonElementNonObjectAtAccessTest, String) +{ + json j_nonobject(json::value_t::string); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with string"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with string"); +} + +TEST(JsonElementNonObjectAtAccessTest, Array) +{ + json j_nonobject(json::value_t::array); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with array"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with array"); +} + +TEST(JsonElementNonObjectAtAccessTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); +} + +TEST(JsonElementNonObjectAtAccessTest, Unsigned) +{ + json j_nonobject(json::value_t::number_unsigned); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); +} + +TEST(JsonElementNonObjectAtAccessTest, Float) +{ + json j_nonobject(json::value_t::number_float); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); + EXPECT_THROW_MSG(j_nonobject_const.at("foo"), json::type_error, + "[json.exception.type_error.304] cannot use at() with number"); +} + +TEST_F(JsonElementObjectAccessTest, KeyValueExist) +{ + EXPECT_EQ(j.value("integer", 2), 1); + EXPECT_LT(std::fabs(j.value("integer", 1.0) - 1), 0.001); + EXPECT_EQ(j.value("unsigned", 2), 1); + EXPECT_LT(std::fabs(j.value("unsigned", 1.0) - 1), 0.001); + EXPECT_EQ(j.value("null", json(1)), json()); + EXPECT_EQ(j.value("boolean", false), true); + EXPECT_EQ(j.value("string", "bar"), "hello world"); + EXPECT_EQ(j.value("string", std::string("bar")), "hello world"); + EXPECT_LT(std::fabs(j.value("floating", 12.34) - 42.23), 0.001); + EXPECT_EQ(j.value("floating", 12), 42); + EXPECT_EQ(j.value("object", json({{"foo", "bar"}})), json::object()); + EXPECT_EQ(j.value("array", json({10, 100})), json({1, 2, 3})); + + EXPECT_EQ(j_const.value("integer", 2), 1); + EXPECT_LT(std::fabs(j_const.value("integer", 1.0) - 1), 0.001); + EXPECT_EQ(j_const.value("unsigned", 2), 1); + EXPECT_LT(std::fabs(j_const.value("unsigned", 1.0) - 1), 0.001); + EXPECT_EQ(j_const.value("boolean", false), true); + EXPECT_EQ(j_const.value("string", "bar"), "hello world"); + EXPECT_EQ(j_const.value("string", std::string("bar")), "hello world"); + EXPECT_LT(std::fabs(j_const.value("floating", 12.34) - 42.23), 0.001); + EXPECT_EQ(j_const.value("floating", 12), 42); + EXPECT_EQ(j_const.value("object", json({{"foo", "bar"}})), json::object()); + EXPECT_EQ(j_const.value("array", json({10, 100})), json({1, 2, 3})); +} + +TEST_F(JsonElementObjectAccessTest, KeyValueNotExist) +{ + EXPECT_EQ(j.value("_", 2), 2); + EXPECT_EQ(j.value("_", 2u), 2u); + EXPECT_EQ(j.value("_", false), false); + EXPECT_EQ(j.value("_", "bar"), "bar"); + EXPECT_LT(std::fabs(j.value("_", 12.34) - 12.34), 0.001); + EXPECT_EQ(j.value("_", json({{"foo", "bar"}})), json({{"foo", "bar"}})); + EXPECT_EQ(j.value("_", json({10, 100})), json({10, 100})); + + EXPECT_EQ(j_const.value("_", 2), 2); + EXPECT_EQ(j_const.value("_", 2u), 2u); + EXPECT_EQ(j_const.value("_", false), false); + EXPECT_EQ(j_const.value("_", "bar"), "bar"); + EXPECT_LT(std::fabs(j_const.value("_", 12.34) - 12.34), 0.001); + EXPECT_EQ(j_const.value("_", json({{"foo", "bar"}})), json({{"foo", "bar"}})); + EXPECT_EQ(j_const.value("_", json({10, 100})), json({10, 100})); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, Null) +{ + json j_nonobject(json::value_t::null); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with null"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with null"); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with boolean"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with boolean"); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, String) +{ + json j_nonobject(json::value_t::string); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with string"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with string"); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, Array) +{ + json j_nonobject(json::value_t::array); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with array"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with array"); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, Unsigned) +{ + json j_nonobject(json::value_t::number_unsigned); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); +} + +TEST(JsonElementNonObjectKeyValueAccessTest, Float) +{ + json j_nonobject(json::value_t::number_float); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); + EXPECT_THROW_MSG(j_nonobject_const.value("foo", 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); +} + +TEST_F(JsonElementObjectAccessTest, PointerValueExist) +{ + EXPECT_EQ(j.value("/integer"_json_pointer, 2), 1); + EXPECT_LT(std::fabs(j.value("/integer"_json_pointer, 1.0) - 1), 0.001); + EXPECT_EQ(j.value("/unsigned"_json_pointer, 2), 1); + EXPECT_LT(std::fabs(j.value("/unsigned"_json_pointer, 1.0) - 1), 0.001); + EXPECT_EQ(j.value("/null"_json_pointer, json(1)), json()); + EXPECT_EQ(j.value("/boolean"_json_pointer, false), true); + EXPECT_EQ(j.value("/string"_json_pointer, "bar"), "hello world"); + EXPECT_EQ(j.value("/string"_json_pointer, std::string("bar")), "hello world"); + EXPECT_LT(std::fabs(j.value("/floating"_json_pointer, 12.34) - 42.23), 0.001); + EXPECT_EQ(j.value("/floating"_json_pointer, 12), 42); + EXPECT_EQ(j.value("/object"_json_pointer, json({{"foo", "bar"}})), json::object()); + EXPECT_EQ(j.value("/array"_json_pointer, json({10, 100})), json({1, 2, 3})); + + EXPECT_EQ(j_const.value("/integer"_json_pointer, 2), 1); + EXPECT_LT(std::fabs(j_const.value("/integer"_json_pointer, 1.0) - 1), 0.001); + EXPECT_EQ(j_const.value("/unsigned"_json_pointer, 2), 1); + EXPECT_LT(std::fabs(j_const.value("/unsigned"_json_pointer, 1.0) - 1), 0.001); + EXPECT_EQ(j_const.value("/boolean"_json_pointer, false), true); + EXPECT_EQ(j_const.value("/string"_json_pointer, "bar"), "hello world"); + EXPECT_EQ(j_const.value("/string"_json_pointer, std::string("bar")), "hello world"); + EXPECT_LT(std::fabs(j_const.value("/floating"_json_pointer, 12.34) - 42.23), 0.001); + EXPECT_EQ(j_const.value("/floating"_json_pointer, 12), 42); + EXPECT_EQ(j_const.value("/object"_json_pointer, json({{"foo", "bar"}})), json::object()); + EXPECT_EQ(j_const.value("/array"_json_pointer, json({10, 100})), json({1, 2, 3})); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, Null) +{ + json j_nonobject(json::value_t::null); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with null"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with null"); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with boolean"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with boolean"); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, String) +{ + json j_nonobject(json::value_t::string); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with string"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with string"); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, Array) +{ + json j_nonobject(json::value_t::array); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with array"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with array"); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, Unsigned) +{ + json j_nonobject(json::value_t::number_unsigned); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); +} + +TEST(JsonElementNonObjectPointerValueAccessTest, Float) +{ + json j_nonobject(json::value_t::number_float); + const json j_nonobject_const(j_nonobject); + EXPECT_THROW_MSG(j_nonobject.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); + EXPECT_THROW_MSG(j_nonobject_const.value("/foo"_json_pointer, 1), json::type_error, + "[json.exception.type_error.306] cannot use value() with number"); +} +#if 0 +TEST_F(JsonElementObjectAccessTest, FrontAndBack) +{ + // "array" is the smallest key + EXPECT_EQ(j.front(), json({1, 2, 3})); + EXPECT_EQ(j_const.front(), json({1, 2, 3})); + // "unsigned" is the largest key + EXPECT_EQ(j.back(), json(1u)); + EXPECT_EQ(j_const.back(), json(1u)); +} +#endif +TEST_F(JsonElementObjectAccessTest, OperatorWithinBounds) +{ + EXPECT_EQ(j["integer"], json(1)); + EXPECT_EQ(j[json::object_t::key_type("integer")], j["integer"]); + + EXPECT_EQ(j["unsigned"], json(1u)); + EXPECT_EQ(j[json::object_t::key_type("unsigned")], j["unsigned"]); + + EXPECT_EQ(j["boolean"], json(true)); + EXPECT_EQ(j[json::object_t::key_type("boolean")], j["boolean"]); + + EXPECT_EQ(j["null"], json(nullptr)); + EXPECT_EQ(j[json::object_t::key_type("null")], j["null"]); + + EXPECT_EQ(j["string"], json("hello world")); + EXPECT_EQ(j[json::object_t::key_type("string")], j["string"]); + + EXPECT_EQ(j["floating"], json(42.23)); + EXPECT_EQ(j[json::object_t::key_type("floating")], j["floating"]); + + EXPECT_EQ(j["object"], json::object()); + EXPECT_EQ(j[json::object_t::key_type("object")], j["object"]); + + EXPECT_EQ(j["array"], json({1, 2, 3})); + EXPECT_EQ(j[json::object_t::key_type("array")], j["array"]); + + EXPECT_EQ(j_const["integer"], json(1)); + EXPECT_EQ(j_const[json::object_t::key_type("integer")], j["integer"]); + + EXPECT_EQ(j_const["boolean"], json(true)); + EXPECT_EQ(j_const[json::object_t::key_type("boolean")], j["boolean"]); + + EXPECT_EQ(j_const["null"], json(nullptr)); + EXPECT_EQ(j_const[json::object_t::key_type("null")], j["null"]); + + EXPECT_EQ(j_const["string"], json("hello world")); + EXPECT_EQ(j_const[json::object_t::key_type("string")], j["string"]); + + EXPECT_EQ(j_const["floating"], json(42.23)); + EXPECT_EQ(j_const[json::object_t::key_type("floating")], j["floating"]); + + EXPECT_EQ(j_const["object"], json::object()); + EXPECT_EQ(j_const[json::object_t::key_type("object")], j["object"]); + + EXPECT_EQ(j_const["array"], json({1, 2, 3})); + EXPECT_EQ(j_const[json::object_t::key_type("array")], j["array"]); +} + +TEST(JsonElementNonObjectOperatorAccessTest, Null) +{ + json j_nonobject(json::value_t::null); + json j_nonobject2(json::value_t::null); + const json j_const_nonobject(j_nonobject); + EXPECT_NO_THROW(j_nonobject["foo"]); + EXPECT_NO_THROW(j_nonobject2[json::object_t::key_type("foo")]); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with null"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with null"); +} + +TEST(JsonElementNonObjectOperatorAccessTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + const json j_const_nonobject(j_nonobject); + EXPECT_THROW_MSG(j_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with boolean"); + EXPECT_THROW_MSG(j_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with boolean"); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with boolean"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with boolean"); +} + +TEST(JsonElementNonObjectOperatorAccessTest, String) +{ + json j_nonobject(json::value_t::string); + const json j_const_nonobject(j_nonobject); + EXPECT_THROW_MSG(j_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with string"); + EXPECT_THROW_MSG(j_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with string"); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with string"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with string"); +} + +TEST(JsonElementNonObjectOperatorAccessTest, Array) +{ + json j_nonobject(json::value_t::array); + const json j_const_nonobject(j_nonobject); + EXPECT_THROW_MSG(j_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with array"); + EXPECT_THROW_MSG(j_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with array"); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with array"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with array"); +} + +TEST(JsonElementNonObjectOperatorAccessTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + const json j_const_nonobject(j_nonobject); + EXPECT_THROW_MSG(j_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); +} + +TEST(JsonElementNonObjectOperatorAccessTest, Unsigned) +{ + json j_nonobject(json::value_t::number_unsigned); + const json j_const_nonobject(j_nonobject); + EXPECT_THROW_MSG(j_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); +} + +TEST(JsonElementNonObjectOperatorAccessTest, Float) +{ + json j_nonobject(json::value_t::number_float); + const json j_const_nonobject(j_nonobject); + EXPECT_THROW_MSG(j_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_const_nonobject["foo"], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); + EXPECT_THROW_MSG(j_const_nonobject[json::object_t::key_type("foo")], json::type_error, + "[json.exception.type_error.305] cannot use operator[] with number"); +} + +class JsonElementObjectRemoveTest : public ::testing::Test, + public JsonElementObjectAccessTestBase {}; + +TEST_F(JsonElementObjectRemoveTest, Key) +{ + EXPECT_NE(j.find("integer"), j.end()); + EXPECT_EQ(j.erase("integer"), 1u); + EXPECT_EQ(j.find("integer"), j.end()); + EXPECT_EQ(j.erase("integer"), 0u); + + EXPECT_NE(j.find("unsigned"), j.end()); + EXPECT_EQ(j.erase("unsigned"), 1u); + EXPECT_EQ(j.find("unsigned"), j.end()); + EXPECT_EQ(j.erase("unsigned"), 0u); + + EXPECT_NE(j.find("boolean"), j.end()); + EXPECT_EQ(j.erase("boolean"), 1u); + EXPECT_EQ(j.find("boolean"), j.end()); + EXPECT_EQ(j.erase("boolean"), 0u); + + EXPECT_NE(j.find("null"), j.end()); + EXPECT_EQ(j.erase("null"), 1u); + EXPECT_EQ(j.find("null"), j.end()); + EXPECT_EQ(j.erase("null"), 0u); + + EXPECT_NE(j.find("string"), j.end()); + EXPECT_EQ(j.erase("string"), 1u); + EXPECT_EQ(j.find("string"), j.end()); + EXPECT_EQ(j.erase("string"), 0u); + + EXPECT_NE(j.find("floating"), j.end()); + EXPECT_EQ(j.erase("floating"), 1u); + EXPECT_EQ(j.find("floating"), j.end()); + EXPECT_EQ(j.erase("floating"), 0u); + + EXPECT_NE(j.find("object"), j.end()); + EXPECT_EQ(j.erase("object"), 1u); + EXPECT_EQ(j.find("object"), j.end()); + EXPECT_EQ(j.erase("object"), 0u); + + EXPECT_NE(j.find("array"), j.end()); + EXPECT_EQ(j.erase("array"), 1u); + EXPECT_EQ(j.find("array"), j.end()); + EXPECT_EQ(j.erase("array"), 0u); +} + +// erase(begin()) +TEST_F(JsonElementObjectRemoveTest, Begin) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + jobject.erase(jobject.begin()); + EXPECT_EQ(jobject, json({{"b", 1}, {"c", 17u}})); +} + +TEST_F(JsonElementObjectRemoveTest, BeginConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + jobject.erase(jobject.cbegin()); + EXPECT_EQ(jobject, json({{"b", 1}, {"c", 17u}})); +} + +// erase(begin(), end()) +TEST_F(JsonElementObjectRemoveTest, BeginEnd) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json::iterator it2 = jobject.erase(jobject.begin(), jobject.end()); + EXPECT_EQ(jobject, json::object()); + EXPECT_EQ(it2, jobject.end()); +#else + EXPECT_THROW(jobject.erase(jobject.begin(), jobject.end()), json::type_error); +#endif +} + +TEST_F(JsonElementObjectRemoveTest, BeginEndConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json::const_iterator it2 = jobject.erase(jobject.cbegin(), jobject.cend()); + EXPECT_EQ(jobject, json::object()); + EXPECT_EQ(it2, jobject.cend()); +#else + EXPECT_THROW(jobject.erase(jobject.cbegin(), jobject.cend()), json::type_error); +#endif +} + +TEST_F(JsonElementObjectRemoveTest, BeginBegin) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json::iterator it2 = jobject.erase(jobject.begin(), jobject.begin()); + EXPECT_EQ(jobject, json({{"a", "a"}, {"b", 1}, {"c", 17u}})); + EXPECT_EQ(*it2, json("a")); +#else + EXPECT_THROW(jobject.erase(jobject.begin(), jobject.end()), json::type_error); +#endif +} + +TEST_F(JsonElementObjectRemoveTest, BeginBeginConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; +#if 0 + json::const_iterator it2 = jobject.erase(jobject.cbegin(), jobject.cbegin()); + EXPECT_EQ(jobject, json({{"a", "a"}, {"b", 1}, {"c", 17u}})); + EXPECT_EQ(*it2, json("a")); +#else + EXPECT_THROW(jobject.erase(jobject.cbegin(), jobject.cbegin()), json::type_error); +#endif +} + +TEST_F(JsonElementObjectRemoveTest, Offset) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + json::iterator it = jobject.find("b"); + jobject.erase(it); + EXPECT_EQ(jobject, json({{"a", "a"}, {"c", 17u}})); +} + +TEST_F(JsonElementObjectRemoveTest, OffsetConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + json::const_iterator it = jobject.find("b"); + jobject.erase(it); + EXPECT_EQ(jobject, json({{"a", "a"}, {"c", 17u}})); +} + +TEST_F(JsonElementObjectRemoveTest, Subrange) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; +#if 0 + json::iterator it2 = jobject.erase(jobject.find("b"), jobject.find("e")); + EXPECT_EQ(jobject, json({{"a", "a"}, {"e", true}})); + EXPECT_EQ(*it2, json(true)); +#else + EXPECT_THROW(jobject.erase(jobject.find("b"), jobject.find("e")), json::type_error); +#endif +} + +TEST_F(JsonElementObjectRemoveTest, SubrangeConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; +#if 0 + json::const_iterator it2 = jobject.erase(jobject.find("b"), jobject.find("e")); + EXPECT_EQ(jobject, json({{"a", "a"}, {"e", true}})); + EXPECT_EQ(*it2, json(true)); +#else + EXPECT_THROW(jobject.erase(jobject.find("b"), jobject.find("e")), json::type_error); +#endif +} + +TEST_F(JsonElementObjectRemoveTest, Different) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; + json jobject2 = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + EXPECT_THROW_MSG(jobject.erase(jobject2.begin()), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(jobject.erase(jobject.begin(), jobject2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(jobject.erase(jobject2.begin(), jobject.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(jobject.erase(jobject2.begin(), jobject2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); +} + +TEST_F(JsonElementObjectRemoveTest, DifferentConst) +{ + json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; + json jobject2 = {{"a", "a"}, {"b", 1}, {"c", 17u}}; + EXPECT_THROW_MSG(jobject.erase(jobject2.cbegin()), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(jobject.erase(jobject.cbegin(), jobject2.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(jobject.erase(jobject2.cbegin(), jobject.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); + EXPECT_THROW_MSG(jobject.erase(jobject2.cbegin(), jobject2.cend()), json::invalid_iterator, + "[json.exception.invalid_iterator.203] iterators do not fit current value"); +} + +// remove element by key in non-object type +TEST(JsonElementNonObjectKeyRemoveTest, Null) +{ + json j_nonobject(json::value_t::null); + EXPECT_THROW_MSG(j_nonobject.erase("foo"), json::type_error, + "[json.exception.type_error.307] cannot use erase() with null"); +} + +TEST(JsonElementNonObjectKeyRemoveTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + EXPECT_THROW_MSG(j_nonobject.erase("foo"), json::type_error, + "[json.exception.type_error.307] cannot use erase() with boolean"); +} + +TEST(JsonElementNonObjectKeyRemoveTest, String) +{ + json j_nonobject(json::value_t::string); + EXPECT_THROW_MSG(j_nonobject.erase("foo"), json::type_error, + "[json.exception.type_error.307] cannot use erase() with string"); +} + +TEST(JsonElementNonObjectKeyRemoveTest, Array) +{ + json j_nonobject(json::value_t::array); + EXPECT_THROW_MSG(j_nonobject.erase("foo"), json::type_error, + "[json.exception.type_error.307] cannot use erase() with array"); +} + +TEST(JsonElementNonObjectKeyRemoveTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + EXPECT_THROW_MSG(j_nonobject.erase("foo"), json::type_error, + "[json.exception.type_error.307] cannot use erase() with number"); +} + +TEST(JsonElementNonObjectKeyRemoveTest, Float) +{ + json j_nonobject(json::value_t::number_float); + EXPECT_THROW_MSG(j_nonobject.erase("foo"), json::type_error, + "[json.exception.type_error.307] cannot use erase() with number"); +} + +TEST_F(JsonElementObjectAccessTest, FindExist) +{ + for (auto key : + {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" + }) + { + EXPECT_NE(j.find(key), j.end()); + EXPECT_EQ(*j.find(key), j.at(key)); + EXPECT_NE(j_const.find(key), j_const.end()); + EXPECT_EQ(*j_const.find(key), j_const.at(key)); + } +} + +TEST_F(JsonElementObjectAccessTest, FindNotExist) +{ + EXPECT_EQ(j.find("foo"), j.end()); + EXPECT_EQ(j_const.find("foo"), j_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Null) +{ + json j_nonarray(json::value_t::null); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, String) +{ + json j_nonarray(json::value_t::string); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Object) +{ + json j_nonarray(json::value_t::object); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Array) +{ + json j_nonarray(json::value_t::array); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Boolean) +{ + json j_nonarray(json::value_t::boolean); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Integer) +{ + json j_nonarray(json::value_t::number_integer); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Unsigned) +{ + json j_nonarray(json::value_t::number_unsigned); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST(JsonElementNonObjectFindAccessTest, Float) +{ + json j_nonarray(json::value_t::number_float); + const json j_nonarray_const(j_nonarray); + EXPECT_EQ(j_nonarray.find("foo"), j_nonarray.end()); + EXPECT_EQ(j_nonarray_const.find("foo"), j_nonarray_const.end()); +} + +TEST_F(JsonElementObjectAccessTest, CountExist) +{ + for (auto key : + {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" + }) + { + EXPECT_EQ(j.count(key), 1u); + EXPECT_EQ(j_const.count(key), 1u); + } +} + +TEST_F(JsonElementObjectAccessTest, CountNotExist) +{ + EXPECT_EQ(j.count("foo"), 0u); + EXPECT_EQ(j_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Null) +{ + json j_nonobject(json::value_t::null); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, String) +{ + json j_nonobject(json::value_t::string); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Object) +{ + json j_nonobject(json::value_t::object); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Array) +{ + json j_nonobject(json::value_t::array); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Boolean) +{ + json j_nonobject(json::value_t::boolean); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Integer) +{ + json j_nonobject(json::value_t::number_integer); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Unsigned) +{ + json j_nonobject(json::value_t::number_unsigned); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST(JsonElementNonObjectCountAccessTest, Float) +{ + json j_nonobject(json::value_t::number_float); + const json j_nonobject_const(j_nonobject); + EXPECT_EQ(j_nonobject.count("foo"), 0u); + EXPECT_EQ(j_nonobject_const.count("foo"), 0u); +} + +TEST_F(JsonElementObjectAccessTest, PointerValueNotExist) +{ + EXPECT_EQ(j.value("/not/existing"_json_pointer, 2), 2); + EXPECT_EQ(j.value("/not/existing"_json_pointer, 2u), 2u); + EXPECT_EQ(j.value("/not/existing"_json_pointer, false), false); + EXPECT_EQ(j.value("/not/existing"_json_pointer, "bar"), "bar"); + EXPECT_LT(std::fabs(j.value("/not/existing"_json_pointer, 12.34) - 12.34), 0.001); + EXPECT_EQ(j.value("/not/existing"_json_pointer, json({{"foo", "bar"}})), json({{"foo", "bar"}})); + EXPECT_EQ(j.value("/not/existing"_json_pointer, json({10, 100})), json({10, 100})); + + EXPECT_EQ(j_const.value("/not/existing"_json_pointer, 2), 2); + EXPECT_EQ(j_const.value("/not/existing"_json_pointer, 2u), 2u); + EXPECT_EQ(j_const.value("/not/existing"_json_pointer, false), false); + EXPECT_EQ(j_const.value("/not/existing"_json_pointer, "bar"), "bar"); + EXPECT_LT(std::fabs(j_const.value("/not/existing"_json_pointer, 12.34) - 12.34), 0.001); + EXPECT_EQ(j_const.value("/not/existing"_json_pointer, json({{"foo", "bar"}})), json({{"foo", "bar"}})); + EXPECT_EQ(j_const.value("/not/existing"_json_pointer, json({10, 100})), json({10, 100})); +} diff --git a/src/test/native/cpp/json/unit-inspection.cpp b/src/test/native/cpp/json/unit-inspection.cpp new file mode 100644 index 0000000000..79c63f0cca --- /dev/null +++ b/src/test/native/cpp/json/unit-inspection.cpp @@ -0,0 +1,385 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonConvTypeCheckTest, Object) +{ + json j {{"foo", 1}, {"bar", false}}; + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_FALSE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_TRUE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_FALSE(j.is_primitive()); + EXPECT_TRUE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Array) +{ + json j {"foo", 1, 1u, 42.23, false}; + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_FALSE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_TRUE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_FALSE(j.is_primitive()); + EXPECT_TRUE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Null) +{ + json j(nullptr); + EXPECT_TRUE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_FALSE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_TRUE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Boolean) +{ + json j(true); + EXPECT_FALSE(j.is_null()); + EXPECT_TRUE(j.is_boolean()); + EXPECT_FALSE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_TRUE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, String) +{ + json j("Hello world"); + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_FALSE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_TRUE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_TRUE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Integer) +{ + json j(42); + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_TRUE(j.is_number()); + EXPECT_TRUE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_TRUE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Unsigned) +{ + json j(42u); + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_TRUE(j.is_number()); + EXPECT_TRUE(j.is_number_integer()); + EXPECT_TRUE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_TRUE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Float) +{ + json j(42.23); + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_TRUE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_TRUE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_FALSE(j.is_discarded()); + EXPECT_TRUE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +TEST(JsonConvTypeCheckTest, Discarded) +{ + json j(json::value_t::discarded); + EXPECT_FALSE(j.is_null()); + EXPECT_FALSE(j.is_boolean()); + EXPECT_FALSE(j.is_number()); + EXPECT_FALSE(j.is_number_integer()); + EXPECT_FALSE(j.is_number_unsigned()); + EXPECT_FALSE(j.is_number_float()); + EXPECT_FALSE(j.is_object()); + EXPECT_FALSE(j.is_array()); + EXPECT_FALSE(j.is_string()); + EXPECT_TRUE(j.is_discarded()); + EXPECT_FALSE(j.is_primitive()); + EXPECT_FALSE(j.is_structured()); +} + +class JsonConvSerializationTest : public ::testing::Test { + protected: + json j {{"object", json::object()}, {"array", {1, 2, 3, 4}}, {"number", 42}, {"boolean", false}, {"null", nullptr}, {"string", "Hello world"} }; +}; +#if 0 +// no indent / indent=-1 +TEST_F(JsonConvSerializationTest, NoIndent) +{ + EXPECT_EQ(j.dump(), + "{\"array\":[1,2,3,4],\"boolean\":false,\"null\":null,\"number\":42,\"object\":{},\"string\":\"Hello world\"}"); + + EXPECT_EQ(j.dump(), j.dump(-1)); +} + +// indent=0 +TEST_F(JsonConvSerializationTest, Indent0) +{ + EXPECT_EQ(j.dump(0), + "{\n\"array\": [\n1,\n2,\n3,\n4\n],\n\"boolean\": false,\n\"null\": null,\n\"number\": 42,\n\"object\": {},\n\"string\": \"Hello world\"\n}"); +} + +// indent=1, space='\t' +TEST_F(JsonConvSerializationTest, Indent1) +{ + EXPECT_EQ(j.dump(1, '\t'), + "{\n\t\"array\": [\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t4\n\t],\n\t\"boolean\": false,\n\t\"null\": null,\n\t\"number\": 42,\n\t\"object\": {},\n\t\"string\": \"Hello world\"\n}"); +} + +// indent=4 +TEST_F(JsonConvSerializationTest, Indent4) +{ + EXPECT_EQ(j.dump(4), + "{\n \"array\": [\n 1,\n 2,\n 3,\n 4\n ],\n \"boolean\": false,\n \"null\": null,\n \"number\": 42,\n \"object\": {},\n \"string\": \"Hello world\"\n}"); +} +#endif +// indent=x +TEST_F(JsonConvSerializationTest, IndentX) +{ + EXPECT_EQ(j.dump().size(), 94u); + EXPECT_EQ(j.dump(1).size(), 127u); + EXPECT_EQ(j.dump(2).size(), 142u); + EXPECT_EQ(j.dump(512).size(), 7792u); +} + +// dump and floating-point numbers +TEST_F(JsonConvSerializationTest, Float) +{ + auto s = json(42.23).dump(); + EXPECT_NE(s.find("42.23"), std::string::npos); +} + +// dump and small floating-point numbers +TEST_F(JsonConvSerializationTest, SmallFloat) +{ + auto s = json(1.23456e-78).dump(); + EXPECT_NE(s.find("1.23456e-78"), std::string::npos); +} + +// dump and non-ASCII characters +TEST_F(JsonConvSerializationTest, NonAscii) +{ + EXPECT_EQ(json("ä").dump(), "\"ä\""); + EXPECT_EQ(json("Ö").dump(), "\"Ö\""); + EXPECT_EQ(json("❤️").dump(), "\"❤️\""); +} + +// serialization of discarded element +TEST_F(JsonConvSerializationTest, Discarded) +{ + json j_discarded(json::value_t::discarded); + EXPECT_EQ(j_discarded.dump(), ""); +} + +TEST(JsonConvRoundTripTest, Case) +{ + for (const auto& s : +{"3.141592653589793", "1000000000000000010E5" +}) + { + SCOPED_TRACE(s); + json j1 = json::parse(s); + std::string s1 = j1.dump(); + json j2 = json::parse(s1); + std::string s2 = j2.dump(); + EXPECT_EQ(s1, s2); + } +} + +// return the type of the object (explicit) +TEST(JsonConvTypeExplicitTest, Null) +{ + json j = nullptr; + EXPECT_EQ(j.type(), json::value_t::null); +} + +TEST(JsonConvTypeExplicitTest, Object) +{ + json j = {{"foo", "bar"}}; + EXPECT_EQ(j.type(), json::value_t::object); +} + +TEST(JsonConvTypeExplicitTest, Array) +{ + json j = {1, 2, 3, 4}; + EXPECT_EQ(j.type(), json::value_t::array); +} + +TEST(JsonConvTypeExplicitTest, Boolean) +{ + json j = true; + EXPECT_EQ(j.type(), json::value_t::boolean); +} + +TEST(JsonConvTypeExplicitTest, String) +{ + json j = "Hello world"; + EXPECT_EQ(j.type(), json::value_t::string); +} + +TEST(JsonConvTypeExplicitTest, Integer) +{ + json j = 23; + EXPECT_EQ(j.type(), json::value_t::number_integer); +} + +TEST(JsonConvTypeExplicitTest, Unsigned) +{ + json j = 23u; + EXPECT_EQ(j.type(), json::value_t::number_unsigned); +} + +TEST(JsonConvTypeExplicitTest, Float) +{ + json j = 42.23; + EXPECT_EQ(j.type(), json::value_t::number_float); +} + +// return the type of the object (implicit) +TEST(JsonConvTypeImplicitTest, Null) +{ + json j = nullptr; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, Object) +{ + json j = {{"foo", "bar"}}; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, Array) +{ + json j = {1, 2, 3, 4}; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, Boolean) +{ + json j = true; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, String) +{ + json j = "Hello world"; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, Integer) +{ + json j = 23; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, Unsigned) +{ + json j = 23u; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} + +TEST(JsonConvTypeImplicitTest, Float) +{ + json j = 42.23; + json::value_t t = j; + EXPECT_EQ(t, j.type()); +} diff --git a/src/test/native/cpp/json/unit-iterator_wrapper.cpp b/src/test/native/cpp/json/unit-iterator_wrapper.cpp new file mode 100644 index 0000000000..8d1f18ed1e --- /dev/null +++ b/src/test/native/cpp/json/unit-iterator_wrapper.cpp @@ -0,0 +1,745 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +class JsonIteratorWrapperObjectTest : public ::testing::Test { + protected: + json j = {{"A", 1}, {"B", 2}}; +}; + +TEST_F(JsonIteratorWrapperObjectTest, Value) +{ + int counter = 1; + + for (auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperObjectTest, Reference) +{ + int counter = 1; + + for (auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + + // change the value + i.value() = json(11); + EXPECT_EQ(i.value(), json(11)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + + // change the value + i.value() = json(22); + EXPECT_EQ(i.value(), json(22)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); + + // check if values where changed + EXPECT_EQ(j, json({{"A", 11}, {"B", 22}})); +} + +TEST_F(JsonIteratorWrapperObjectTest, ConstValue) +{ + int counter = 1; + + for (const auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperObjectTest, ConstReference) +{ + json j = {{"A", 1}, {"B", 2}}; + int counter = 1; + + for (const auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +class JsonIteratorWrapperConstObjectTest : public ::testing::Test { + protected: + const json j = {{"A", 1}, {"B", 2}}; +}; + +TEST_F(JsonIteratorWrapperConstObjectTest, Value) +{ + int counter = 1; + + for (auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperConstObjectTest, Reference) +{ + int counter = 1; + + for (auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperConstObjectTest, ConstValue) +{ + int counter = 1; + + for (const auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperConstObjectTest, ConstReference) +{ + int counter = 1; + + for (const auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "A"); + EXPECT_EQ(i.value(), json(1)); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "B"); + EXPECT_EQ(i.value(), json(2)); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +class JsonIteratorWrapperArrayTest : public ::testing::Test { + protected: + json j = {"A", "B"}; +}; + +TEST_F(JsonIteratorWrapperArrayTest, Value) +{ + int counter = 1; + + for (auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperArrayTest, Reference) +{ + int counter = 1; + + for (auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + + // change the value + i.value() = "AA"; + EXPECT_EQ(i.value(), "AA"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + + // change the value + i.value() = "BB"; + EXPECT_EQ(i.value(), "BB"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); + + // check if values where changed + EXPECT_EQ(j, json({"AA", "BB"})); +} + +TEST_F(JsonIteratorWrapperArrayTest, ConstValue) +{ + int counter = 1; + + for (const auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperArrayTest, ConstReference) +{ + int counter = 1; + + for (const auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +class JsonIteratorWrapperConstArrayTest : public ::testing::Test { + protected: + const json j = {"A", "B"}; +}; + +TEST_F(JsonIteratorWrapperConstArrayTest, Value) +{ + int counter = 1; + + for (auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperConstArrayTest, Reference) +{ + int counter = 1; + + for (auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperConstArrayTest, ConstValue) +{ + int counter = 1; + + for (const auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +TEST_F(JsonIteratorWrapperConstArrayTest, ConstReference) +{ + int counter = 1; + + for (const auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + switch (counter++) + { + case 1: + { + EXPECT_EQ(i.key(), "0"); + EXPECT_EQ(i.value(), "A"); + break; + } + + case 2: + { + EXPECT_EQ(i.key(), "1"); + EXPECT_EQ(i.value(), "B"); + break; + } + + default: + { + break; + } + } + } + + EXPECT_EQ(counter, 3); +} + +class JsonIteratorWrapperPrimitiveTest : public ::testing::Test { + protected: + json j = 1; +}; + +TEST_F(JsonIteratorWrapperPrimitiveTest, Value) +{ + int counter = 1; + + for (auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} + +TEST_F(JsonIteratorWrapperPrimitiveTest, Reference) +{ + int counter = 1; + + for (auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + + // change value + i.value() = json(2); + } + + EXPECT_EQ(counter, 2); + + // check if value has changed + EXPECT_EQ(j, json(2)); +} + +TEST_F(JsonIteratorWrapperPrimitiveTest, ConstValue) +{ + int counter = 1; + + for (const auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} + +TEST_F(JsonIteratorWrapperPrimitiveTest, ConstReference) +{ + int counter = 1; + + for (const auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} + +class JsonIteratorWrapperConstPrimitiveTest : public ::testing::Test { + protected: + const json j = 1; +}; + +TEST_F(JsonIteratorWrapperConstPrimitiveTest, Value) +{ + int counter = 1; + + for (auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} + +TEST_F(JsonIteratorWrapperConstPrimitiveTest, Reference) +{ + int counter = 1; + + for (auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} + +TEST_F(JsonIteratorWrapperConstPrimitiveTest, ConstValue) +{ + int counter = 1; + + for (const auto i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} + +TEST_F(JsonIteratorWrapperConstPrimitiveTest, ConstReference) +{ + int counter = 1; + + for (const auto& i : json::iterator_wrapper(j)) + { + SCOPED_TRACE(counter); + ++counter; + EXPECT_EQ(i.key(), ""); + EXPECT_EQ(i.value(), json(1)); + } + + EXPECT_EQ(counter, 2); +} diff --git a/src/test/native/cpp/json/unit-iterators1.cpp b/src/test/native/cpp/json/unit-iterators1.cpp new file mode 100644 index 0000000000..2dd8219aaf --- /dev/null +++ b/src/test/native/cpp/json/unit-iterators1.cpp @@ -0,0 +1,1616 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; +using wpi::JsonTest; + +TEST(JsonIteratorBasicTest, Uninitialized) +{ + json::iterator it; + EXPECT_EQ(JsonTest::GetObject(it), nullptr); + + json::const_iterator cit; + EXPECT_EQ(JsonTest::GetObject(cit), nullptr); +} + +class JsonIteratorBooleanTest : public ::testing::Test { + public: + JsonIteratorBooleanTest() : j_const(j) {} + + protected: + json j = true; + json j_const; +}; + +TEST_F(JsonIteratorBooleanTest, BeginEnd) +{ + json::iterator it = j.begin(); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + it--; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + --it; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorBooleanTest, ConstBeginEnd) +{ + json::const_iterator it = j_const.begin(); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + it--; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + --it; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); +} + +TEST_F(JsonIteratorBooleanTest, CBeginEnd) +{ + json::const_iterator it = j.cbegin(); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + it--; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + --it; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorBooleanTest, ConstCBeginEnd) +{ + json::const_iterator it = j_const.cbegin(); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + it--; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + --it; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); +} +#if 0 +TEST_F(JsonIteratorBooleanTest, RBeginEnd) +{ + json::reverse_iterator it = j.rbegin(); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + it--; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + --it; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorBooleanTest, CRBeginEnd) +{ + json::const_reverse_iterator it = j.crbegin(); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + it--; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + --it; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorBooleanTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it = j_const.crbegin(); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + it--; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + --it; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); +} +#endif +TEST_F(JsonIteratorBooleanTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(it.value(), json(true)); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(cit.value(), json(true)); +#if 0 + auto rit = j.rend(); + auto crit = j.crend(); + EXPECT_THROW_MSG(rit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(rit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(crit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(crit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#endif +} + +class JsonIteratorStringTest : public ::testing::Test { + public: + JsonIteratorStringTest() : j_const(j) {} + + protected: + json j = "hello world"; + json j_const; +}; + +TEST_F(JsonIteratorStringTest, BeginEnd) +{ + json::iterator it = j.begin(); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + it--; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + --it; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorStringTest, ConstBeginEnd) +{ + json::const_iterator it = j_const.begin(); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + it--; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + --it; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); +} + +TEST_F(JsonIteratorStringTest, CBeginEnd) +{ + json::const_iterator it = j.cbegin(); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + it--; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + --it; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorStringTest, ConstCBeginEnd) +{ + json::const_iterator it = j_const.cbegin(); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + it--; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + --it; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); +} +#if 0 +TEST_F(JsonIteratorStringTest, RBeginEnd) +{ + json::reverse_iterator it = j.rbegin(); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + it--; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + --it; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorStringTest, CRBeginEnd) +{ + json::const_reverse_iterator it = j.crbegin(); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + it--; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + --it; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorStringTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it = j_const.crbegin(); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + it--; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + --it; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); +} +#endif +TEST_F(JsonIteratorStringTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(it.value(), json("hello world")); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(cit.value(), json("hello world")); +#if 0 + auto rit = j.rend(); + auto crit = j.crend(); + EXPECT_THROW_MSG(rit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(rit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(crit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(crit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#endif +} + +class JsonIteratorArrayTest : public ::testing::Test { + public: + JsonIteratorArrayTest() : j_const(j) {} + + protected: + json j = {1, 2, 3}; + json j_const; +}; + +TEST_F(JsonIteratorArrayTest, BeginEnd) +{ + json::iterator it_begin = j.begin(); + json::iterator it_end = j.end(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[0]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[2]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorArrayTest, ConstBeginEnd) +{ + json::const_iterator it_begin = j_const.begin(); + json::const_iterator it_end = j_const.end(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const[0]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const[2]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorArrayTest, CBeginEnd) +{ + json::const_iterator it_begin = j.cbegin(); + json::const_iterator it_end = j.cend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[0]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[2]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorArrayTest, ConstCBeginEnd) +{ + json::const_iterator it_begin = j_const.cbegin(); + json::const_iterator it_end = j_const.cend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[0]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[2]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} +#if 0 +TEST_F(JsonIteratorArrayTest, RBeginEnd) +{ + json::reverse_iterator it_begin = j.rbegin(); + json::reverse_iterator it_end = j.rend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[2]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[0]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorArrayTest, CRBeginEnd) +{ + json::const_reverse_iterator it_begin = j.crbegin(); + json::const_reverse_iterator it_end = j.crend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[2]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[0]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorArrayTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it_begin = j_const.crbegin(); + json::const_reverse_iterator it_end = j_const.crend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[2]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[1]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j[0]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} +#endif +TEST_F(JsonIteratorArrayTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(it.value(), json(1)); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(cit.value(), json(1)); +} + +class JsonIteratorObjectTest : public ::testing::Test { + public: + JsonIteratorObjectTest() : j_const(j) {} + + protected: + json j = {{"A", 1}, {"B", 2}, {"C", 3}}; + json j_const; +}; + +TEST_F(JsonIteratorObjectTest, BeginEnd) +{ + json::iterator it_begin = j.begin(); + json::iterator it_end = j.end(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["A"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["C"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorObjectTest, ConstBeginEnd) +{ + json::const_iterator it_begin = j_const.begin(); + json::const_iterator it_end = j_const.end(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const["A"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const["C"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorObjectTest, CBeginEnd) +{ + json::const_iterator it_begin = j.cbegin(); + json::const_iterator it_end = j.cend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["A"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["C"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorObjectTest, ConstCBeginEnd) +{ + json::const_iterator it_begin = j_const.cbegin(); + json::const_iterator it_end = j_const.cend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const["A"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j_const["C"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} +#if 0 +TEST_F(JsonIteratorObjectTest, RBeginEnd) +{ + json::reverse_iterator it_begin = j.rbegin(); + json::reverse_iterator it_end = j.rend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["C"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["A"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorObjectTest, CRBeginEnd) +{ + json::const_reverse_iterator it_begin = j.crbegin(); + json::const_reverse_iterator it_end = j.crend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["C"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["A"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} + +TEST_F(JsonIteratorObjectTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it_begin = j_const.crbegin(); + json::const_reverse_iterator it_end = j_const.crend(); + + auto it = it_begin; + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["C"]); + + it++; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["B"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_NE(it, it_end); + EXPECT_EQ(*it, j["A"]); + + ++it; + EXPECT_NE(it, it_begin); + EXPECT_EQ(it, it_end); +} +#endif +TEST_F(JsonIteratorObjectTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_EQ(it.key(), "A"); + EXPECT_EQ(it.value(), json(1)); + EXPECT_EQ(cit.key(), "A"); + EXPECT_EQ(cit.value(), json(1)); +} + +class JsonIteratorIntegerTest : public ::testing::Test { + public: + JsonIteratorIntegerTest() : j_const(j) {} + + protected: + json j = 23; + json j_const; +}; + +TEST_F(JsonIteratorIntegerTest, BeginEnd) +{ + json::iterator it = j.begin(); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + it--; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + --it; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorIntegerTest, ConstBeginEnd) +{ + json::const_iterator it = j_const.begin(); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + it--; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + --it; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); +} + +TEST_F(JsonIteratorIntegerTest, CBeginEnd) +{ + json::const_iterator it = j.cbegin(); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + it--; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + --it; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorIntegerTest, ConstCBeginEnd) +{ + json::const_iterator it = j_const.cbegin(); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + it--; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + --it; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); +} +#if 0 +TEST_F(JsonIteratorIntegerTest, RBeginEnd) +{ + json::reverse_iterator it = j.rbegin(); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + it--; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + --it; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorIntegerTest, CRBeginEnd) +{ + json::const_reverse_iterator it = j.crbegin(); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + it--; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + --it; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorIntegerTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it = j_const.crbegin(); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + it--; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + --it; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); +} +#endif +TEST_F(JsonIteratorIntegerTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(it.value(), json(23)); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(cit.value(), json(23)); +#if 0 + auto rit = j.rend(); + auto crit = j.crend(); + EXPECT_THROW_MSG(rit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(rit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(crit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(crit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#endif +} + +class JsonIteratorUnsignedTest : public ::testing::Test { + public: + JsonIteratorUnsignedTest() : j_const(j) {} + + protected: + json j = 23u; + json j_const; +}; + +TEST_F(JsonIteratorUnsignedTest, BeginEnd) +{ + json::iterator it = j.begin(); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + it--; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + --it; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorUnsignedTest, ConstBeginEnd) +{ + json::const_iterator it = j_const.begin(); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + it--; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + --it; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); +} + +TEST_F(JsonIteratorUnsignedTest, CBeginEnd) +{ + json::const_iterator it = j.cbegin(); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + it--; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + --it; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorUnsignedTest, ConstCBeginEnd) +{ + json::const_iterator it = j_const.cbegin(); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + it--; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + --it; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); +} +#if 0 +TEST_F(JsonIteratorUnsignedTest, RBeginEnd) +{ + json::reverse_iterator it = j.rbegin(); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + it--; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + --it; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorUnsignedTest, CRBeginEnd) +{ + json::const_reverse_iterator it = j.crbegin(); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + it--; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + --it; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorUnsignedTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it = j_const.crbegin(); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + it--; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + --it; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); +} +#endif +TEST_F(JsonIteratorUnsignedTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(it.value(), json(23)); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(cit.value(), json(23)); +#if 0 + auto rit = j.rend(); + auto crit = j.crend(); + EXPECT_THROW_MSG(rit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(rit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(crit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(crit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#endif +} + +class JsonIteratorFloatTest : public ::testing::Test { + public: + JsonIteratorFloatTest() : j_const(j) {} + + protected: + json j = 23.42; + json j_const; +}; + +TEST_F(JsonIteratorFloatTest, BeginEnd) +{ + json::iterator it = j.begin(); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + it--; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.begin()); + EXPECT_EQ(it, j.end()); + + --it; + EXPECT_EQ(it, j.begin()); + EXPECT_NE(it, j.end()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorFloatTest, ConstBeginEnd) +{ + json::const_iterator it = j_const.begin(); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + it--; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.begin()); + EXPECT_EQ(it, j_const.end()); + + --it; + EXPECT_EQ(it, j_const.begin()); + EXPECT_NE(it, j_const.end()); + EXPECT_EQ(*it, j_const); +} + +TEST_F(JsonIteratorFloatTest, CBeginEnd) +{ + json::const_iterator it = j.cbegin(); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + it--; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.cbegin()); + EXPECT_EQ(it, j.cend()); + + --it; + EXPECT_EQ(it, j.cbegin()); + EXPECT_NE(it, j.cend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorFloatTest, ConstCBeginEnd) +{ + json::const_iterator it = j_const.cbegin(); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + it--; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.cbegin()); + EXPECT_EQ(it, j_const.cend()); + + --it; + EXPECT_EQ(it, j_const.cbegin()); + EXPECT_NE(it, j_const.cend()); + EXPECT_EQ(*it, j_const); +} +#if 0 +TEST_F(JsonIteratorFloatTest, RBeginEnd) +{ + json::reverse_iterator it = j.rbegin(); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + it--; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.rbegin()); + EXPECT_EQ(it, j.rend()); + + --it; + EXPECT_EQ(it, j.rbegin()); + EXPECT_NE(it, j.rend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorFloatTest, CRBeginEnd) +{ + json::const_reverse_iterator it = j.crbegin(); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + it++; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + it--; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); + + ++it; + EXPECT_NE(it, j.crbegin()); + EXPECT_EQ(it, j.crend()); + + --it; + EXPECT_EQ(it, j.crbegin()); + EXPECT_NE(it, j.crend()); + EXPECT_EQ(*it, j); +} + +TEST_F(JsonIteratorFloatTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it = j_const.crbegin(); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + it++; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + it--; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); + + ++it; + EXPECT_NE(it, j_const.crbegin()); + EXPECT_EQ(it, j_const.crend()); + + --it; + EXPECT_EQ(it, j_const.crbegin()); + EXPECT_NE(it, j_const.crend()); + EXPECT_EQ(*it, j_const); +} +#endif +TEST_F(JsonIteratorFloatTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(it.value(), json(23.42)); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_EQ(cit.value(), json(23.42)); +#if 0 + auto rit = j.rend(); + auto crit = j.crend(); + EXPECT_THROW_MSG(rit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(rit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(crit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(crit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#endif +} + +class JsonIteratorNullTest : public ::testing::Test { + public: + JsonIteratorNullTest() : j_const(j) {} + + protected: + json j = nullptr; + json j_const; +}; + +TEST_F(JsonIteratorNullTest, BeginEnd) +{ + json::iterator it = j.begin(); + EXPECT_EQ(it, j.end()); +} + +TEST_F(JsonIteratorNullTest, ConstBeginEnd) +{ + json::const_iterator it_begin = j_const.begin(); + json::const_iterator it_end = j_const.end(); + EXPECT_EQ(it_begin, it_end); +} + +TEST_F(JsonIteratorNullTest, CBeginEnd) +{ + json::const_iterator it_begin = j.cbegin(); + json::const_iterator it_end = j.cend(); + EXPECT_EQ(it_begin, it_end); +} + +TEST_F(JsonIteratorNullTest, ConstCBeginEnd) +{ + json::const_iterator it_begin = j_const.cbegin(); + json::const_iterator it_end = j_const.cend(); + EXPECT_EQ(it_begin, it_end); +} +#if 0 +TEST_F(JsonIteratorNullTest, RBeginEnd) +{ + json::reverse_iterator it = j.rbegin(); + EXPECT_EQ(it, j.rend()); +} + +TEST_F(JsonIteratorNullTest, CRBeginEnd) +{ + json::const_reverse_iterator it = j.crbegin(); + EXPECT_EQ(it, j.crend()); +} + +TEST_F(JsonIteratorNullTest, ConstCRBeginEnd) +{ + json::const_reverse_iterator it = j_const.crbegin(); + EXPECT_EQ(it, j_const.crend()); +} +#endif +TEST_F(JsonIteratorNullTest, KeyValue) +{ + auto it = j.begin(); + auto cit = j_const.cbegin(); + EXPECT_THROW_MSG(it.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(it.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(cit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(cit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#if 0 + auto rit = j.rend(); + auto crit = j.crend(); + EXPECT_THROW_MSG(rit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(rit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(crit.key(), json::invalid_iterator, + "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators"); + EXPECT_THROW_MSG(crit.value(), json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +#endif +} + +TEST(JsonIteratorConstConversionTest, Boolean) +{ + json j = true; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, String) +{ + json j = "hello world"; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, Array) +{ + json j = {1, 2, 3}; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, Object) +{ + json j = {{"A", 1}, {"B", 2}, {"C", 3}}; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, Integer) +{ + json j = 23; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, Unsigned) +{ + json j = 23u; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, Float) +{ + json j = 23.42; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} + +TEST(JsonIteratorConstConversionTest, Null) +{ + json j = nullptr; + json::const_iterator it = j.begin(); + EXPECT_EQ(it, j.cbegin()); + it = j.begin(); + EXPECT_EQ(it, j.cbegin()); +} diff --git a/src/test/native/cpp/json/unit-iterators2.cpp b/src/test/native/cpp/json/unit-iterators2.cpp new file mode 100644 index 0000000000..69a4dac571 --- /dev/null +++ b/src/test/native/cpp/json/unit-iterators2.cpp @@ -0,0 +1,899 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonIteratorTest, Comparisons) +{ + json j_values = {nullptr, true, 42, 42u, 23.23, {{"one", 1}, {"two", 2}}, {1, 2, 3, 4, 5}, "Hello, world"}; + + for (json& j : j_values) + { + SCOPED_TRACE(j.dump()); + auto it1 = j.begin(); + auto it2 = j.begin(); + auto it3 = j.begin(); + ++it2; + ++it3; + ++it3; + auto it1_c = j.cbegin(); + auto it2_c = j.cbegin(); + auto it3_c = j.cbegin(); + ++it2_c; + ++it3_c; + ++it3_c; + + // comparison: equal + { + EXPECT_TRUE(it1 == it1); + EXPECT_FALSE(it1 == it2); + EXPECT_FALSE(it1 == it3); + EXPECT_FALSE(it2 == it3); + EXPECT_TRUE(it1_c == it1_c); + EXPECT_FALSE(it1_c == it2_c); + EXPECT_FALSE(it1_c == it3_c); + EXPECT_FALSE(it2_c == it3_c); + } + + // comparison: not equal + { + // check definition + EXPECT_EQ( (it1 != it1), !(it1 == it1) ); + EXPECT_EQ( (it1 != it2), !(it1 == it2) ); + EXPECT_EQ( (it1 != it3), !(it1 == it3) ); + EXPECT_EQ( (it2 != it3), !(it2 == it3) ); + EXPECT_EQ( (it1_c != it1_c), !(it1_c == it1_c) ); + EXPECT_EQ( (it1_c != it2_c), !(it1_c == it2_c) ); + EXPECT_EQ( (it1_c != it3_c), !(it1_c == it3_c) ); + EXPECT_EQ( (it2_c != it3_c), !(it2_c == it3_c) ); + } + + // comparison: smaller + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 < it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 < it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 < it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 < it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c < it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c < it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c < it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c < it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + EXPECT_FALSE(it1 < it1); + EXPECT_TRUE(it1 < it2); + EXPECT_TRUE(it1 < it3); + EXPECT_TRUE(it2 < it3); + EXPECT_FALSE(it1_c < it1_c); + EXPECT_TRUE(it1_c < it2_c); + EXPECT_TRUE(it1_c < it3_c); + EXPECT_TRUE(it2_c < it3_c); + } + } + + // comparison: less than or equal + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 <= it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 <= it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 <= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 <= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c <= it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c <= it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c <= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c <= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + // check definition + EXPECT_EQ( (it1 <= it1), !(it1 < it1) ); + EXPECT_EQ( (it1 <= it2), !(it2 < it1) ); + EXPECT_EQ( (it1 <= it3), !(it3 < it1) ); + EXPECT_EQ( (it2 <= it3), !(it3 < it2) ); + EXPECT_EQ( (it1_c <= it1_c), !(it1_c < it1_c) ); + EXPECT_EQ( (it1_c <= it2_c), !(it2_c < it1_c) ); + EXPECT_EQ( (it1_c <= it3_c), !(it3_c < it1_c) ); + EXPECT_EQ( (it2_c <= it3_c), !(it3_c < it2_c) ); + } + } + + // comparison: greater than + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 > it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 > it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 > it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 > it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c > it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c > it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c > it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c > it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + // check definition + EXPECT_EQ( (it1 > it1), (it1 < it1) ); + EXPECT_EQ( (it1 > it2), (it2 < it1) ); + EXPECT_EQ( (it1 > it3), (it3 < it1) ); + EXPECT_EQ( (it2 > it3), (it3 < it2) ); + EXPECT_EQ( (it1_c > it1_c), (it1_c < it1_c) ); + EXPECT_EQ( (it1_c > it2_c), (it2_c < it1_c) ); + EXPECT_EQ( (it1_c > it3_c), (it3_c < it1_c) ); + EXPECT_EQ( (it2_c > it3_c), (it3_c < it2_c) ); + } + } + + // comparison: greater than or equal + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 >= it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 >= it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 >= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 >= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c >= it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c >= it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c >= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c >= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + // check definition + EXPECT_EQ( (it1 >= it1), !(it1 < it1) ); + EXPECT_EQ( (it1 >= it2), !(it1 < it2) ); + EXPECT_EQ( (it1 >= it3), !(it1 < it3) ); + EXPECT_EQ( (it2 >= it3), !(it2 < it3) ); + EXPECT_EQ( (it1_c >= it1_c), !(it1_c < it1_c) ); + EXPECT_EQ( (it1_c >= it2_c), !(it1_c < it2_c) ); + EXPECT_EQ( (it1_c >= it3_c), !(it1_c < it3_c) ); + EXPECT_EQ( (it2_c >= it3_c), !(it2_c < it3_c) ); + } + } + } + + // check exceptions if different objects are compared + for (auto j : j_values) + { + for (auto k : j_values) + { + if (j != k) + { + EXPECT_THROW_MSG(j.begin() == k.begin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + EXPECT_THROW_MSG(j.cbegin() == k.cbegin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + + EXPECT_THROW_MSG(j.begin() < k.begin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + EXPECT_THROW_MSG(j.cbegin() < k.cbegin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + } + } + } +} + +class JsonIteratorArithmeticTest : public ::testing::Test { + protected: + json j_object = {{"one", 1}, {"two", 2}, {"three", 3}}; + json j_array = {1, 2, 3, 4, 5, 6}; + json j_null = nullptr; + json j_value = 42; +}; + +TEST_F(JsonIteratorArithmeticTest, AddSubObject) +{ + { + auto it = j_object.begin(); + EXPECT_THROW_MSG(it += 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(it += 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.begin(); + EXPECT_THROW_MSG(it + 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(it + 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.begin(); + EXPECT_THROW_MSG(1 + it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(1 + it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.begin(); + EXPECT_THROW_MSG(it -= 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(it -= 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.begin(); + EXPECT_THROW_MSG(it - 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(it - 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.begin(); + EXPECT_THROW_MSG(it - it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(it - it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } +} + +TEST_F(JsonIteratorArithmeticTest, AddSubArray) +{ + auto it = j_array.begin(); + it += 3; + EXPECT_EQ((j_array.begin() + 3), it); + EXPECT_EQ(json::iterator(3 + j_array.begin()), it); + EXPECT_EQ((it - 3), j_array.begin()); + EXPECT_EQ((it - j_array.begin()), 3); + EXPECT_EQ(*it, json(4)); + it -= 2; + EXPECT_EQ(*it, json(2)); +} + +TEST_F(JsonIteratorArithmeticTest, AddSubArrayConst) +{ + auto it = j_array.cbegin(); + it += 3; + EXPECT_EQ((j_array.cbegin() + 3), it); + EXPECT_EQ(json::const_iterator(3 + j_array.cbegin()), it); + EXPECT_EQ((it - 3), j_array.cbegin()); + EXPECT_EQ((it - j_array.cbegin()), 3); + EXPECT_EQ(*it, json(4)); + it -= 2; + EXPECT_EQ(*it, json(2)); +} + +TEST_F(JsonIteratorArithmeticTest, AddSubNull) +{ + auto it = j_null.begin(); + it += 3; + EXPECT_EQ((j_null.begin() + 3), it); + EXPECT_EQ(json::iterator(3 + j_null.begin()), it); + EXPECT_EQ((it - 3), j_null.begin()); + EXPECT_EQ((it - j_null.begin()), 3); + EXPECT_NE(it, j_null.end()); + it -= 3; + EXPECT_EQ(it, j_null.end()); +} + +TEST_F(JsonIteratorArithmeticTest, AddSubNullConst) +{ + auto it = j_null.cbegin(); + it += 3; + EXPECT_EQ((j_null.cbegin() + 3), it); + EXPECT_EQ(json::const_iterator(3 + j_null.cbegin()), it); + EXPECT_EQ((it - 3), j_null.cbegin()); + EXPECT_EQ((it - j_null.cbegin()), 3); + EXPECT_NE(it, j_null.cend()); + it -= 3; + EXPECT_EQ(it, j_null.cend()); +} + +TEST_F(JsonIteratorArithmeticTest, AddSubValue) +{ + auto it = j_value.begin(); + it += 3; + EXPECT_EQ((j_value.begin() + 3), it); + EXPECT_EQ(json::iterator(3 + j_value.begin()), it); + EXPECT_EQ((it - 3), j_value.begin()); + EXPECT_EQ((it - j_value.begin()), 3); + EXPECT_NE(it, j_value.end()); + it -= 3; + EXPECT_EQ(*it, json(42)); +} + +TEST_F(JsonIteratorArithmeticTest, AddSubValueConst) +{ + auto it = j_value.cbegin(); + it += 3; + EXPECT_EQ((j_value.cbegin() + 3), it); + EXPECT_EQ(json::const_iterator(3 + j_value.cbegin()), it); + EXPECT_EQ((it - 3), j_value.cbegin()); + EXPECT_EQ((it - j_value.cbegin()), 3); + EXPECT_NE(it, j_value.cend()); + it -= 3; + EXPECT_EQ(*it, json(42)); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptObject) +{ + auto it = j_object.begin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.208] cannot use operator[] for object iterators"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.208] cannot use operator[] for object iterators"); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptObjectConst) +{ + auto it = j_object.cbegin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.208] cannot use operator[] for object iterators"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.208] cannot use operator[] for object iterators"); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptArray) +{ + auto it = j_array.begin(); + EXPECT_EQ(it[0], json(1)); + EXPECT_EQ(it[1], json(2)); + EXPECT_EQ(it[2], json(3)); + EXPECT_EQ(it[3], json(4)); + EXPECT_EQ(it[4], json(5)); + EXPECT_EQ(it[5], json(6)); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptArrayConst) +{ + auto it = j_array.cbegin(); + EXPECT_EQ(it[0], json(1)); + EXPECT_EQ(it[1], json(2)); + EXPECT_EQ(it[2], json(3)); + EXPECT_EQ(it[3], json(4)); + EXPECT_EQ(it[4], json(5)); + EXPECT_EQ(it[5], json(6)); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptNull) +{ + auto it = j_null.begin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptNullConst) +{ + auto it = j_null.cbegin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptValue) +{ + auto it = j_value.begin(); + EXPECT_EQ(it[0], json(42)); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST_F(JsonIteratorArithmeticTest, SubscriptValueConst) +{ + auto it = j_value.cbegin(); + EXPECT_EQ(it[0], json(42)); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} +#if 0 +TEST(JsonReverseIteratorTest, Comparisons) +{ + json j_values = {nullptr, true, 42, 42u, 23.23, {{"one", 1}, {"two", 2}}, {1, 2, 3, 4, 5}, "Hello, world"}; + + for (json& j : j_values) + { + SCOPED_TRACE(j.dump()); + auto it1 = j.rbegin(); + auto it2 = j.rbegin(); + auto it3 = j.rbegin(); + ++it2; + ++it3; + ++it3; + auto it1_c = j.crbegin(); + auto it2_c = j.crbegin(); + auto it3_c = j.crbegin(); + ++it2_c; + ++it3_c; + ++it3_c; + + // comparison: equal + { + EXPECT_TRUE(it1 == it1); + EXPECT_FALSE(it1 == it2); + EXPECT_FALSE(it1 == it3); + EXPECT_FALSE(it2 == it3); + EXPECT_TRUE(it1_c == it1_c); + EXPECT_FALSE(it1_c == it2_c); + EXPECT_FALSE(it1_c == it3_c); + EXPECT_FALSE(it2_c == it3_c); + } + + // comparison: not equal + { + // check definition + EXPECT_EQ( (it1 != it1), !(it1 == it1) ); + EXPECT_EQ( (it1 != it2), !(it1 == it2) ); + EXPECT_EQ( (it1 != it3), !(it1 == it3) ); + EXPECT_EQ( (it2 != it3), !(it2 == it3) ); + EXPECT_EQ( (it1_c != it1_c), !(it1_c == it1_c) ); + EXPECT_EQ( (it1_c != it2_c), !(it1_c == it2_c) ); + EXPECT_EQ( (it1_c != it3_c), !(it1_c == it3_c) ); + EXPECT_EQ( (it2_c != it3_c), !(it2_c == it3_c) ); + } + + // comparison: smaller + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 < it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 < it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 < it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 < it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c < it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c < it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c < it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c < it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + EXPECT_FALSE(it1 < it1); + EXPECT_TRUE(it1 < it2); + EXPECT_TRUE(it1 < it3); + EXPECT_TRUE(it2 < it3); + EXPECT_FALSE(it1_c < it1_c); + EXPECT_TRUE(it1_c < it2_c); + EXPECT_TRUE(it1_c < it3_c); + EXPECT_TRUE(it2_c < it3_c); + } + } + + // comparison: less than or equal + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 <= it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 <= it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 <= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 <= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c <= it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c <= it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c <= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c <= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + // check definition + EXPECT_EQ( (it1 <= it1), !(it1 < it1) ); + EXPECT_EQ( (it1 <= it2), !(it2 < it1) ); + EXPECT_EQ( (it1 <= it3), !(it3 < it1) ); + EXPECT_EQ( (it2 <= it3), !(it3 < it2) ); + EXPECT_EQ( (it1_c <= it1_c), !(it1_c < it1_c) ); + EXPECT_EQ( (it1_c <= it2_c), !(it2_c < it1_c) ); + EXPECT_EQ( (it1_c <= it3_c), !(it3_c < it1_c) ); + EXPECT_EQ( (it2_c <= it3_c), !(it3_c < it2_c) ); + } + } + + // comparison: greater than + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 > it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 > it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 > it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 > it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c > it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c > it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c > it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c > it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + // check definition + EXPECT_EQ( (it1 > it1), (it1 < it1) ); + EXPECT_EQ( (it1 > it2), (it2 < it1) ); + EXPECT_EQ( (it1 > it3), (it3 < it1) ); + EXPECT_EQ( (it2 > it3), (it3 < it2) ); + EXPECT_EQ( (it1_c > it1_c), (it1_c < it1_c) ); + EXPECT_EQ( (it1_c > it2_c), (it2_c < it1_c) ); + EXPECT_EQ( (it1_c > it3_c), (it3_c < it1_c) ); + EXPECT_EQ( (it2_c > it3_c), (it3_c < it2_c) ); + } + } + + // comparison: greater than or equal + { + if (j.type() == json::value_t::object) + { + EXPECT_THROW_MSG(it1 >= it1, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 >= it2, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2 >= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1 >= it3, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c >= it1_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c >= it2_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it2_c >= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + EXPECT_THROW_MSG(it1_c >= it3_c, json::invalid_iterator, + "[json.exception.invalid_iterator.213] cannot compare order of object iterators"); + } + else + { + // check definition + EXPECT_EQ( (it1 >= it1), !(it1 < it1) ); + EXPECT_EQ( (it1 >= it2), !(it1 < it2) ); + EXPECT_EQ( (it1 >= it3), !(it1 < it3) ); + EXPECT_EQ( (it2 >= it3), !(it2 < it3) ); + EXPECT_EQ( (it1_c >= it1_c), !(it1_c < it1_c) ); + EXPECT_EQ( (it1_c >= it2_c), !(it1_c < it2_c) ); + EXPECT_EQ( (it1_c >= it3_c), !(it1_c < it3_c) ); + EXPECT_EQ( (it2_c >= it3_c), !(it2_c < it3_c) ); + } + } + } + + // check exceptions if different objects are compared + for (auto j : j_values) + { + for (auto k : j_values) + { + if (j != k) + { + EXPECT_THROW_MSG(j.rbegin() == k.rbegin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + EXPECT_THROW_MSG(j.crbegin() == k.crbegin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + + EXPECT_THROW_MSG(j.rbegin() < k.rbegin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + EXPECT_THROW_MSG(j.crbegin() < k.crbegin(), json::invalid_iterator, + "[json.exception.invalid_iterator.212] cannot compare iterators of different containers"); + } + } + } +} + +class JsonReverseIteratorArithmeticTest : public ::testing::Test { + protected: + json j_object = {{"one", 1}, {"two", 2}, {"three", 3}}; + json j_array = {1, 2, 3, 4, 5, 6}; + json j_null = nullptr; + json j_value = 42; +}; + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubObject) +{ + { + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(it += 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(it += 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(it + 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(it + 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(1 + it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(1 + it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(it -= 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(it -= 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(it - 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(it - 1, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(it - it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } + { + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(it - it, json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + } +} + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubArray) +{ + auto it = j_array.rbegin(); + it += 3; + EXPECT_EQ((j_array.rbegin() + 3), it); + EXPECT_EQ(json::reverse_iterator(3 + j_array.rbegin()), it); + EXPECT_EQ((it - 3), j_array.rbegin()); + EXPECT_EQ((it - j_array.rbegin()), 3); + EXPECT_EQ(*it, json(3)); + it -= 2; + EXPECT_EQ(*it, json(5)); +} + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubArrayConst) +{ + auto it = j_array.crbegin(); + it += 3; + EXPECT_EQ((j_array.crbegin() + 3), it); + EXPECT_EQ(json::const_reverse_iterator(3 + j_array.crbegin()), it); + EXPECT_EQ((it - 3), j_array.crbegin()); + EXPECT_EQ((it - j_array.crbegin()), 3); + EXPECT_EQ(*it, json(3)); + it -= 2; + EXPECT_EQ(*it, json(5)); +} + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubNull) +{ + auto it = j_null.rbegin(); + it += 3; + EXPECT_EQ((j_null.rbegin() + 3), it); + EXPECT_EQ(json::reverse_iterator(3 + j_null.rbegin()), it); + EXPECT_EQ((it - 3), j_null.rbegin()); + EXPECT_EQ((it - j_null.rbegin()), 3); + EXPECT_NE(it, j_null.rend()); + it -= 3; + EXPECT_EQ(it, j_null.rend()); +} + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubNullConst) +{ + auto it = j_null.crbegin(); + it += 3; + EXPECT_EQ((j_null.crbegin() + 3), it); + EXPECT_EQ(json::const_reverse_iterator(3 + j_null.crbegin()), it); + EXPECT_EQ((it - 3), j_null.crbegin()); + EXPECT_EQ((it - j_null.crbegin()), 3); + EXPECT_NE(it, j_null.crend()); + it -= 3; + EXPECT_EQ(it, j_null.crend()); +} + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubValue) +{ + auto it = j_value.rbegin(); + it += 3; + EXPECT_EQ((j_value.rbegin() + 3), it); + EXPECT_EQ(json::reverse_iterator(3 + j_value.rbegin()), it); + EXPECT_EQ((it - 3), j_value.rbegin()); + EXPECT_EQ((it - j_value.rbegin()), 3); + EXPECT_NE(it, j_value.rend()); + it -= 3; + EXPECT_EQ(*it, json(42)); +} + +TEST_F(JsonReverseIteratorArithmeticTest, AddSubValueConst) +{ + auto it = j_value.crbegin(); + it += 3; + EXPECT_EQ((j_value.crbegin() + 3), it); + EXPECT_EQ(json::const_reverse_iterator(3 + j_value.crbegin()), it); + EXPECT_EQ((it - 3), j_value.crbegin()); + EXPECT_EQ((it - j_value.crbegin()), 3); + EXPECT_NE(it, j_value.crend()); + it -= 3; + EXPECT_EQ(*it, json(42)); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptObject) +{ + auto it = j_object.rbegin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptObjectConst) +{ + auto it = j_object.crbegin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.209] cannot use offsets with object iterators"); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptArray) +{ + auto it = j_array.rbegin(); + EXPECT_EQ(it[0], json(6)); + EXPECT_EQ(it[1], json(5)); + EXPECT_EQ(it[2], json(4)); + EXPECT_EQ(it[3], json(3)); + EXPECT_EQ(it[4], json(2)); + EXPECT_EQ(it[5], json(1)); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptArrayConst) +{ + auto it = j_array.crbegin(); + EXPECT_EQ(it[0], json(6)); + EXPECT_EQ(it[1], json(5)); + EXPECT_EQ(it[2], json(4)); + EXPECT_EQ(it[3], json(3)); + EXPECT_EQ(it[4], json(2)); + EXPECT_EQ(it[5], json(1)); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptNull) +{ + auto it = j_null.rbegin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptNullConst) +{ + auto it = j_null.crbegin(); + EXPECT_THROW_MSG(it[0], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptValue) +{ + auto it = j_value.rbegin(); + EXPECT_EQ(it[0], json(42)); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} + +TEST_F(JsonReverseIteratorArithmeticTest, SubscriptValueConst) +{ + auto it = j_value.crbegin(); + EXPECT_EQ(it[0], json(42)); + EXPECT_THROW_MSG(it[1], json::invalid_iterator, + "[json.exception.invalid_iterator.214] cannot get value"); +} +#endif diff --git a/src/test/native/cpp/json/unit-json.h b/src/test/native/cpp/json/unit-json.h new file mode 100644 index 0000000000..9e7ddd29c1 --- /dev/null +++ b/src/test/native/cpp/json/unit-json.h @@ -0,0 +1,88 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/#ifndef UNIT_JSON_H_ +#define UNIT_JSON_H_ + +#include + +#include "support/json.h" + +namespace wpi { + +inline +void PrintTo(const json& j, std::ostream* os) { + *os << j.dump(); +} + +class JsonTest { + public: + static const json::json_value& GetValue(const json& j) { + return j.m_value; + } + static json::pointer GetObject(json::iterator it) { + return it.m_object; + } + static json::const_pointer GetObject(json::const_iterator it) { + return it.m_object; + } + static std::string pop_back(json::json_pointer& p) { + return p.pop_back(); + } + static json::json_pointer top(const json::json_pointer& p) { + return p.top(); + } +}; + +} // namespace wpi + +// clang warns on TEST_THROW_MSG(x == y, ...) saying the result is unused. +// suppress this warning. +#if defined(__clang__) +#pragma GCC diagnostic ignored "-Wunused-comparison" +#endif + +// variant of GTEST_TEST_THROW_ that also checks the exception's message. +#define TEST_THROW_MSG(statement, expected_exception, expected_msg, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::ConstCharPtr gtest_msg = "") { \ + bool gtest_caught_expected = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + catch (expected_exception const& gtest_ex) { \ + gtest_caught_expected = true; \ + if (::std::string(gtest_ex.what()) != expected_msg) { \ + ::testing::AssertionResult gtest_ar = ::testing::AssertionFailure(); \ + gtest_ar \ + << "Expected: " #statement " throws an exception with message \"" \ + << expected_msg "\".\n Actual: it throws message \"" \ + << gtest_ex.what() << "\"."; \ + fail(gtest_ar.failure_message()); \ + } \ + } \ + catch (...) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws a different type."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + if (!gtest_caught_expected) { \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws nothing."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ + fail(gtest_msg.value) + +#define EXPECT_THROW_MSG(statement, expected_exception, expected_msg) \ + TEST_THROW_MSG(statement, expected_exception, expected_msg, GTEST_NONFATAL_FAILURE_) + +#define ASSERT_THROW_MSG(statement, expected_exception, expected_msg) \ + TEST_THROW_MSG(statement, expected_exception, expected_msg, GTEST_FATAL_FAILURE_) + +#endif diff --git a/src/test/native/cpp/json/unit-json_pointer.cpp b/src/test/native/cpp/json/unit-json_pointer.cpp new file mode 100644 index 0000000000..d54fd6afe7 --- /dev/null +++ b/src/test/native/cpp/json/unit-json_pointer.cpp @@ -0,0 +1,402 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; +using wpi::JsonTest; + +TEST(JsonPointerTest, Errors) +{ + EXPECT_THROW_MSG(json::json_pointer("foo"), json::parse_error, + "[json.exception.parse_error.107] parse error at 1: JSON pointer must be empty or begin with '/' - was: 'foo'"); + + EXPECT_THROW_MSG(json::json_pointer("/~~"), json::parse_error, + "[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'"); + + EXPECT_THROW_MSG(json::json_pointer("/~"), json::parse_error, + "[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'"); + + json::json_pointer p; + EXPECT_THROW_MSG(JsonTest::top(p), json::out_of_range, + "[json.exception.out_of_range.405] JSON pointer has no parent"); + EXPECT_THROW_MSG(JsonTest::pop_back(p), json::out_of_range, + "[json.exception.out_of_range.405] JSON pointer has no parent"); +} + +// examples from RFC 6901 +TEST(JsonPointerTest, AccessNonConst) +{ + json j = R"( + { + "foo": ["bar", "baz"], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 + } + )"_json; + + // the whole document + EXPECT_EQ(j[json::json_pointer()], j); + EXPECT_EQ(j[json::json_pointer("")], j); + + // array access + EXPECT_EQ(j[json::json_pointer("/foo")], j["foo"]); + EXPECT_EQ(j[json::json_pointer("/foo/0")], j["foo"][0]); + EXPECT_EQ(j[json::json_pointer("/foo/1")], j["foo"][1]); + EXPECT_EQ(j["/foo/1"_json_pointer], j["foo"][1]); + + // checked array access + EXPECT_EQ(j.at(json::json_pointer("/foo/0")), j["foo"][0]); + EXPECT_EQ(j.at(json::json_pointer("/foo/1")), j["foo"][1]); + + // empty string access + EXPECT_EQ(j[json::json_pointer("/")], j[""]); + + // other cases + EXPECT_EQ(j[json::json_pointer("/ ")], j[" "]); + EXPECT_EQ(j[json::json_pointer("/c%d")], j["c%d"]); + EXPECT_EQ(j[json::json_pointer("/e^f")], j["e^f"]); + EXPECT_EQ(j[json::json_pointer("/g|h")], j["g|h"]); + EXPECT_EQ(j[json::json_pointer("/i\\j")], j["i\\j"]); + EXPECT_EQ(j[json::json_pointer("/k\"l")], j["k\"l"]); + + // checked access + EXPECT_EQ(j.at(json::json_pointer("/ ")), j[" "]); + EXPECT_EQ(j.at(json::json_pointer("/c%d")), j["c%d"]); + EXPECT_EQ(j.at(json::json_pointer("/e^f")), j["e^f"]); + EXPECT_EQ(j.at(json::json_pointer("/g|h")), j["g|h"]); + EXPECT_EQ(j.at(json::json_pointer("/i\\j")), j["i\\j"]); + EXPECT_EQ(j.at(json::json_pointer("/k\"l")), j["k\"l"]); + + // escaped access + EXPECT_EQ(j[json::json_pointer("/a~1b")], j["a/b"]); + EXPECT_EQ(j[json::json_pointer("/m~0n")], j["m~n"]); + + // unescaped access + // access to nonexisting values yield object creation + EXPECT_NO_THROW(j[json::json_pointer("/a/b")] = 42); + EXPECT_EQ(j["a"]["b"], json(42)); + EXPECT_NO_THROW(j[json::json_pointer("/a/c/1")] = 42); + EXPECT_EQ(j["a"]["c"], json({nullptr, 42})); + EXPECT_NO_THROW(j[json::json_pointer("/a/d/-")] = 42); + EXPECT_EQ(j["a"]["d"], json::array({42})); + // "/a/b" works for JSON {"a": {"b": 42}} + EXPECT_EQ(json({{"a", {{"b", 42}}}})[json::json_pointer("/a/b")], json(42)); + + // unresolved access + json j_primitive = 1; + EXPECT_THROW_MSG(j_primitive["/foo"_json_pointer], json::out_of_range, + "[json.exception.out_of_range.404] unresolved reference token 'foo'"); + EXPECT_THROW_MSG(j_primitive.at("/foo"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.404] unresolved reference token 'foo'"); +} + +TEST(JsonPointerTest, AccessConst) +{ + const json j = R"( + { + "foo": ["bar", "baz"], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 + } + )"_json; + + // the whole document + EXPECT_EQ(j[json::json_pointer()], j); + EXPECT_EQ(j[json::json_pointer("")], j); + + // array access + EXPECT_EQ(j[json::json_pointer("/foo")], j["foo"]); + EXPECT_EQ(j[json::json_pointer("/foo/0")], j["foo"][0]); + EXPECT_EQ(j[json::json_pointer("/foo/1")], j["foo"][1]); + EXPECT_EQ(j["/foo/1"_json_pointer], j["foo"][1]); + + // checked array access + EXPECT_EQ(j.at(json::json_pointer("/foo/0")), j["foo"][0]); + EXPECT_EQ(j.at(json::json_pointer("/foo/1")), j["foo"][1]); + + // empty string access + EXPECT_EQ(j[json::json_pointer("/")], j[""]); + + // other cases + EXPECT_EQ(j[json::json_pointer("/ ")], j[" "]); + EXPECT_EQ(j[json::json_pointer("/c%d")], j["c%d"]); + EXPECT_EQ(j[json::json_pointer("/e^f")], j["e^f"]); + EXPECT_EQ(j[json::json_pointer("/g|h")], j["g|h"]); + EXPECT_EQ(j[json::json_pointer("/i\\j")], j["i\\j"]); + EXPECT_EQ(j[json::json_pointer("/k\"l")], j["k\"l"]); + + // checked access + EXPECT_EQ(j.at(json::json_pointer("/ ")), j[" "]); + EXPECT_EQ(j.at(json::json_pointer("/c%d")), j["c%d"]); + EXPECT_EQ(j.at(json::json_pointer("/e^f")), j["e^f"]); + EXPECT_EQ(j.at(json::json_pointer("/g|h")), j["g|h"]); + EXPECT_EQ(j.at(json::json_pointer("/i\\j")), j["i\\j"]); + EXPECT_EQ(j.at(json::json_pointer("/k\"l")), j["k\"l"]); + + // escaped access + EXPECT_EQ(j[json::json_pointer("/a~1b")], j["a/b"]); + EXPECT_EQ(j[json::json_pointer("/m~0n")], j["m~n"]); + + // unescaped access + EXPECT_THROW_MSG(j.at(json::json_pointer("/a/b")), json::out_of_range, + "[json.exception.out_of_range.403] key 'a' not found"); + + // unresolved access + const json j_primitive = 1; + EXPECT_THROW_MSG(j_primitive["/foo"_json_pointer], json::out_of_range, + "[json.exception.out_of_range.404] unresolved reference token 'foo'"); + EXPECT_THROW_MSG(j_primitive.at("/foo"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.404] unresolved reference token 'foo'"); +} + +TEST(JsonPointerTest, UserStringLiteral) +{ + json j = R"( + { + "foo": ["bar", "baz"], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 + } + )"_json; + + // the whole document + EXPECT_EQ(j[""_json_pointer], j); + + // array access + EXPECT_EQ(j["/foo"_json_pointer], j["foo"]); + EXPECT_EQ(j["/foo/0"_json_pointer], j["foo"][0]); + EXPECT_EQ(j["/foo/1"_json_pointer], j["foo"][1]); +} + +TEST(JsonPointerTest, ArrayNonConst) +{ + json j = {1, 2, 3}; + const json j_const = j; + + // check reading access + EXPECT_EQ(j["/0"_json_pointer], j[0]); + EXPECT_EQ(j["/1"_json_pointer], j[1]); + EXPECT_EQ(j["/2"_json_pointer], j[2]); + + // assign to existing index + j["/1"_json_pointer] = 13; + EXPECT_EQ(j[1], json(13)); + + // assign to nonexisting index + j["/3"_json_pointer] = 33; + EXPECT_EQ(j[3], json(33)); + + // assign to nonexisting index (with gap) + j["/5"_json_pointer] = 55; + EXPECT_EQ(j, json({1, 13, 3, 33, nullptr, 55})); + + // error with leading 0 + EXPECT_THROW_MSG(j["/01"_json_pointer], json::parse_error, + "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'"); + EXPECT_THROW_MSG(j_const["/01"_json_pointer], json::parse_error, + "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'"); + EXPECT_THROW_MSG(j.at("/01"_json_pointer), json::parse_error, + "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'"); + EXPECT_THROW_MSG(j_const.at("/01"_json_pointer), json::parse_error, + "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'"); + + // error with incorrect numbers + EXPECT_THROW_MSG(j["/one"_json_pointer] = 1, json::parse_error, + "[json.exception.parse_error.109] parse error: array index 'one' is not a number"); + EXPECT_THROW_MSG(j_const["/one"_json_pointer] == 1, json::parse_error, + "[json.exception.parse_error.109] parse error: array index 'one' is not a number"); + + EXPECT_THROW_MSG(j.at("/one"_json_pointer) = 1, json::parse_error, + "[json.exception.parse_error.109] parse error: array index 'one' is not a number"); + EXPECT_THROW_MSG(j_const.at("/one"_json_pointer) == 1, json::parse_error, + "[json.exception.parse_error.109] parse error: array index 'one' is not a number"); + + EXPECT_THROW_MSG(json({{"/list/0", 1}, {"/list/1", 2}, {"/list/three", 3}}).unflatten(), json::parse_error, + "[json.exception.parse_error.109] parse error: array index 'three' is not a number"); + + // assign to "-" + j["/-"_json_pointer] = 99; + EXPECT_EQ(j, json({1, 13, 3, 33, nullptr, 55, 99})); + + // error when using "-" in const object + EXPECT_THROW_MSG(j_const["/-"_json_pointer], json::out_of_range, + "[json.exception.out_of_range.402] array index '-' (3) is out of range"); + + // error when using "-" with at + EXPECT_THROW_MSG(j.at("/-"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.402] array index '-' (7) is out of range"); + EXPECT_THROW_MSG(j_const.at("/-"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.402] array index '-' (3) is out of range"); +} + +TEST(JsonPointerTest, ArrayConst) +{ + const json j = {1, 2, 3}; + + // check reading access + EXPECT_EQ(j["/0"_json_pointer], j[0]); + EXPECT_EQ(j["/1"_json_pointer], j[1]); + EXPECT_EQ(j["/2"_json_pointer], j[2]); + + // assign to nonexisting index + EXPECT_THROW_MSG(j.at("/3"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.401] array index 3 is out of range"); + + // assign to nonexisting index (with gap) + EXPECT_THROW_MSG(j.at("/5"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.401] array index 5 is out of range"); + + // assign to "-" + EXPECT_THROW_MSG(j["/-"_json_pointer], json::out_of_range, + "[json.exception.out_of_range.402] array index '-' (3) is out of range"); + EXPECT_THROW_MSG(j.at("/-"_json_pointer), json::out_of_range, + "[json.exception.out_of_range.402] array index '-' (3) is out of range"); +} + +TEST(JsonPointerTest, Flatten) +{ + json j = + { + {"pi", 3.141}, + {"happy", true}, + {"name", "Niels"}, + {"nothing", nullptr}, + { + "answer", { + {"everything", 42} + } + }, + {"list", {1, 0, 2}}, + { + "object", { + {"currency", "USD"}, + {"value", 42.99}, + {"", "empty string"}, + {"/", "slash"}, + {"~", "tilde"}, + {"~1", "tilde1"} + } + } + }; + + json j_flatten = + { + {"/pi", 3.141}, + {"/happy", true}, + {"/name", "Niels"}, + {"/nothing", nullptr}, + {"/answer/everything", 42}, + {"/list/0", 1}, + {"/list/1", 0}, + {"/list/2", 2}, + {"/object/currency", "USD"}, + {"/object/value", 42.99}, + {"/object/", "empty string"}, + {"/object/~1", "slash"}, + {"/object/~0", "tilde"}, + {"/object/~01", "tilde1"} + }; + + // check if flattened result is as expected + EXPECT_EQ(j.flatten(), j_flatten); + + // check if unflattened result is as expected + EXPECT_EQ(j_flatten.unflatten(), j); + + // error for nonobjects + EXPECT_THROW_MSG(json(1).unflatten(), json::type_error, + "[json.exception.type_error.314] only objects can be unflattened"); + + // error for nonprimitve values + EXPECT_THROW_MSG(json({{"/1", {1, 2, 3}}}).unflatten(), json::type_error, + "[json.exception.type_error.315] values in object must be primitive"); + + // error for conflicting values + json j_error = {{"", 42}, {"/foo", 17}}; + EXPECT_THROW_MSG(j_error.unflatten(), json::type_error, + "[json.exception.type_error.313] invalid value to unflatten"); + + // explicit roundtrip check + EXPECT_EQ(j.flatten().unflatten(), j); + + // roundtrip for primitive values + json j_null; + EXPECT_EQ(j_null.flatten().unflatten(), j_null); + json j_number = 42; + EXPECT_EQ(j_number.flatten().unflatten(), j_number); + json j_boolean = false; + EXPECT_EQ(j_boolean.flatten().unflatten(), j_boolean); + json j_string = "foo"; + EXPECT_EQ(j_string.flatten().unflatten(), j_string); + + // roundtrip for empty structured values (will be unflattened to null) + json j_array(json::value_t::array); + EXPECT_EQ(j_array.flatten().unflatten(), json()); + json j_object(json::value_t::object); + EXPECT_EQ(j_object.flatten().unflatten(), json()); +} + +TEST(JsonPointerTest, StringRepresentation) +{ + for (auto ptr : + {"", "/foo", "/foo/0", "/", "/a~1b", "/c%d", "/e^f", "/g|h", "/i\\j", "/k\"l", "/ ", "/m~0n" + }) + { + SCOPED_TRACE(ptr); + EXPECT_EQ(json::json_pointer(ptr).to_string(), ptr); + } +} diff --git a/src/test/native/cpp/json/unit-meta.cpp b/src/test/native/cpp/json/unit-meta.cpp new file mode 100644 index 0000000000..ecf77baa80 --- /dev/null +++ b/src/test/native/cpp/json/unit-meta.cpp @@ -0,0 +1,54 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2016 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonVersionTest, Meta) +{ + json j = json::meta(); + + EXPECT_EQ(j["name"], "WPI version of JSON for Modern C++"); + EXPECT_EQ(j["copyright"], "(C) 2013-2017 Niels Lohmann, (C) 2017 FIRST"); + EXPECT_EQ(j["url"], "https://github.com/wpilibsuite/wpiutil"); + EXPECT_EQ(j["version"], json( + { + {"string", "2.1.1"}, + {"major", 2}, + {"minor", 1}, + {"patch", 1} + })); +} diff --git a/src/test/native/cpp/json/unit-modifiers.cpp b/src/test/native/cpp/json/unit-modifiers.cpp new file mode 100644 index 0000000000..4abc628894 --- /dev/null +++ b/src/test/native/cpp/json/unit-modifiers.cpp @@ -0,0 +1,739 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonClearTest, Boolean) +{ + json j = true; + + j.clear(); + EXPECT_EQ(j, json(json::value_t::boolean)); +} + +TEST(JsonClearTest, String) +{ + json j = "hello world"; + + j.clear(); + EXPECT_EQ(j, json(json::value_t::string)); +} + +TEST(JsonClearTest, ArrayEmpty) +{ + json j = json::array(); + + j.clear(); + EXPECT_TRUE(j.empty()); + EXPECT_EQ(j, json(json::value_t::array)); +} + +TEST(JsonClearTest, ArrayFilled) +{ + json j = {1, 2, 3}; + + j.clear(); + EXPECT_TRUE(j.empty()); + EXPECT_EQ(j, json(json::value_t::array)); +} + +TEST(JsonClearTest, ObjectEmpty) +{ + json j = json::object(); + + j.clear(); + EXPECT_TRUE(j.empty()); + EXPECT_EQ(j, json(json::value_t::object)); +} + +TEST(JsonClearTest, ObjectFilled) +{ + json j = {{"one", 1}, {"two", 2}, {"three", 3}}; + + j.clear(); + EXPECT_TRUE(j.empty()); + EXPECT_EQ(j, json(json::value_t::object)); +} + +TEST(JsonClearTest, Integer) +{ + json j = 23; + + j.clear(); + EXPECT_EQ(j, json(json::value_t::number_integer)); +} + +TEST(JsonClearTest, Unsigned) +{ + json j = 23u; + + j.clear(); + EXPECT_EQ(j, json(json::value_t::number_integer)); +} + +TEST(JsonClearTest, Float) +{ + json j = 23.42; + + j.clear(); + EXPECT_EQ(j, json(json::value_t::number_float)); +} + +TEST(JsonClearTest, Null) +{ + json j = nullptr; + + j.clear(); + EXPECT_EQ(j, json(json::value_t::null)); +} + +TEST(JsonPushBackArrayTest, RRefNull) +{ + json j; + j.push_back(1); + j.push_back(2); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2})); +} + +TEST(JsonPushBackArrayTest, RRefArray) +{ + json j = {1, 2, 3}; + j.push_back("Hello"); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2, 3, "Hello"})); +} + +TEST(JsonPushBackArrayTest, RRefOther) +{ + json j = 1; + EXPECT_THROW_MSG(j.push_back("Hello"), json::type_error, + "[json.exception.type_error.308] cannot use push_back() with number"); +} + +TEST(JsonPushBackArrayTest, LRefNull) +{ + json j; + json k(1); + j.push_back(k); + j.push_back(k); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 1})); +} + +TEST(JsonPushBackArrayTest, LRefArray) +{ + json j = {1, 2, 3}; + json k("Hello"); + j.push_back(k); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2, 3, "Hello"})); +} + +TEST(JsonPushBackArrayTest, LRefOther) +{ + json j = 1; + json k("Hello"); + EXPECT_THROW_MSG(j.push_back(k), json::type_error, + "[json.exception.type_error.308] cannot use push_back() with number"); +} +#if 0 +TEST(JsonPushBackObjectTest, Null) +{ + json j; + j.push_back(json::object_t::value_type({"one", 1})); + j.push_back(json::object_t::value_type({"two", 2})); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j.size(), 2u); + EXPECT_EQ(j["one"], json(1)); + EXPECT_EQ(j["two"], json(2)); +} + +TEST(JsonPushBackObjectTest, Object) +{ + json j(json::value_t::object); + j.push_back(json::object_t::value_type({"one", 1})); + j.push_back(json::object_t::value_type({"two", 2})); + EXPECT_EQ(j.size(), 2u); + EXPECT_EQ(j["one"], json(1)); + EXPECT_EQ(j["two"], json(2)); +} + +TEST(JsonPushBackObjectTest, Other) +{ + json j = 1; + json k("Hello"); + EXPECT_THROW_MSG(j.push_back(json::object_t::value_type({"one", 1})), json::type_error, + "[json.exception.type_error.308] cannot use push_back() with number"); +} +#endif +TEST(JsonPushBackInitListTest, Null) +{ + json j; + j.push_back({"foo", "bar"}); + EXPECT_EQ(j, json::array({{"foo", "bar"}})); + + json k; + k.push_back({1, 2, 3}); + EXPECT_EQ(k, json::array({{1, 2, 3}})); +} + +TEST(JsonPushBackInitListTest, Array) +{ + json j = {1, 2, 3}; + j.push_back({"foo", "bar"}); + EXPECT_EQ(j, json({1, 2, 3, {"foo", "bar"}})); + + json k = {1, 2, 3}; + k.push_back({1, 2, 3}); + EXPECT_EQ(k, json({1, 2, 3, {1, 2, 3}})); +} + +TEST(JsonPushBackInitListTest, Object) +{ + json j = {{"key1", 1}}; + j.push_back({"key2", "bar"}); + EXPECT_EQ(j, json({{"key1", 1}, {"key2", "bar"}})); + + json k = {{"key1", 1}}; + EXPECT_THROW_MSG(k.push_back({1, 2, 3, 4}), json::type_error, + "[json.exception.type_error.308] cannot use push_back() with object"); +} + +TEST(JsonEmplaceBackArrayTest, Null) +{ + json j; + j.emplace_back(1); + j.emplace_back(2); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2})); +} + +TEST(JsonEmplaceBackArrayTest, Array) +{ + json j = {1, 2, 3}; + j.emplace_back("Hello"); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2, 3, "Hello"})); +} + +TEST(JsonEmplaceBackArrayTest, MultipleValues) +{ + json j; + j.emplace_back(3, "foo"); + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({{"foo", "foo", "foo"}})); +} + +TEST(JsonEmplaceBackArrayTest, Other) +{ + json j = 1; + EXPECT_THROW_MSG(j.emplace_back("Hello"), json::type_error, + "[json.exception.type_error.311] cannot use emplace_back() with number"); +} + +TEST(JsonEmplaceObjectTest, Null) +{ + // start with a null value + json j; + + // add a new key + auto res1 = j.emplace("foo", "bar"); + EXPECT_EQ(res1.second, true); + EXPECT_EQ(*res1.first, "bar"); + + // the null value is changed to an object + EXPECT_EQ(j.type(), json::value_t::object); + + // add a new key + auto res2 = j.emplace("baz", "bam"); + EXPECT_EQ(res2.second, true); + EXPECT_EQ(*res2.first, "bam"); + + // we try to insert at given key - no change + auto res3 = j.emplace("baz", "bad"); + EXPECT_EQ(res3.second, false); + EXPECT_EQ(*res3.first, "bam"); + + // the final object + EXPECT_EQ(j, json({{"baz", "bam"}, {"foo", "bar"}})); +} + +TEST(JsonEmplaceObjectTest, Object) +{ + // start with an object + json j = {{"foo", "bar"}}; + + // add a new key + auto res1 = j.emplace("baz", "bam"); + EXPECT_EQ(res1.second, true); + EXPECT_EQ(*res1.first, "bam"); + + // add an existing key + auto res2 = j.emplace("foo", "bad"); + EXPECT_EQ(res2.second, false); + EXPECT_EQ(*res2.first, "bar"); + + // check final object + EXPECT_EQ(j, json({{"baz", "bam"}, {"foo", "bar"}})); +} + +TEST(JsonEmplaceObjectTest, Other) +{ + json j = 1; + EXPECT_THROW_MSG(j.emplace("foo", "bar"), json::type_error, + "[json.exception.type_error.311] cannot use emplace() with number"); +} + +TEST(JsonPlusEqualArrayTest, RRefNull) +{ + json j; + j += 1; + j += 2; + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2})); +} + +TEST(JsonPlusEqualArrayTest, RRefArray) +{ + json j = {1, 2, 3}; + j += "Hello"; + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2, 3, "Hello"})); +} + +TEST(JsonPlusEqualArrayTest, RRefOther) +{ + json j = 1; + EXPECT_THROW_MSG(j += "Hello", json::type_error, + "[json.exception.type_error.308] cannot use push_back() with number"); +} + +TEST(JsonPlusEqualArrayTest, LRefNull) +{ + json j; + json k(1); + j += k; + j += k; + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 1})); +} + +TEST(JsonPlusEqualArrayTest, LRefArray) +{ + json j = {1, 2, 3}; + json k("Hello"); + j += k; + EXPECT_EQ(j.type(), json::value_t::array); + EXPECT_EQ(j, json({1, 2, 3, "Hello"})); +} + +TEST(JsonPlusEqualArrayTest, LRefOther) +{ + json j = 1; + json k("Hello"); + EXPECT_THROW_MSG(j += k, json::type_error, + "[json.exception.type_error.308] cannot use push_back() with number"); +} +#if 0 +TEST(JsonPlusEqualObjectTest, Null) +{ + json j; + j += json::object_t::value_type({"one", 1}); + j += json::object_t::value_type({"two", 2}); + EXPECT_EQ(j.type(), json::value_t::object); + EXPECT_EQ(j.size(), 2u); + EXPECT_EQ(j["one"], json(1)); + EXPECT_EQ(j["two"], json(2)); +} + +TEST(JsonPlusEqualObjectTest, Object) +{ + json j(json::value_t::object); + j += json::object_t::value_type({"one", 1}); + j += json::object_t::value_type({"two", 2}); + EXPECT_EQ(j.size(), 2u); + EXPECT_EQ(j["one"], json(1)); + EXPECT_EQ(j["two"], json(2)); +} + +TEST(JsonPlusEqualObjectTest, Other) +{ + json j = 1; + json k("Hello"); + EXPECT_THROW_MSG(j += json::object_t::value_type({"one", 1}), json::type_error, + "[json.exception.type_error.308] cannot use push_back() with number"); +} +#endif +TEST(JsonPlusEqualInitListTest, Null) +{ + json j; + j += {"foo", "bar"}; + EXPECT_EQ(j, json::array({{"foo", "bar"}})); + + json k; + k += {1, 2, 3}; + EXPECT_EQ(k, json::array({{1, 2, 3}})); +} + +TEST(JsonPlusEqualInitListTest, Array) +{ + json j = {1, 2, 3}; + j += {"foo", "bar"}; + EXPECT_EQ(j, json({1, 2, 3, {"foo", "bar"}})); + + json k = {1, 2, 3}; + k += {1, 2, 3}; + EXPECT_EQ(k, json({1, 2, 3, {1, 2, 3}})); +} + +TEST(JsonPlusEqualInitListTest, Object) +{ + json j = {{"key1", 1}}; + j += {"key2", "bar"}; + EXPECT_EQ(j, json({{"key1", 1}, {"key2", "bar"}})); + + json k = {{"key1", 1}}; + EXPECT_THROW_MSG((k += {1, 2, 3, 4}), json::type_error, + "[json.exception.type_error.308] cannot use push_back() with object"); +} + +class JsonInsertTest : public ::testing::Test { + protected: + json j_array = {1, 2, 3, 4}; + json j_value = 5; + json j_other_array = {"first", "second"}; + json j_object1 = {{"one", "eins"}, {"two", "zwei"}}; + json j_object2 = {{"eleven", "elf"}, {"seventeen", "siebzehn"}}; +}; + +TEST_F(JsonInsertTest, ValueBegin) +{ + auto it = j_array.insert(j_array.begin(), j_value); + EXPECT_EQ(j_array.size(), 5u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ(j_array.begin(), it); + EXPECT_EQ(j_array, json({5, 1, 2, 3, 4})); +} + +TEST_F(JsonInsertTest, ValueMiddle) +{ + auto it = j_array.insert(j_array.begin() + 2, j_value); + EXPECT_EQ(j_array.size(), 5u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ((it - j_array.begin()), 2); + EXPECT_EQ(j_array, json({1, 2, 5, 3, 4})); +} + +TEST_F(JsonInsertTest, ValueEnd) +{ + auto it = j_array.insert(j_array.end(), j_value); + EXPECT_EQ(j_array.size(), 5u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ((j_array.end() - it), 1); + EXPECT_EQ(j_array, json({1, 2, 3, 4, 5})); +} + +TEST_F(JsonInsertTest, RvalueBegin) +{ + auto it = j_array.insert(j_array.begin(), 5); + EXPECT_EQ(j_array.size(), 5u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ(j_array.begin(), it); + EXPECT_EQ(j_array, json({5, 1, 2, 3, 4})); +} + +TEST_F(JsonInsertTest, RvalueMiddle) +{ + auto it = j_array.insert(j_array.begin() + 2, 5); + EXPECT_EQ(j_array.size(), 5u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ((it - j_array.begin()), 2); + EXPECT_EQ(j_array, json({1, 2, 5, 3, 4})); +} + +TEST_F(JsonInsertTest, RvalueEnd) +{ + auto it = j_array.insert(j_array.end(), 5); + EXPECT_EQ(j_array.size(), 5u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ((j_array.end() - it), 1); + EXPECT_EQ(j_array, json({1, 2, 3, 4, 5})); +} + +TEST_F(JsonInsertTest, CopyBegin) +{ + auto it = j_array.insert(j_array.begin(), 3, 5); + EXPECT_EQ(j_array.size(), 7u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ(j_array.begin(), it); + EXPECT_EQ(j_array, json({5, 5, 5, 1, 2, 3, 4})); +} + +TEST_F(JsonInsertTest, CopyMiddle) +{ + auto it = j_array.insert(j_array.begin() + 2, 3, 5); + EXPECT_EQ(j_array.size(), 7u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ((it - j_array.begin()), 2); + EXPECT_EQ(j_array, json({1, 2, 5, 5, 5, 3, 4})); +} + +TEST_F(JsonInsertTest, CopyEnd) +{ + auto it = j_array.insert(j_array.end(), 3, 5); + EXPECT_EQ(j_array.size(), 7u); + EXPECT_EQ(*it, j_value); + EXPECT_EQ((j_array.end() - it), 3); + EXPECT_EQ(j_array, json({1, 2, 3, 4, 5, 5, 5})); +} + +TEST_F(JsonInsertTest, CopyNothing) +{ + auto it = j_array.insert(j_array.end(), 0, 5); + EXPECT_EQ(j_array.size(), 4u); + // the returned iterator points to the first inserted element; + // there were 4 elements, so it should point to the 5th + EXPECT_EQ(it, j_array.begin() + 4); + EXPECT_EQ(j_array, json({1, 2, 3, 4})); +} + +TEST_F(JsonInsertTest, RangeForArrayProper) +{ + auto it = j_array.insert(j_array.end(), j_other_array.begin(), j_other_array.end()); + EXPECT_EQ(j_array.size(), 6u); + EXPECT_EQ(*it, *j_other_array.begin()); + EXPECT_EQ((j_array.end() - it), 2); + EXPECT_EQ(j_array, json({1, 2, 3, 4, "first", "second"})); +} + +TEST_F(JsonInsertTest, RangeForArrayEmpty) +{ + auto it = j_array.insert(j_array.end(), j_other_array.begin(), j_other_array.begin()); + EXPECT_EQ(j_array.size(), 4u); + EXPECT_EQ(it, j_array.end()); + EXPECT_EQ(j_array, json({1, 2, 3, 4})); +} + +TEST_F(JsonInsertTest, RangeForArrayInvalid) +{ + json j_other_array2 = {"first", "second"}; + + EXPECT_THROW_MSG(j_array.insert(j_array.end(), j_array.begin(), j_array.end()), + json::invalid_iterator, + "[json.exception.invalid_iterator.211] passed iterators may not belong to container"); + EXPECT_THROW_MSG(j_array.insert(j_array.end(), j_other_array.begin(), j_other_array2.end()), + json::invalid_iterator, + "[json.exception.invalid_iterator.210] iterators do not fit"); +} + +TEST_F(JsonInsertTest, RangeForObjectProper) +{ + j_object1.insert(j_object2.begin(), j_object2.end()); + EXPECT_EQ(j_object1.size(), 4u); +} + +TEST_F(JsonInsertTest, RangeForObjectEmpty) +{ + j_object1.insert(j_object2.begin(), j_object2.begin()); + EXPECT_EQ(j_object1.size(), 2u); +} + +TEST_F(JsonInsertTest, RangeForObjectInvalid) +{ + json j_other_array2 = {"first", "second"}; + + EXPECT_THROW_MSG(j_array.insert(j_object2.begin(), j_object2.end()), json::type_error, + "[json.exception.type_error.309] cannot use insert() with array"); + EXPECT_THROW_MSG(j_object1.insert(j_object1.begin(), j_object2.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.210] iterators do not fit"); + EXPECT_THROW_MSG(j_object1.insert(j_array.begin(), j_array.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterators first and last must point to objects"); +} + +TEST_F(JsonInsertTest, InitListBegin) +{ + auto it = j_array.insert(j_array.begin(), {7, 8, 9}); + EXPECT_EQ(j_array.size(), 7u); + EXPECT_EQ(*it, json(7)); + EXPECT_EQ(j_array.begin(), it); + EXPECT_EQ(j_array, json({7, 8, 9, 1, 2, 3, 4})); +} + +TEST_F(JsonInsertTest, InitListMiddle) +{ + auto it = j_array.insert(j_array.begin() + 2, {7, 8, 9}); + EXPECT_EQ(j_array.size(), 7u); + EXPECT_EQ(*it, json(7)); + EXPECT_EQ((it - j_array.begin()), 2); + EXPECT_EQ(j_array, json({1, 2, 7, 8, 9, 3, 4})); +} + +TEST_F(JsonInsertTest, InitListEnd) +{ + auto it = j_array.insert(j_array.end(), {7, 8, 9}); + EXPECT_EQ(j_array.size(), 7u); + EXPECT_EQ(*it, json(7)); + EXPECT_EQ((j_array.end() - it), 3); + EXPECT_EQ(j_array, json({1, 2, 3, 4, 7, 8, 9})); +} + +TEST_F(JsonInsertTest, InvalidIterator) +{ + // pass iterator to a different array + json j_another_array = {1, 2}; + json j_yet_another_array = {"first", "second"}; + EXPECT_THROW_MSG(j_array.insert(j_another_array.end(), 10), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(j_array.insert(j_another_array.end(), j_value), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(j_array.insert(j_another_array.end(), 10, 11), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(j_array.insert(j_another_array.end(), j_yet_another_array.begin(), j_yet_another_array.end()), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); + EXPECT_THROW_MSG(j_array.insert(j_another_array.end(), {1, 2, 3, 4}), json::invalid_iterator, + "[json.exception.invalid_iterator.202] iterator does not fit current value"); +} + +TEST_F(JsonInsertTest, NonArray) +{ + // call insert on a non-array type + json j_nonarray = 3; + json j_yet_another_array = {"first", "second"}; + EXPECT_THROW_MSG(j_nonarray.insert(j_nonarray.end(), 10), json::type_error, + "[json.exception.type_error.309] cannot use insert() with number"); + EXPECT_THROW_MSG(j_nonarray.insert(j_nonarray.end(), j_value), json::type_error, + "[json.exception.type_error.309] cannot use insert() with number"); + EXPECT_THROW_MSG(j_nonarray.insert(j_nonarray.end(), 10, 11), json::type_error, + "[json.exception.type_error.309] cannot use insert() with number"); + EXPECT_THROW_MSG(j_nonarray.insert(j_nonarray.end(), j_yet_another_array.begin(), + j_yet_another_array.end()), json::type_error, + "[json.exception.type_error.309] cannot use insert() with number"); + EXPECT_THROW_MSG(j_nonarray.insert(j_nonarray.end(), {1, 2, 3, 4}), json::type_error, + "[json.exception.type_error.309] cannot use insert() with number"); +} + +TEST(JsonSwapTest, JsonMember) +{ + json j("hello world"); + json k(42.23); + + j.swap(k); + + EXPECT_EQ(j, json(42.23)); + EXPECT_EQ(k, json("hello world")); +} + +TEST(JsonSwapTest, JsonNonMember) +{ + json j("hello world"); + json k(42.23); + + std::swap(j, k); + + EXPECT_EQ(j, json(42.23)); + EXPECT_EQ(k, json("hello world")); +} + +TEST(JsonSwapTest, ArrayT) +{ + json j = {1, 2, 3, 4}; + json::array_t a = {"foo", "bar", "baz"}; + + j.swap(a); + + EXPECT_EQ(j, json({"foo", "bar", "baz"})); + + j.swap(a); + + EXPECT_EQ(j, json({1, 2, 3, 4})); +} + +TEST(JsonSwapTest, NonArrayT) +{ + json j = 17; + json::array_t a = {"foo", "bar", "baz"}; + + EXPECT_THROW_MSG(j.swap(a), json::type_error, + "[json.exception.type_error.310] cannot use swap() with number"); +} + +TEST(JsonSwapTest, ObjectT) +{ + json j = {{"one", 1}, {"two", 2}}; + json::object_t o = {{"cow", "Kuh"}, {"chicken", "Huhn"}}; + + j.swap(o); + + EXPECT_EQ(j, json({{"cow", "Kuh"}, {"chicken", "Huhn"}})); + + j.swap(o); + + EXPECT_EQ(j, json({{"one", 1}, {"two", 2}})); +} + +TEST(JsonSwapTest, NonObjectT) +{ + json j = 17; + json::object_t o = {{"cow", "Kuh"}, {"chicken", "Huhn"}}; + + EXPECT_THROW_MSG(j.swap(o), json::type_error, + "[json.exception.type_error.310] cannot use swap() with number"); +} + +TEST(JsonSwapTest, StringT) +{ + json j = "Hello world"; + json::string_t s = "Hallo Welt"; + + j.swap(s); + + EXPECT_EQ(j, json("Hallo Welt")); + + j.swap(s); + + EXPECT_EQ(j, json("Hello world")); +} + +TEST(JsonSwapTest, NonStringT) +{ + json j = 17; + json::string_t s = "Hallo Welt"; + + EXPECT_THROW_MSG(j.swap(s), json::type_error, + "[json.exception.type_error.310] cannot use swap() with number"); +} diff --git a/src/test/native/cpp/json/unit-msgpack.cpp b/src/test/native/cpp/json/unit-msgpack.cpp new file mode 100644 index 0000000000..b92c450c06 --- /dev/null +++ b/src/test/native/cpp/json/unit-msgpack.cpp @@ -0,0 +1,1257 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +#include + +TEST(MessagePackDiscardedTest, Case) +{ + // discarded values are not serialized + json j = json::value_t::discarded; + const auto result = json::to_msgpack(j); + EXPECT_TRUE(result.empty()); +} + +TEST(MessagePackNullTest, Case) +{ + json j = nullptr; + std::string expected = "\xc0"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +TEST(MessagePackBooleanTest, True) +{ + json j = true; + std::string expected = "\xc3"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +TEST(MessagePackBooleanTest, False) +{ + json j = false; + std::string expected = "\xc2"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// -32..-1 (negative fixnum) +TEST(MessagePackSignedTest, Neg0) +{ + for (auto i = -32; i <= -1; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 1u); + + // check individual bytes + EXPECT_EQ(static_cast(result[0]), i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 0..127 (positive fixnum) +TEST(MessagePackSignedTest, Pos0) +{ + for (size_t i = 0; i <= 127; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(i); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 1u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(i)); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 128..255 (int 8) +TEST(MessagePackSignedTest, Pos1) +{ + for (size_t i = 128; i <= 255; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(i); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xcc)); + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 2u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xcc)); + uint8_t restored = static_cast(result[1]); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 256..65535 (int 16) +TEST(MessagePackSignedTest, Pos2) +{ + for (size_t i = 256; i <= 65535; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(i); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xcd)); + expected.push_back(static_cast((i >> 8) & 0xff)); + expected.push_back(static_cast(i & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xcd)); + uint16_t restored = static_cast(static_cast(result[1]) * 256 + static_cast(result[2])); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 65536..4294967295 (int 32) +class MessagePackSignedPos4Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackSignedPos4Test, Case) +{ + // create JSON value with integer number + json j = -1; + j.get_ref() = static_cast(GetParam()); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xce)); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 5u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xce)); + uint32_t restored = (static_cast(static_cast(result[1])) << 030) + + (static_cast(static_cast(result[2])) << 020) + + (static_cast(static_cast(result[3])) << 010) + + static_cast(static_cast(result[4])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +static const uint32_t pos4_numbers[] = { + 65536u, + 77777u, + 1048576u, + 4294967295u, +}; + +INSTANTIATE_TEST_CASE_P(MessagePackSignedPos4Tests, MessagePackSignedPos4Test, + ::testing::ValuesIn(pos4_numbers)); + +// 4294967296..9223372036854775807 (int 64) +class MessagePackSignedPos8Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackSignedPos8Test, Case) +{ + // create JSON value with integer number + json j = -1; + j.get_ref() = + static_cast(GetParam()); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xcf)); + expected.push_back(static_cast((GetParam() >> 070) & 0xff)); + expected.push_back(static_cast((GetParam() >> 060) & 0xff)); + expected.push_back(static_cast((GetParam() >> 050) & 0xff)); + expected.push_back(static_cast((GetParam() >> 040) & 0xff)); + expected.push_back(static_cast((GetParam() >> 030) & 0xff)); + expected.push_back(static_cast((GetParam() >> 020) & 0xff)); + expected.push_back(static_cast((GetParam() >> 010) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 9u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xcf)); + uint64_t restored = (static_cast(static_cast(result[1])) << 070) + + (static_cast(static_cast(result[2])) << 060) + + (static_cast(static_cast(result[3])) << 050) + + (static_cast(static_cast(result[4])) << 040) + + (static_cast(static_cast(result[5])) << 030) + + (static_cast(static_cast(result[6])) << 020) + + (static_cast(static_cast(result[7])) << 010) + + static_cast(static_cast(result[8])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +static const uint64_t pos8_numbers[] = { + 4294967296lu, + 9223372036854775807lu, +}; + +INSTANTIATE_TEST_CASE_P(MessagePackSignedPos8Tests, MessagePackSignedPos8Test, + ::testing::ValuesIn(pos8_numbers)); + +// -128..-33 (int 8) +TEST(MessagePackSignedTest, Neg1) +{ + for (auto i = -128; i <= -33; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xd0)); + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 2u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xd0)); + EXPECT_EQ(static_cast(result[1]), i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// -32768..-129 (int 16) +TEST(MessagePackSignedTest, Neg2) +{ + for (int16_t i = -32768; i <= -129; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with integer number + json j = i; + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xd1)); + expected.push_back(static_cast((i >> 8) & 0xff)); + expected.push_back(static_cast(i & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xd1)); + int16_t restored = static_cast((static_cast(result[1]) << 8) + + static_cast(result[2])); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// -32769..-2147483648 +class MessagePackSignedNeg4Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackSignedNeg4Test, Case) +{ + // create JSON value with integer number + json j = GetParam(); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xd2)); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 5u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xd2)); + uint32_t restored = (static_cast(static_cast(result[1])) << 030) + + (static_cast(static_cast(result[2])) << 020) + + (static_cast(static_cast(result[3])) << 010) + + static_cast(static_cast(result[4])); + EXPECT_EQ(static_cast(restored), GetParam()); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +static const int32_t neg4_numbers[] = { + -32769, + -65536, + -77777, + -1048576, + -2147483648ll, +}; + +INSTANTIATE_TEST_CASE_P(MessagePackSignedNeg4Tests, MessagePackSignedNeg4Test, + ::testing::ValuesIn(neg4_numbers)); + +// -9223372036854775808..-2147483649 (int 64) +class MessagePackSignedNeg8Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackSignedNeg8Test, Case) +{ + // create JSON value with unsigned integer number + json j = GetParam(); + + // check type + EXPECT_TRUE(j.is_number_integer()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xd3)); + expected.push_back(static_cast((GetParam() >> 070) & 0xff)); + expected.push_back(static_cast((GetParam() >> 060) & 0xff)); + expected.push_back(static_cast((GetParam() >> 050) & 0xff)); + expected.push_back(static_cast((GetParam() >> 040) & 0xff)); + expected.push_back(static_cast((GetParam() >> 030) & 0xff)); + expected.push_back(static_cast((GetParam() >> 020) & 0xff)); + expected.push_back(static_cast((GetParam() >> 010) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 9u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xd3)); + int64_t restored = (static_cast(static_cast(result[1])) << 070) + + (static_cast(static_cast(result[2])) << 060) + + (static_cast(static_cast(result[3])) << 050) + + (static_cast(static_cast(result[4])) << 040) + + (static_cast(static_cast(result[5])) << 030) + + (static_cast(static_cast(result[6])) << 020) + + (static_cast(static_cast(result[7])) << 010) + + static_cast(static_cast(result[8])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +static const int64_t neg8_numbers[] = { + INT64_MIN, + -2147483649ll, +}; + +INSTANTIATE_TEST_CASE_P(MessagePackSignedNeg8Tests, MessagePackSignedNeg8Test, + ::testing::ValuesIn(neg8_numbers)); + +// 0..127 (positive fixnum) +TEST(MessagePackUnsignedTest, Pos0) +{ + for (size_t i = 0; i <= 127; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with unsigned integer number + json j = i; + + // check type + EXPECT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 1u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(i)); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 128..255 (uint 8) +TEST(MessagePackUnsignedTest, Pos1) +{ + for (size_t i = 128; i <= 255; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with unsigned integer number + json j = i; + + // check type + EXPECT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xcc)); + expected.push_back(static_cast(i)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 2u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xcc)); + uint8_t restored = static_cast(result[1]); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 256..65535 (uint 16) +TEST(MessagePackUnsignedTest, Pos2) +{ + for (size_t i = 256; i <= 65535; ++i) + { + SCOPED_TRACE(i); + + // create JSON value with unsigned integer number + json j = i; + + // check type + EXPECT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xcd)); + expected.push_back(static_cast((i >> 8) & 0xff)); + expected.push_back(static_cast(i & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 3u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xcd)); + uint16_t restored = static_cast(static_cast(result[1]) * 256 + static_cast(result[2])); + EXPECT_EQ(restored, i); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// 65536..4294967295 (uint 32) +class MessagePackUnsignedPos4Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackUnsignedPos4Test, Case) +{ + // create JSON value with unsigned integer number + json j = GetParam(); + + // check type + EXPECT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xce)); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 5u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xce)); + uint32_t restored = (static_cast(static_cast(result[1])) << 030) + + (static_cast(static_cast(result[2])) << 020) + + (static_cast(static_cast(result[3])) << 010) + + static_cast(static_cast(result[4])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +INSTANTIATE_TEST_CASE_P(MessagePackUnsignedPos4Tests, + MessagePackUnsignedPos4Test, + ::testing::ValuesIn(pos4_numbers)); + +// 4294967296..18446744073709551615 (uint 64) +class MessagePackUnsignedPos8Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackUnsignedPos8Test, Case) +{ + // create JSON value with unsigned integer number + json j = GetParam(); + + // check type + EXPECT_TRUE(j.is_number_unsigned()); + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xcf)); + expected.push_back(static_cast((GetParam() >> 070) & 0xff)); + expected.push_back(static_cast((GetParam() >> 060) & 0xff)); + expected.push_back(static_cast((GetParam() >> 050) & 0xff)); + expected.push_back(static_cast((GetParam() >> 040) & 0xff)); + expected.push_back(static_cast((GetParam() >> 030) & 0xff)); + expected.push_back(static_cast((GetParam() >> 020) & 0xff)); + expected.push_back(static_cast((GetParam() >> 010) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), 9u); + + // check individual bytes + EXPECT_EQ(result[0], static_cast(0xcf)); + uint64_t restored = (static_cast(static_cast(result[1])) << 070) + + (static_cast(static_cast(result[2])) << 060) + + (static_cast(static_cast(result[3])) << 050) + + (static_cast(static_cast(result[4])) << 040) + + (static_cast(static_cast(result[5])) << 030) + + (static_cast(static_cast(result[6])) << 020) + + (static_cast(static_cast(result[7])) << 010) + + static_cast(static_cast(result[8])); + EXPECT_EQ(restored, GetParam()); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +INSTANTIATE_TEST_CASE_P(MessagePackUnsignedPos8Tests, + MessagePackUnsignedPos8Test, + ::testing::ValuesIn(pos8_numbers)); + +// 3.1415925 +TEST(MessagePackFloatTest, Number) +{ + double v = 3.1415925; + json j = v; + std::string expected = "\xcb\x40\x09\x21\xfb\x3f\xa6\xde\xfc"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + EXPECT_EQ(json::from_msgpack(result), v); +} + +// N = 0..31 +TEST(MessagePackStringTest, String1) +{ + // explicitly enumerate the first byte for all 32 strings + const std::vector first_bytes = + { + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, + 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, + 0xbb, 0xbc, 0xbd, 0xbe, 0xbf + }; + + for (size_t N = 0; N < first_bytes.size(); ++N) + { + SCOPED_TRACE(N); + + // create JSON value with string containing of N * 'x' + const auto s = std::string(N, 'x'); + json j = s; + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(first_bytes[N])); + expected.append(s); + + // check first byte + EXPECT_EQ((first_bytes[N] & 0x1f), static_cast(N)); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), N + 1); + // check that no null byte is appended + if (N > 0) + { + EXPECT_NE(result.back(), '\x00'); + } + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// N = 32..255 +TEST(MessagePackStringTest, String2) +{ + for (size_t N = 32; N <= 255; ++N) + { + SCOPED_TRACE(N); + + // create JSON value with string containing of N * 'x' + const auto s = std::string(N, 'x'); + json j = s; + + // create expected byte vector + std::string expected; + expected.push_back(static_cast(0xd9)); + expected.push_back(static_cast(N)); + expected.append(s); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), N + 2); + // check that no null byte is appended + EXPECT_NE(result.back(), '\x00'); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); + } +} + +// N = 256..65535 +class MessagePackString3Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackString3Test, Case) +{ + // create JSON value with string containing of N * 'x' + const auto s = std::string(GetParam(), 'x'); + json j = s; + + // create expected byte vector (hack: create string first) + std::string expected; + expected.push_back(static_cast(0xda)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + expected.append(s); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), GetParam() + 3); + // check that no null byte is appended + EXPECT_NE(result.back(), '\x00'); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +static size_t string3_lens[] = { + 256u, + 999u, + 1025u, + 3333u, + 2048u, + 65535u +}; + +INSTANTIATE_TEST_CASE_P(MessagePackString3Tests, MessagePackString3Test, + ::testing::ValuesIn(string3_lens)); + + +// N = 65536..4294967295 +class MessagePackString5Test : public ::testing::TestWithParam {}; +TEST_P(MessagePackString5Test, Case) +{ + // create JSON value with string containing of N * 'x' + const auto s = std::string(GetParam(), 'x'); + json j = s; + + // create expected byte vector (hack: create string first) + std::string expected; + expected.push_back(static_cast(0xdb)); + expected.push_back(static_cast((GetParam() >> 24) & 0xff)); + expected.push_back(static_cast((GetParam() >> 16) & 0xff)); + expected.push_back(static_cast((GetParam() >> 8) & 0xff)); + expected.push_back(static_cast(GetParam() & 0xff)); + expected.append(s); + + // compare result + size + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + EXPECT_EQ(result.size(), GetParam() + 5); + // check that no null byte is appended + EXPECT_NE(result.back(), '\x00'); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +static size_t string5_lens[] = { + 65536u, + 77777u, + 1048576u +}; + +INSTANTIATE_TEST_CASE_P(MessagePackString5Tests, MessagePackString5Test, + ::testing::ValuesIn(string5_lens)); + +TEST(MessagePackArrayTest, Empty) +{ + json j = json::array(); + std::string expected = "\x90"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// [null] +TEST(MessagePackArrayTest, Null) +{ + json j = {nullptr}; + std::string expected = "\x91\xc0"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// [1,2,3,4,5] +TEST(MessagePackArrayTest, Simple) +{ + json j = json::parse("[1,2,3,4,5]"); + std::string expected = "\x95\x01\x02\x03\x04\x05"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// [[[[]]]] +TEST(MessagePackArrayTest, NestEmpty) +{ + json j = json::parse("[[[[]]]]"); + std::string expected = "\x91\x91\x91\x90"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// array 16 +TEST(MessagePackArrayTest, UInt16) +{ + json j(16, nullptr); + std::string expected(j.size() + 3, static_cast(0xc0)); // all null + expected[0] = static_cast(0xdc); // array 16 + expected[1] = 0x00; // size (0x0010), byte 0 + expected[2] = 0x10; // size (0x0010), byte 1 + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// array 32 +TEST(MessagePackArrayTest, UInt32) +{ + json j(65536, nullptr); + std::string expected(j.size() + 5, static_cast(0xc0)); // all null + expected[0] = static_cast(0xdd); // array 32 + expected[1] = 0x00; // size (0x00100000), byte 0 + expected[2] = 0x01; // size (0x00100000), byte 1 + expected[3] = 0x00; // size (0x00100000), byte 2 + expected[4] = 0x00; // size (0x00100000), byte 3 + const auto result = json::to_msgpack(j); + //EXPECT_EQ(result, expected); + + EXPECT_EQ(result.size(), expected.size()); + for (size_t i = 0; i < expected.size(); ++i) + { + SCOPED_TRACE(i); + EXPECT_EQ(result[i], expected[i]); + } + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +TEST(MessagePackObjectTest, Empty) +{ + json j = json::object(); + std::string expected = "\x80"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// {"":null} +TEST(MessagePackObjectTest, EmptyKey) +{ + json j = {{"", nullptr}}; + std::string expected = "\x81\xa0\xc0"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// {"a": {"b": {"c": {}}}} +TEST(MessagePackObjectTest, NestedEmpty) +{ + json j = json::parse("{\"a\": {\"b\": {\"c\": {}}}}"); + std::string expected = "\x81\xa1\x61\x81\xa1\x62\x81\xa1\x63\x80"; + const auto result = json::to_msgpack(j); + EXPECT_EQ(result, expected); + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// map 16 +TEST(MessagePackObjectTest, UInt16) +{ + json j = R"({"00": null, "01": null, "02": null, "03": null, + "04": null, "05": null, "06": null, "07": null, + "08": null, "09": null, "10": null, "11": null, + "12": null, "13": null, "14": null, "15": null})"_json; + + const auto result = json::to_msgpack(j); + + // Checking against an expected vector byte by byte is + // difficult, because no assumption on the order of key/value + // pairs are made. We therefore only check the prefix (type and + // size and the overall size. The rest is then handled in the + // roundtrip check. + EXPECT_EQ(result.size(), 67u); // 1 type, 2 size, 16*4 content + EXPECT_EQ(result[0], static_cast(0xde)); // map 16 + EXPECT_EQ(result[1], 0x00); // byte 0 of size (0x0010) + EXPECT_EQ(result[2], 0x10); // byte 1 of size (0x0010) + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// map 32 +TEST(MessagePackObjectTest, UInt32) +{ + json j; + for (auto i = 0; i < 65536; ++i) + { + // format i to a fixed width of 5 + // each entry will need 7 bytes: 6 for fixstr, 1 for null + std::stringstream ss; + ss << std::setw(5) << std::setfill('0') << i; + j.emplace(ss.str(), nullptr); + } + + const auto result = json::to_msgpack(j); + + // Checking against an expected vector byte by byte is + // difficult, because no assumption on the order of key/value + // pairs are made. We therefore only check the prefix (type and + // size and the overall size. The rest is then handled in the + // roundtrip check. + EXPECT_EQ(result.size(), 458757u); // 1 type, 4 size, 65536*7 content + EXPECT_EQ(result[0], static_cast(0xdf)); // map 32 + EXPECT_EQ(result[1], 0x00); // byte 0 of size (0x00010000) + EXPECT_EQ(result[2], 0x01); // byte 1 of size (0x00010000) + EXPECT_EQ(result[3], 0x00); // byte 2 of size (0x00010000) + EXPECT_EQ(result[4], 0x00); // byte 3 of size (0x00010000) + + // roundtrip + EXPECT_EQ(json::from_msgpack(result), j); +} + +// from float32 +TEST(MessagePackFloat32Test, Case) +{ + auto given = std::string("\xca\x41\xc8\x00\x01", 5); + json j = json::from_msgpack(given); + EXPECT_LT(std::fabs(j.get() - 25), 0.001); +} + +TEST(MessagePackErrorTest, TooShortByteVector) +{ + EXPECT_THROW_MSG(json::from_msgpack("\xcc"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack("\xcd"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcd\x00", 2)), json::parse_error, + "[json.exception.parse_error.110] parse error at 3: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack("\xce"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xce\x00", 2)), json::parse_error, + "[json.exception.parse_error.110] parse error at 3: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xce\x00\x00", 3)), json::parse_error, + "[json.exception.parse_error.110] parse error at 4: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xce\x00\x00\x00", 4)), json::parse_error, + "[json.exception.parse_error.110] parse error at 5: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack("\xcf"), json::parse_error, + "[json.exception.parse_error.110] parse error at 2: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00", 2)), json::parse_error, + "[json.exception.parse_error.110] parse error at 3: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00\x00", 3)), json::parse_error, + "[json.exception.parse_error.110] parse error at 4: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00\x00\x00", 4)), json::parse_error, + "[json.exception.parse_error.110] parse error at 5: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00\x00\x00\x00", 5)), json::parse_error, + "[json.exception.parse_error.110] parse error at 6: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00\x00\x00\x00\x00", 6)), json::parse_error, + "[json.exception.parse_error.110] parse error at 7: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00\x00\x00\x00\x00\x00", 7)), json::parse_error, + "[json.exception.parse_error.110] parse error at 8: unexpected end of input"); + EXPECT_THROW_MSG(json::from_msgpack(llvm::StringRef("\xcf\x00\x00\x00\x00\x00\x00\x00", 8)), json::parse_error, + "[json.exception.parse_error.110] parse error at 9: unexpected end of input"); +} + +TEST(MessagePackErrorTest, UnsupportedBytesConcrete) +{ + EXPECT_THROW_MSG(json::from_msgpack("\xc1"), json::parse_error, + "[json.exception.parse_error.112] parse error at 1: error reading MessagePack; last byte: 0xc1"); + EXPECT_THROW_MSG(json::from_msgpack("\xc6"), json::parse_error, + "[json.exception.parse_error.112] parse error at 1: error reading MessagePack; last byte: 0xc6"); +} + +TEST(MessagePackErrorTest, UnsupportedBytesAll) +{ + for (auto byte : + { + // never used + 0xc1, + // bin + 0xc4, 0xc5, 0xc6, + // ext + 0xc7, 0xc8, 0xc9, + // fixext + 0xd4, 0xd5, 0xd6, 0xd7, 0xd8 + }) + { + EXPECT_THROW(json::from_msgpack(std::string(1, static_cast(byte))), json::parse_error); + } +} +#if 0 +// use this testcase outside [hide] to run it with Valgrind +TEST(MessagePackRoundtripTest, Sample) +{ + std::string filename = "test/data/json_testsuite/sample.json"; + + // parse JSON file + std::ifstream f_json(filename); + json j1 = json::parse(f_json); + + // parse MessagePack file + std::ifstream f_msgpack(filename + ".msgpack", std::ios::binary); + std::vector packed((std::istreambuf_iterator(f_msgpack)), + std::istreambuf_iterator()); + json j2; + EXPECT_NO_THROW(j2 = json::from_msgpack(packed)); + + // compare parsed JSON values + EXPECT_EQ(j1, j2); + + // check with different start index + packed.insert(packed.begin(), 5, 0xff); + EXPECT_EQ(j1, json::from_msgpack(packed, 5)); +} + +class MessagePackRegressionTest : public ::testing::TestWithParam {}; +TEST_P(MessagePackRegressionTest, Case) +{ + // parse JSON file + std::ifstream f_json(GetParam()); + json j1 = json::parse(f_json); + + // parse MessagePack file + std::ifstream f_msgpack(filename + ".msgpack", std::ios::binary); + std::vector packed((std::istreambuf_iterator(f_msgpack)), + std::istreambuf_iterator()); + json j2; + EXPECT_NO_THROW(j2 = json::from_msgpack(packed)); + + // compare parsed JSON values + EXPECT_EQ(j1, j2); +} + +static const char* regression_test_cases[] = { + "test/data/json_nlohmann_tests/all_unicode.json", + "test/data/json.org/1.json", + "test/data/json.org/2.json", + "test/data/json.org/3.json", + "test/data/json.org/4.json", + "test/data/json.org/5.json", + "test/data/json_roundtrip/roundtrip01.json", + "test/data/json_roundtrip/roundtrip02.json", + "test/data/json_roundtrip/roundtrip03.json", + "test/data/json_roundtrip/roundtrip04.json", + "test/data/json_roundtrip/roundtrip05.json", + "test/data/json_roundtrip/roundtrip06.json", + "test/data/json_roundtrip/roundtrip07.json", + "test/data/json_roundtrip/roundtrip08.json", + "test/data/json_roundtrip/roundtrip09.json", + "test/data/json_roundtrip/roundtrip10.json", + "test/data/json_roundtrip/roundtrip11.json", + "test/data/json_roundtrip/roundtrip12.json", + "test/data/json_roundtrip/roundtrip13.json", + "test/data/json_roundtrip/roundtrip14.json", + "test/data/json_roundtrip/roundtrip15.json", + "test/data/json_roundtrip/roundtrip16.json", + "test/data/json_roundtrip/roundtrip17.json", + "test/data/json_roundtrip/roundtrip18.json", + "test/data/json_roundtrip/roundtrip19.json", + "test/data/json_roundtrip/roundtrip20.json", + "test/data/json_roundtrip/roundtrip21.json", + "test/data/json_roundtrip/roundtrip22.json", + "test/data/json_roundtrip/roundtrip23.json", + "test/data/json_roundtrip/roundtrip24.json", + "test/data/json_roundtrip/roundtrip25.json", + "test/data/json_roundtrip/roundtrip26.json", + "test/data/json_roundtrip/roundtrip27.json", + "test/data/json_roundtrip/roundtrip28.json", + "test/data/json_roundtrip/roundtrip29.json", + "test/data/json_roundtrip/roundtrip30.json", + "test/data/json_roundtrip/roundtrip31.json", + "test/data/json_roundtrip/roundtrip32.json", + "test/data/json_testsuite/sample.json", // kills AppVeyor + "test/data/json_tests/pass1.json", + "test/data/json_tests/pass2.json", + "test/data/json_tests/pass3.json", + "test/data/regression/floats.json", + "test/data/regression/signed_ints.json", + "test/data/regression/unsigned_ints.json", + "test/data/regression/working_file.json", + "test/data/nst_json_testsuite/test_parsing/y_array_arraysWithSpaces.json", + "test/data/nst_json_testsuite/test_parsing/y_array_empty-string.json", + "test/data/nst_json_testsuite/test_parsing/y_array_empty.json", + "test/data/nst_json_testsuite/test_parsing/y_array_ending_with_newline.json", + "test/data/nst_json_testsuite/test_parsing/y_array_false.json", + "test/data/nst_json_testsuite/test_parsing/y_array_heterogeneous.json", + "test/data/nst_json_testsuite/test_parsing/y_array_null.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_1_and_newline.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_leading_space.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_several_null.json", + "test/data/nst_json_testsuite/test_parsing/y_array_with_trailing_space.json", + "test/data/nst_json_testsuite/test_parsing/y_number.json", + "test/data/nst_json_testsuite/test_parsing/y_number_0e+1.json", + "test/data/nst_json_testsuite/test_parsing/y_number_0e1.json", + "test/data/nst_json_testsuite/test_parsing/y_number_after_space.json", + "test/data/nst_json_testsuite/test_parsing/y_number_double_close_to_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_number_double_huge_neg_exp.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_huge_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_int_with_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_minus_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_number_negative_int.json", + "test/data/nst_json_testsuite/test_parsing/y_number_negative_one.json", + "test/data/nst_json_testsuite/test_parsing/y_number_negative_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_capital_e.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_capital_e_neg_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_capital_e_pos_exp.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_exponent.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_fraction_exponent.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_neg_exp.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_real_neg_overflow.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_pos_exponent.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_real_pos_overflow.json", + "test/data/nst_json_testsuite/test_parsing/y_number_real_underflow.json", + "test/data/nst_json_testsuite/test_parsing/y_number_simple_int.json", + "test/data/nst_json_testsuite/test_parsing/y_number_simple_real.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_too_big_neg_int.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_too_big_pos_int.json", + //"test/data/nst_json_testsuite/test_parsing/y_number_very_big_negative_int.json", + "test/data/nst_json_testsuite/test_parsing/y_object.json", + "test/data/nst_json_testsuite/test_parsing/y_object_basic.json", + "test/data/nst_json_testsuite/test_parsing/y_object_duplicated_key.json", + "test/data/nst_json_testsuite/test_parsing/y_object_duplicated_key_and_value.json", + "test/data/nst_json_testsuite/test_parsing/y_object_empty.json", + "test/data/nst_json_testsuite/test_parsing/y_object_empty_key.json", + "test/data/nst_json_testsuite/test_parsing/y_object_escaped_null_in_key.json", + "test/data/nst_json_testsuite/test_parsing/y_object_extreme_numbers.json", + "test/data/nst_json_testsuite/test_parsing/y_object_long_strings.json", + "test/data/nst_json_testsuite/test_parsing/y_object_simple.json", + "test/data/nst_json_testsuite/test_parsing/y_object_string_unicode.json", + "test/data/nst_json_testsuite/test_parsing/y_object_with_newlines.json", + "test/data/nst_json_testsuite/test_parsing/y_string_1_2_3_bytes_UTF-8_sequences.json", + "test/data/nst_json_testsuite/test_parsing/y_string_UTF-16_Surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_accepted_surrogate_pair.json", + "test/data/nst_json_testsuite/test_parsing/y_string_accepted_surrogate_pairs.json", + "test/data/nst_json_testsuite/test_parsing/y_string_allowed_escapes.json", + "test/data/nst_json_testsuite/test_parsing/y_string_backslash_and_u_escaped_zero.json", + "test/data/nst_json_testsuite/test_parsing/y_string_backslash_doublequotes.json", + "test/data/nst_json_testsuite/test_parsing/y_string_comments.json", + "test/data/nst_json_testsuite/test_parsing/y_string_double_escape_a.json", + "test/data/nst_json_testsuite/test_parsing/y_string_double_escape_n.json", + "test/data/nst_json_testsuite/test_parsing/y_string_escaped_control_character.json", + "test/data/nst_json_testsuite/test_parsing/y_string_escaped_noncharacter.json", + "test/data/nst_json_testsuite/test_parsing/y_string_in_array.json", + "test/data/nst_json_testsuite/test_parsing/y_string_in_array_with_leading_space.json", + "test/data/nst_json_testsuite/test_parsing/y_string_last_surrogates_1_and_2.json", + "test/data/nst_json_testsuite/test_parsing/y_string_newline_uescaped.json", + "test/data/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+10FFFF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+1FFFF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+FFFF.json", + "test/data/nst_json_testsuite/test_parsing/y_string_null_escape.json", + "test/data/nst_json_testsuite/test_parsing/y_string_one-byte-utf-8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_pi.json", + "test/data/nst_json_testsuite/test_parsing/y_string_simple_ascii.json", + "test/data/nst_json_testsuite/test_parsing/y_string_space.json", + "test/data/nst_json_testsuite/test_parsing/y_string_three-byte-utf-8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_two-byte-utf-8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_u+2028_line_sep.json", + "test/data/nst_json_testsuite/test_parsing/y_string_u+2029_par_sep.json", + "test/data/nst_json_testsuite/test_parsing/y_string_uEscape.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unescaped_char_delete.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicodeEscapedBackslash.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_2.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_U+2064_invisible_plus.json", + "test/data/nst_json_testsuite/test_parsing/y_string_unicode_escaped_double_quote.json", + // "test/data/nst_json_testsuite/test_parsing/y_string_utf16.json", + "test/data/nst_json_testsuite/test_parsing/y_string_utf8.json", + "test/data/nst_json_testsuite/test_parsing/y_string_with_del_character.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_false.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_int.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_negative_real.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_null.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_string.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_lonely_true.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_string_empty.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_trailing_newline.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_true_in_array.json", + "test/data/nst_json_testsuite/test_parsing/y_structure_whitespace_array.json", +}; + +INSTANTIATE_TEST_CASE_P(MessagePackRegressionTests, MessagePackRegressionTest, + ::testing::ValuesIn(regression_test_cases)); +#endif diff --git a/src/test/native/cpp/json/unit-pointer_access.cpp b/src/test/native/cpp/json/unit-pointer_access.cpp new file mode 100644 index 0000000000..a6a87fcc3e --- /dev/null +++ b/src/test/native/cpp/json/unit-pointer_access.cpp @@ -0,0 +1,463 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +TEST(JsonPointerTest, TypesCreate) +{ + // create a JSON value with different types + json json_types = + { + {"boolean", true}, + { + "number", { + {"integer", 42}, + {"unsigned", 42u}, + {"floating-point", 17.23} + } + }, + {"string", "Hello, world!"}, + {"array", {1, 2, 3, 4, 5}}, + {"null", nullptr} + }; +} + +// pointer access to object_t +TEST(JsonPointerTest, ObjectT) +{ + using test_type = json::object_t; + json value = {{"one", 1}, {"two", 2}}; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to const object_t +TEST(JsonPointerTest, ConstObjectT) +{ + using test_type = const json::object_t; + const json value = {{"one", 1}, {"two", 2}}; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to array_t +TEST(JsonPointerTest, ArrayT) +{ + using test_type = json::array_t; + json value = {1, 2, 3, 4}; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to const array_t +TEST(JsonPointerTest, ConstArrayT) +{ + using test_type = const json::array_t; + const json value = {1, 2, 3, 4}; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to string_t +TEST(JsonPointerTest, StringT) +{ + using test_type = json::string_t; + json value = "hello"; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to const string_t +TEST(JsonPointerTest, ConstStringT) +{ + using test_type = const json::string_t; + const json value = "hello"; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to boolean_t +TEST(JsonPointerTest, BooleanT) +{ + using test_type = json::boolean_t; + json value = false; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to const boolean_t +TEST(JsonPointerTest, ConstBooleanT) +{ + using test_type = const json::boolean_t; + const json value = false; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + //EXPECT_EQ(*p1, value.get()); + + //const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + //EXPECT_EQ(*p2, value.get()); + + //const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + //EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to number_integer_t +TEST(JsonPointerTest, IntegerT) +{ + using test_type = json::number_integer_t; + json value = 23; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to const number_integer_t +TEST(JsonPointerTest, ConstIntegerT) +{ + using test_type = const json::number_integer_t; + const json value = 23; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to number_unsigned_t +TEST(JsonPointerTest, UnsignedT) +{ + using test_type = json::number_unsigned_t; + json value = 23u; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to const number_unsigned_t +TEST(JsonPointerTest, ConstUnsignedT) +{ + using test_type = const json::number_unsigned_t; + const json value = 23u; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p1, value.get()); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p2, value.get()); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_EQ(*p3, value.get()); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); +} + +// pointer access to number_float_t +TEST(JsonPointerTest, FloatT) +{ + using test_type = json::number_float_t; + json value = 42.23; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_LT(std::fabs(*p1 - value.get()), 0.001); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_LT(std::fabs(*p2 - value.get()), 0.001); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_LT(std::fabs(*p3 - value.get()), 0.001); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); +} + +// pointer access to const number_float_t +TEST(JsonPointerTest, ConstFloatT) +{ + using test_type = const json::number_float_t; + const json value = 42.23; + + // check if pointers are returned correctly + test_type* p1 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_LT(std::fabs(*p1 - value.get()), 0.001); + + const test_type* p2 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_LT(std::fabs(*p2 - value.get()), 0.001); + + const test_type* const p3 = value.get_ptr(); + EXPECT_EQ(p1, value.get_ptr()); + EXPECT_LT(std::fabs(*p3 - value.get()), 0.001); + + // check if null pointers are returned correctly + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_EQ(value.get_ptr(), nullptr); + EXPECT_NE(value.get_ptr(), nullptr); +} diff --git a/src/test/native/cpp/json/unit-readme.cpp b/src/test/native/cpp/json/unit-readme.cpp new file mode 100644 index 0000000000..e088773bbb --- /dev/null +++ b/src/test/native/cpp/json/unit-readme.cpp @@ -0,0 +1,325 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +#include +#include +#include +#include +#include +#include +#include + +TEST(JsonReadmeTest, Basic) +{ + // create an empty structure (null) + json j; + + // add a number that is stored as double (note the implicit conversion of j to an object) + j["pi"] = 3.141; + + // add a Boolean that is stored as bool + j["happy"] = true; + + // add a string that is stored as std::string + j["name"] = "Niels"; + + // add another null object by passing nullptr + j["nothing"] = nullptr; + + // add an object inside the object + j["answer"]["everything"] = 42; + + // add an array that is stored as std::vector (using an initializer list) + j["list"] = { 1, 0, 2 }; + + // add another object (using an initializer list of pairs) + j["object"] = { {"currency", "USD"}, {"value", 42.99} }; + + // instead, you could also write (which looks very similar to the JSON above) + json j2 = + { + {"pi", 3.141}, + {"happy", true}, + {"name", "Niels"}, + {"nothing", nullptr}, + { + "answer", { + {"everything", 42} + } + }, + {"list", {1, 0, 2}}, + { + "object", { + {"currency", "USD"}, + {"value", 42.99} + } + } + }; +} + +TEST(JsonReadmeTest, Other) +{ + // ways to express the empty array [] + json empty_array_implicit = {{}}; + json empty_array_explicit = json::array(); + + // a way to express the empty object {} + json empty_object_explicit = json::object(); + + // a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]] + json array_not_object = { json::array({"currency", "USD"}), json::array({"value", 42.99}) }; +} + +TEST(JsonReadmeTest, FromToString) +{ + // create object from string literal + json j = "{ \"happy\": true, \"pi\": 3.141 }"_json; + + // or even nicer with a raw string literal + auto j2 = R"( + { + "happy": true, + "pi": 3.141 + } +)"_json; + + // or explicitly + auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }"); + + // explicit conversion to string + std::string s; + llvm::raw_string_ostream os(s); + j.dump(os); // {\"happy\":true,\"pi\":3.141} + EXPECT_EQ(os.str(), "{\"happy\":true,\"pi\":3.141}"); + + // serialization with pretty printing + // pass in the amount of spaces to indent + std::string s2; + llvm::raw_string_ostream os2(s2); + j2.dump(os2, 4); + EXPECT_EQ(os2.str(), "{\n \"happy\": true,\n \"pi\": 3.141\n}"); + // { + // "happy": true, + // "pi": 3.141 + // } +} + +TEST(JsonReadmeTest, Basic2) +{ + // create an array using push_back + json j; + j.push_back("foo"); + j.push_back(1); + j.push_back(true); + + std::string s; + llvm::raw_string_ostream os(s); + + // iterate the array + for (json::iterator it = j.begin(); it != j.end(); ++it) + { + os << *it << '\n'; + } + + // range-based for + for (auto element : j) + { + os << element << '\n'; + } + + // comparison + bool x = (j == "[\"foo\", 1, true]"_json); // true + EXPECT_EQ(x, true); + + // getter/setter + const std::string tmp = j[0]; + j[1] = 42; + bool foo = j.at(2); + EXPECT_EQ(foo, true); + + // other stuff + EXPECT_EQ(j.size(), 3u); // 3 entries + EXPECT_EQ(j.empty(), false); + EXPECT_EQ(j.type(), json::value_t::array); + j.clear(); // the array is empty again + EXPECT_EQ(j.size(), 0u); + EXPECT_EQ(j.empty(), true); + + // create an object + json o; + o["foo"] = 23; + o["bar"] = false; + o["baz"] = 3.141; + + // find an entry + if (o.find("foo") != o.end()) + { + // there is an entry with key "foo" + } +} + +TEST(JsonReadmeTest, OtherContainer) +{ + std::vector c_vector {1, 2, 3, 4}; + json j_vec(c_vector); + json j_vec2(llvm::makeArrayRef(c_vector)); + // [1, 2, 3, 4] + + std::deque c_deque {1.2f, 2.3f, 3.4f, 5.6f}; + json j_deque(c_deque); + // [1.2, 2.3, 3.4, 5.6] + + std::list c_list {true, true, false, true}; + json j_list(c_list); + // [true, true, false, true] + + std::forward_list c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543}; + json j_flist(c_flist); + // [12345678909876, 23456789098765, 34567890987654, 45678909876543] + + std::array c_array {{1, 2, 3, 4}}; + json j_array(c_array); + // [1, 2, 3, 4] + + std::set c_set {"one", "two", "three", "four", "one"}; + json j_set(c_set); // only one entry for "one" is used + // ["four", "one", "three", "two"] + + std::unordered_set c_uset {"one", "two", "three", "four", "one"}; + json j_uset(c_uset); // only one entry for "one" is used + // maybe ["two", "three", "four", "one"] + + std::multiset c_mset {"one", "two", "one", "four"}; + json j_mset(c_mset); // both entries for "one" are used + // maybe ["one", "two", "one", "four"] + + std::unordered_multiset c_umset {"one", "two", "one", "four"}; + json j_umset(c_umset); // both entries for "one" are used + // maybe ["one", "two", "one", "four"] +} + +TEST(JsonReadmeTest, MapContainer) +{ + std::map c_map { {"one", 1}, {"two", 2}, {"three", 3} }; + json j_map(c_map); + // {"one": 1, "two": 2, "three": 3} + +#if 0 + std::unordered_map c_umap { {"one", 1.2f}, {"two", 2.3f}, {"three", 3.4f} }; + json j_umap(c_umap); + // {"one": 1.2, "two": 2.3, "three": 3.4} +#endif + + std::multimap c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} }; + json j_mmap(c_mmap); // only one entry for key "three" is used + // maybe {"one": true, "two": true, "three": true} + + std::unordered_multimap c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} }; + json j_ummap(c_ummap); // only one entry for key "three" is used + // maybe {"one": true, "two": true, "three": true} +} + +TEST(JsonReadmeTest, Values) +{ + // strings + std::string s1 = "Hello, world!"; + json js = s1; + std::string s2 = js; + EXPECT_EQ(s1, s2); + + // Booleans + bool b1 = true; + json jb = b1; + bool b2 = jb; + EXPECT_EQ(b1, b2); + + // numbers + int i = 42; + json jn = i; + double f = jn; + EXPECT_EQ(i, f); + + // etc. + + std::string vs = js.get(); + bool vb = jb.get(); + int vi = jn.get(); + EXPECT_EQ(s1, vs); + EXPECT_EQ(b1, vb); + EXPECT_EQ(i, vi); + + // etc. +} + +#if 0 +TEST(JsonReadmeTest, DiffPatch) +{ + // a JSON value + json j_original = R"({ + "baz": ["one", "two", "three"], + "foo": "bar" +})"_json; + + // access members with a JSON pointer (RFC 6901) + j_original["/baz/1"_json_pointer]; + // "two" + + // a JSON patch (RFC 6902) + json j_patch = R"([ + { "op": "replace", "path": "/baz", "value": "boo" }, + { "op": "add", "path": "/hello", "value": ["world"] }, + { "op": "remove", "path": "/foo"} +])"_json; + + // apply the patch + json j_result = j_original.patch(j_patch); + // { + // "baz": "boo", + // "hello": ["world"] + // } + + // calculate a JSON patch from two JSON values + json::diff(j_result, j_original); + // [ + // { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] }, + // { "op":"remove","path":"/hello" }, + // { "op":"add","path":"/foo","value":"bar" } + // ] +} +#endif diff --git a/src/test/native/cpp/json/unit-reference_access.cpp b/src/test/native/cpp/json/unit-reference_access.cpp new file mode 100644 index 0000000000..1cea68946d --- /dev/null +++ b/src/test/native/cpp/json/unit-reference_access.cpp @@ -0,0 +1,197 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +// reference access to object_t +TEST(JsonReferenceTest, ObjectT) +{ + using test_type = json::object_t; + json value = {{"one", 1}, {"two", 2}}; + + // check if references are returned correctly + test_type& p1 = value.get_ref(); + EXPECT_EQ(&p1, value.get_ptr()); + EXPECT_EQ(p1, value.get()); + + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); + + // check if mismatching references throw correctly + EXPECT_NO_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); +} + +// const reference access to const object_t +TEST(JsonReferenceTest, ConstObjectT) +{ + using test_type = json::object_t; + const json value = {{"one", 1}, {"two", 2}}; + + // this should not compile + // test_type& p1 = value.get_ref(); + + // check if references are returned correctly + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); +} + +// reference access to array_t +TEST(JsonReferenceTest, ArrayT) +{ + using test_type = json::array_t; + json value = {1, 2, 3, 4}; + + // check if references are returned correctly + test_type& p1 = value.get_ref(); + EXPECT_EQ(&p1, value.get_ptr()); + EXPECT_EQ(p1, value.get()); + + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); + + // check if mismatching references throw correctly + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_NO_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); +} + +// reference access to string_t +TEST(JsonReferenceTest, StringT) +{ + using test_type = json::string_t; + json value = "hello"; + + // check if references are returned correctly + test_type& p1 = value.get_ref(); + EXPECT_EQ(&p1, value.get_ptr()); + EXPECT_EQ(p1, value.get()); + + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); + + // check if mismatching references throw correctly + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_NO_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); +} + +// reference access to boolean_t +TEST(JsonReferenceTest, BooleanT) +{ + using test_type = json::boolean_t; + json value = false; + + // check if references are returned correctly + test_type& p1 = value.get_ref(); + EXPECT_EQ(&p1, value.get_ptr()); + EXPECT_EQ(p1, value.get()); + + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); + + // check if mismatching references throw correctly + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_NO_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); +} + +// reference access to number_integer_t +TEST(JsonReferenceTest, IntegerT) +{ + using test_type = json::number_integer_t; + json value = 23; + + // check if references are returned correctly + test_type& p1 = value.get_ref(); + EXPECT_EQ(&p1, value.get_ptr()); + EXPECT_EQ(p1, value.get()); + + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); + + // check if mismatching references throw correctly + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_NO_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); +} + +// reference access to number_float_t +TEST(JsonReferenceTest, FloatT) +{ + using test_type = json::number_float_t; + json value = 42.23; + + // check if references are returned correctly + test_type& p1 = value.get_ref(); + EXPECT_EQ(&p1, value.get_ptr()); + EXPECT_EQ(p1, value.get()); + + const test_type& p2 = value.get_ref(); + EXPECT_EQ(&p2, value.get_ptr()); + EXPECT_EQ(p2, value.get()); + + // check if mismatching references throw correctly + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_ANY_THROW(value.get_ref()); + EXPECT_NO_THROW(value.get_ref()); +} diff --git a/src/test/native/cpp/json/unit-unicode.cpp b/src/test/native/cpp/json/unit-unicode.cpp new file mode 100644 index 0000000000..1c4546a822 --- /dev/null +++ b/src/test/native/cpp/json/unit-unicode.cpp @@ -0,0 +1,1092 @@ +/*----------------------------------------------------------------------------*/ +/* Modifications Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ (test suite) +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 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. +*/ + +#include "gtest/gtest.h" + +#include "unit-json.h" +using wpi::json; + +#include "llvm/Format.h" +#include "llvm/StringExtras.h" + +#include + +// create and check a JSON string with up to four UTF-8 bytes +::testing::AssertionResult check_utf8string(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1) +{ + std::string json_string = "\""; + + json_string += std::string(1, static_cast(byte1)); + + if (byte2 != -1) + { + json_string += std::string(1, static_cast(byte2)); + } + + if (byte3 != -1) + { + json_string += std::string(1, static_cast(byte3)); + } + + if (byte4 != -1) + { + json_string += std::string(1, static_cast(byte4)); + } + + json_string += "\""; + + const char* basemsg = ""; + + try { + json::parse(json_string); + } catch (json::parse_error) { + if (success_expected) + { + basemsg = "parse_error"; + goto error; + } + return ::testing::AssertionSuccess(); + } catch (...) { + basemsg = "other exception"; + goto error; + } + + if (success_expected) + { + return ::testing::AssertionSuccess(); + } + basemsg = "expected failure"; + +error: + auto result = ::testing::AssertionFailure(); + result << basemsg << " with {" << llvm::utohexstr(byte1); + if (byte2 != -1) + { + result << ',' << llvm::utohexstr(byte2); + } + if (byte3 != -1) + { + result << ',' << llvm::utohexstr(byte3); + } + if (byte4 != -1) + { + result << ',' << llvm::utohexstr(byte4); + } + result << '}'; + return result; +} + +/* +RFC 3629 describes in Sect. 4 the syntax of UTF-8 byte sequences as +follows: + + A UTF-8 string is a sequence of octets representing a sequence of UCS + characters. An octet sequence is valid UTF-8 only if it matches the + following syntax, which is derived from the rules for encoding UTF-8 + and is expressed in the ABNF of [RFC2234]. + + UTF8-octets = *( UTF8-char ) + UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4 + UTF8-1 = %x00-7F + UTF8-2 = %xC2-DF UTF8-tail + UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / + %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) + UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / + %xF4 %x80-8F 2( UTF8-tail ) + UTF8-tail = %x80-BF +*/ + +// ill-formed first byte +TEST(JsonUnicodeRfc3629Test, IllFormedFirstByte) +{ + for (int byte1 = 0x80; byte1 <= 0xC1; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } + + for (int byte1 = 0xF5; byte1 <= 0xFF; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// UTF8-1 (x00-x7F), well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_1WellFormed) +{ + for (int byte1 = 0x00; byte1 <= 0x7F; ++byte1) + { + // unescaped control characters are parse errors in JSON + if (0x00 <= byte1 && byte1 <= 0x1F) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + continue; + } + + // a single quote is a parse error in JSON + if (byte1 == 0x22) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + continue; + } + + // a single backslash is a parse error in JSON + if (byte1 == 0x5C) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + continue; + } + + // all other characters are OK + EXPECT_TRUE(check_utf8string(true, byte1)); + } +} + +// UTF8-2 (xC2-xDF UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_2WellFormed) +{ + for (int byte1 = 0xC2; byte1 <= 0xDF; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2)); + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_2Missing2) +{ + for (int byte1 = 0xC2; byte1 <= 0xDF; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, Utf8_2Wrong2) +{ + for (int byte1 = 0xC2; byte1 <= 0xDF; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x80 <= byte2 && byte2 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// UTF8-3 (xE0 xA0-BF UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_3AWellFormed) +{ + for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1) + { + for (int byte2 = 0xA0; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3AMissing2) +{ + for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3AMissing3) +{ + for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1) + { + for (int byte2 = 0xA0; byte2 <= 0xBF; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3AWrong2) +{ + for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0xA0 <= byte2 && byte2 <= 0xBF) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3AWrong3) +{ + for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1) + { + for (int byte2 = 0xA0; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// UTF8-3 (xE1-xEC UTF8-tail UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_3BWellFormed) +{ + for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3BMissing2) +{ + for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3BMissing3) +{ + for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_3BWrong2) +{ + for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x80 <= byte2 && byte2 <= 0xBF) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_3BWrong3) +{ + for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// UTF8-3 (xED x80-9F UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_3CWellFormed) +{ + for (int byte1 = 0xED; byte1 <= 0xED; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x9F; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3CMissing2) +{ + for (int byte1 = 0xED; byte1 <= 0xED; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3CMissing3) +{ + for (int byte1 = 0xED; byte1 <= 0xED; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x9F; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3CWrong2) +{ + for (int byte1 = 0xED; byte1 <= 0xED; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x80 <= byte2 && byte2 <= 0x9F) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3CWrong3) +{ + for (int byte1 = 0xED; byte1 <= 0xED; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x9F; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// UTF8-3 (xEE-xEF UTF8-tail UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_3DWellFormed) +{ + for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3DMissing2) +{ + for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3DMissing3) +{ + for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, Utf8_3DWrong2) +{ + for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x80 <= byte2 && byte2 <= 0xBF) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, Utf8_3DWrong3) +{ + for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// UTF8-4 (xF0 x90-BF UTF8-tail UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_4AWellFormed) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_4AMissing2) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_4AMissing3) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: missing fourth byte +TEST(JsonUnicodeRfc3629Test, Utf8_4AMissing4) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_4AWrong2) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x90 <= byte2 && byte2 <= 0xBF) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_4AWrong3) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: wrong fourth byte +TEST(JsonUnicodeRfc3629Test, Utf8_4AWrong4) +{ + for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1) + { + for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x00; byte4 <= 0xFF; ++byte4) + { + // skip fourth second byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// UTF8-4 (xF1-F3 UTF8-tail UTF8-tail UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_4BWellFormed) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_4BMissing2) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_4BMissing3) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: missing fourth byte +TEST(JsonUnicodeRfc3629Test, Utf8_4BMissing4) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_4BWrong2) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x80 <= byte2 && byte2 <= 0xBF) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_4BWrong3) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: wrong fourth byte +TEST(JsonUnicodeRfc3629Test, Utf8_4BWrong4) +{ + for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x00; byte4 <= 0xFF; ++byte4) + { + // skip correct fourth byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// UTF8-4 (xF4 x80-8F UTF8-tail UTF8-tail) +// well-formed +TEST(JsonUnicodeRfc3629Test, Utf8_4CWellFormed) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(true, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: missing second byte +TEST(JsonUnicodeRfc3629Test, Utf8_4CMissing2) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + EXPECT_TRUE(check_utf8string(false, byte1)); + } +} + +// ill-formed: missing third byte +TEST(JsonUnicodeRfc3629Test, Utf8_4CMissing3) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2)); + } + } +} + +// ill-formed: missing fourth byte +TEST(JsonUnicodeRfc3629Test, Utf8_4CMissing4) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3)); + } + } + } +} + +// ill-formed: wrong second byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_4CWrong2) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2) + { + // skip correct second byte + if (0x80 <= byte2 && byte2 <= 0x8F) + { + continue; + } + + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: wrong third byte +TEST(JsonUnicodeRfc3629Test, DISABLED_Utf8_4CWrong3) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) + { + for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3) + { + // skip correct third byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4) + { + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// ill-formed: wrong fourth byte +TEST(JsonUnicodeRfc3629Test, Utf8_4CWrong4) +{ + for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) + { + for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) + { + for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) + { + for (int byte4 = 0x00; byte4 <= 0xFF; ++byte4) + { + // skip correct fourth byte + if (0x80 <= byte3 && byte3 <= 0xBF) + { + continue; + } + + EXPECT_TRUE(check_utf8string(false, byte1, byte2, byte3, byte4)); + } + } + } + } +} + +// \\uxxxx sequences + +// create an escaped string from a code point +static std::string codepoint_to_unicode(std::size_t cp) +{ + // code points are represented as a six-character sequence: a + // reverse solidus, followed by the lowercase letter u, followed + // by four hexadecimal digits that encode the character's code + // point + std::string s; + llvm::raw_string_ostream ss(s); + ss << "\\u" << llvm::format_hex_no_prefix(cp, 4); + ss.flush(); + return s; +} + +// correct sequences +TEST(JsonUnicodeCodepointTest, DISABLED_Correct) +{ + // generate all UTF-8 code points; in total, 1112064 code points are + // generated: 0x1FFFFF code points - 2048 invalid values between + // 0xD800 and 0xDFFF. + for (std::size_t cp = 0; cp <= 0x10FFFFu; ++cp) + { + // string to store the code point as in \uxxxx format + std::string json_text = "\""; + + // decide whether to use one or two \uxxxx sequences + if (cp < 0x10000u) + { + // The Unicode standard permanently reserves these code point + // values for UTF-16 encoding of the high and low surrogates, and + // they will never be assigned a character, so there should be no + // reason to encode them. The official Unicode standard says that + // no UTF forms, including UTF-16, can encode these code points. + if (cp >= 0xD800u && cp <= 0xDFFFu) + { + // if we would not skip these code points, we would get a + // "missing low surrogate" exception + continue; + } + + // code points in the Basic Multilingual Plane can be + // represented with one \uxxxx sequence + json_text += codepoint_to_unicode(cp); + } + else + { + // To escape an extended character that is not in the Basic + // Multilingual Plane, the character is represented as a + // 12-character sequence, encoding the UTF-16 surrogate pair + const auto codepoint1 = 0xd800u + (((cp - 0x10000u) >> 10) & 0x3ffu); + const auto codepoint2 = 0xdc00u + ((cp - 0x10000u) & 0x3ffu); + json_text += codepoint_to_unicode(codepoint1) + codepoint_to_unicode(codepoint2); + } + + json_text += "\""; + SCOPED_TRACE(json_text); + EXPECT_NO_THROW(json::parse(json_text)); + } +} + +#if 0 +// incorrect sequences +// high surrogate without low surrogate +TEST(JsonUnicodeCodepointTest, IncorrectHighMissingLow) +{ + // D800..DBFF are high surrogates and must be followed by low + // surrogates DC00..DFFF; here, nothing follows + for (std::size_t cp = 0xD800u; cp <= 0xDBFFu; ++cp) + { + std::string json_text = "\"" + codepoint_to_unicode(cp) + "\""; + SCOPED_TRACE(json_text); + EXPECT_THROW(json::parse(json_text), json::parse_error); + } +} + +// high surrogate with wrong low surrogate +TEST(JsonUnicodeCodepointTest, IncorrectHighWrongLow) +{ + // D800..DBFF are high surrogates and must be followed by low + // surrogates DC00..DFFF; here a different sequence follows + for (std::size_t cp1 = 0xD800u; cp1 <= 0xDBFFu; ++cp1) + { + for (std::size_t cp2 = 0x0000u; cp2 <= 0xFFFFu; ++cp2) + { + if (0xDC00u <= cp2 && cp2 <= 0xDFFFu) + { + continue; + } + + std::string json_text = "\"" + codepoint_to_unicode(cp1) + codepoint_to_unicode(cp2) + "\""; + SCOPED_TRACE(json_text); + EXPECT_THROW(json::parse(json_text), json::parse_error); + } + } +} + +// low surrogate without high surrogate +TEST(JsonUnicodeCodepointTest, IncorrectLowMissingHigh) +{ + // low surrogates DC00..DFFF must follow high surrogates; here, + // they occur alone + for (std::size_t cp = 0xDC00u; cp <= 0xDFFFu; ++cp) + { + std::string json_text = "\"" + codepoint_to_unicode(cp) + "\""; + SCOPED_TRACE(json_text); + EXPECT_THROW(json::parse(json_text), json::parse_error); + } +} +#endif + +#if 0 +// read all unicode characters +TEST(JsonUnicodeTest, ReadAllUnicode) +{ + // read a file with all unicode characters stored as single-character + // strings in a JSON array + std::ifstream f("test/data/json_nlohmann_tests/all_unicode.json"); + json j; + CHECK_NOTHROW(f >> j); + + // the array has 1112064 + 1 elemnts (a terminating "null" value) + // Note: 1112064 = 0x1FFFFF code points - 2048 invalid values between + // 0xD800 and 0xDFFF. + CHECK(j.size() == 1112065); + + SECTION("check JSON Pointers") + { + for (auto s : j) + { + // skip non-string JSON values + if (not s.is_string()) + { + continue; + } + + std::string ptr = s; + + // tilde must be followed by 0 or 1 + if (ptr == "~") + { + ptr += "0"; + } + + // JSON Pointers must begin with "/" + ptr = "/" + ptr; + + CHECK_NOTHROW(json::json_pointer("/" + ptr)); + + // check escape/unescape roundtrip + auto escaped = json::json_pointer::escape(ptr); + json::json_pointer::unescape(escaped); + CHECK(escaped == ptr); + } + } +} + +// ignore byte-order-mark +// in a stream +TEST(JsonUnicodeTest, IgnoreBOMStream) +{ + // read a file with a UTF-8 BOM + std::ifstream f("test/data/json_nlohmann_tests/bom.json"); + json j; + EXPECT_NO_THROW(f >> j); +} + +// with an iterator +TEST(JsonUnicodeTest, IgnoreBOMIterator) +{ + std::string i = "\xef\xbb\xbf{\n \"foo\": true\n}"; + EXPECT_NO_THROW(json::parse(i.begin(), i.end())); +} +#endif +// error for incomplete/wrong BOM +TEST(JsonUnicodeTest, WrongBOM) +{ + EXPECT_THROW(json::parse("\xef\xbb"), json::parse_error); + EXPECT_THROW(json::parse("\xef\xbb\xbb"), json::parse_error); +}