keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/rbegin.cpp
.cpp
343
17
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create an array value json array = {1, 2, 3, 4, 5}; // get an iterator to the reverse-beginning json::reverse_iterator it = array.rbegin(); // serialize the element that the iterator points to std::cout << *it << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/cbegin.cpp
.cpp
343
17
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create an array value const json array = {1, 2, 3, 4, 5}; // get an iterator to the first element json::const_iterator it = array.cbegin(); // serialize the element that the iterator points to std::cout << *it << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_spaceship__const_reference.c++20.cpp
.cpp
1,165
42
#include <compare> #include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; const char* to_string(const std::partial_ordering& po) { if (std::is_lt(po)) { return "less"; } else if (std::is_gt(po)) { return "greater"; } else if (std::is_eq(po)) { return "equivalent"; } return "unordered"; } int main() { // create several JSON values json array_1 = {1, 2, 3}; json array_2 = {1, 2, 4}; json object_1 = {{"A", "a"}, {"B", "b"}}; json object_2 = {{"B", "b"}, {"A", "a"}}; json number = 17; json string = "foo"; json discarded = json(json::value_t::discarded); // output values and comparisons std::cout << array_1 << " <=> " << array_2 << " := " << to_string(array_1 <=> array_2) << '\n'; // *NOPAD* std::cout << object_1 << " <=> " << object_2 << " := " << to_string(object_1 <=> object_2) << '\n'; // *NOPAD* std::cout << string << " <=> " << number << " := " << to_string(string <=> number) << '\n'; // *NOPAD* std::cout << string << " <=> " << discarded << " := " << to_string(string <=> discarded) << '\n'; // *NOPAD* }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_discarded.cpp
.cpp
991
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_unsigned_integer = 12345678987654321u; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_discarded() std::cout << std::boolalpha; std::cout << j_null.is_discarded() << '\n'; std::cout << j_boolean.is_discarded() << '\n'; std::cout << j_number_integer.is_discarded() << '\n'; std::cout << j_number_unsigned_integer.is_discarded() << '\n'; std::cout << j_number_float.is_discarded() << '\n'; std::cout << j_object.is_discarded() << '\n'; std::cout << j_array.is_discarded() << '\n'; std::cout << j_string.is_discarded() << '\n'; std::cout << j_binary.is_discarded() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/number_integer_t.cpp
.cpp
221
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<std::int64_t, json::number_integer_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/swap__reference.cpp
.cpp
372
19
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create two JSON values json j1 = {1, 2, 3, 4, 5}; json j2 = {{"pi", 3.141592653589793}, {"e", 2.718281828459045}}; // swap the values j1.swap(j2); // output the values std::cout << "j1 = " << j1 << '\n'; std::cout << "j2 = " << j2 << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/from_bson.cpp
.cpp
635
22
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create byte vector std::vector<std::uint8_t> v = {0x1b, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // deserialize it with BSON json j = json::from_bson(v); // print the deserialized JSON value std::cout << std::setw(2) << j << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/back.cpp
.cpp
1,049
39
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_object_empty(json::value_t::object); json j_array = {1, 2, 4, 8, 16}; json j_array_empty(json::value_t::array); json j_string = "Hello, world"; // call back() std::cout << j_boolean.back() << '\n'; std::cout << j_number_integer.back() << '\n'; std::cout << j_number_float.back() << '\n'; std::cout << j_object.back() << '\n'; //std::cout << j_object_empty.back() << '\n'; // undefined behavior std::cout << j_array.back() << '\n'; //std::cout << j_array_empty.back() << '\n'; // undefined behavior std::cout << j_string.back() << '\n'; // back() called on a null value try { json j_null; j_null.back(); } catch (json::invalid_iterator& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/byte_container_with_subtype__byte_container_with_subtype.cpp
.cpp
648
24
#include <iostream> #include <nlohmann/json.hpp> // define a byte container based on std::vector using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>; using json = nlohmann::json; int main() { // (1) create empty container auto c1 = byte_container_with_subtype(); std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}}; // (2) create container auto c2 = byte_container_with_subtype(bytes); // (3) create container with subtype auto c3 = byte_container_with_subtype(bytes, 42); std::cout << json(c1) << "\n" << json(c2) << "\n" << json(c3) << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/patch_inplace.cpp
.cpp
772
36
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // the original document json doc = R"( { "baz": "qux", "foo": "bar" } )"_json; // the patch json patch = R"( [ { "op": "replace", "path": "/baz", "value": "boo" }, { "op": "add", "path": "/hello", "value": ["world"] }, { "op": "remove", "path": "/foo"} ] )"_json; // output original document std::cout << "Before\n" << std::setw(4) << doc << std::endl; // apply the patch doc.patch_inplace(patch); // output patched document std::cout << "\nAfter\n" << std::setw(4) << doc << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/contains__object_t_key_type.cpp
.cpp
563
19
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // create some JSON values json j_object = R"( {"key": "value"} )"_json; json j_array = R"( [1, 2, 3] )"_json; // call contains std::cout << std::boolalpha << "j_object contains 'key': " << j_object.contains("key") << '\n' << "j_object contains 'another': " << j_object.contains("another") << '\n' << "j_array contains 'key': " << j_array.contains("key") << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/unflatten.cpp
.cpp
553
27
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON value json j_flattened = { {"/answer/everything", 42}, {"/happy", true}, {"/list/0", 1}, {"/list/1", 0}, {"/list/2", 2}, {"/name", "Niels"}, {"/nothing", nullptr}, {"/object/currency", "USD"}, {"/object/value", 42.99}, {"/pi", 3.141} }; // call unflatten() std::cout << std::setw(4) << j_flattened.unflatten() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/update.cpp
.cpp
691
25
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // create two JSON objects json o1 = R"( {"color": "red", "price": 17.99, "names": {"de": "Flugzeug"}} )"_json; json o2 = R"( {"color": "blue", "speed": 100, "names": {"en": "plane"}} )"_json; json o3 = o1; // add all keys from o2 to o1 (updating "color", replacing "names") o1.update(o2); // add all keys from o2 to o1 (updating "color", merging "names") o3.update(o2, true); // output updated object o1 and o3 std::cout << std::setw(2) << o1 << '\n'; std::cout << std::setw(2) << o3 << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_number_unsigned.cpp
.cpp
1,051
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_unsigned_integer = 12345678987654321u; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_number_unsigned() std::cout << std::boolalpha; std::cout << j_null.is_number_unsigned() << '\n'; std::cout << j_boolean.is_number_unsigned() << '\n'; std::cout << j_number_integer.is_number_unsigned() << '\n'; std::cout << j_number_unsigned_integer.is_number_unsigned() << '\n'; std::cout << j_number_float.is_number_unsigned() << '\n'; std::cout << j_object.is_number_unsigned() << '\n'; std::cout << j_array.is_number_unsigned() << '\n'; std::cout << j_string.is_number_unsigned() << '\n'; std::cout << j_binary.is_number_unsigned() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/json_base_class_t.cpp
.cpp
2,235
89
#include <iostream> #include <nlohmann/json.hpp> class visitor_adaptor_with_metadata { public: template <class Fnc> void visit(const Fnc& fnc) const; int metadata = 42; private: template <class Ptr, class Fnc> void do_visit(const Ptr& ptr, const Fnc& fnc) const; }; using json = nlohmann::basic_json < std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, double, std::allocator, nlohmann::adl_serializer, std::vector<std::uint8_t>, visitor_adaptor_with_metadata >; template <class Fnc> void visitor_adaptor_with_metadata::visit(const Fnc& fnc) const { do_visit(json::json_pointer{}, fnc); } template <class Ptr, class Fnc> void visitor_adaptor_with_metadata::do_visit(const Ptr& ptr, const Fnc& fnc) const { using value_t = nlohmann::detail::value_t; const json& j = *static_cast<const json*>(this); switch (j.type()) { case value_t::object: fnc(ptr, j); for (const auto& entry : j.items()) { entry.value().do_visit(ptr / entry.key(), fnc); } break; case value_t::array: fnc(ptr, j); for (std::size_t i = 0; i < j.size(); ++i) { j.at(i).do_visit(ptr / std::to_string(i), fnc); } break; case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: fnc(ptr, j); break; case value_t::discarded: default: break; } } int main() { // create a json object json j; j["null"]; j["object"]["uint"] = 1U; j["object"].metadata = 21; // visit and output j.visit( [&](const json::json_pointer & p, const json & j) { std::cout << (p.empty() ? std::string{"/"} : p.to_string()) << " - metadata = " << j.metadata << " -> " << j.dump() << '\n'; }); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__equal__nullptr_t.cpp
.cpp
698
23
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create several JSON values json array = {1, 2, 3}; json object = {{"A", "a"}, {"B", "b"}}; json number = 17; json string = "foo"; json null; // output values and comparisons std::cout << std::boolalpha; std::cout << array << " == nullptr " << (array == nullptr) << '\n'; std::cout << object << " == nullptr " << (object == nullptr) << '\n'; std::cout << number << " == nullptr " << (number == nullptr) << '\n'; std::cout << string << " == nullptr " << (string == nullptr) << '\n'; std::cout << null << " == nullptr " << (null == nullptr) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/max_size.cpp
.cpp
707
26
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; // call max_size() std::cout << j_null.max_size() << '\n'; std::cout << j_boolean.max_size() << '\n'; std::cout << j_number_integer.max_size() << '\n'; std::cout << j_number_float.max_size() << '\n'; std::cout << j_object.max_size() << '\n'; std::cout << j_array.max_size() << '\n'; std::cout << j_string.max_size() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/sax_parse.cpp
.cpp
3,319
132
#include <iostream> #include <iomanip> #include <sstream> #include <nlohmann/json.hpp> using json = nlohmann::json; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json::json_sax_t { public: std::vector<std::string> events; bool null() override { events.push_back("null()"); return true; } bool boolean(bool val) override { events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")"); return true; } bool number_integer(number_integer_t val) override { events.push_back("number_integer(val=" + std::to_string(val) + ")"); return true; } bool number_unsigned(number_unsigned_t val) override { events.push_back("number_unsigned(val=" + std::to_string(val) + ")"); return true; } bool number_float(number_float_t val, const string_t& s) override { events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")"); return true; } bool string(string_t& val) override { events.push_back("string(val=" + val + ")"); return true; } bool start_object(std::size_t elements) override { events.push_back("start_object(elements=" + std::to_string(elements) + ")"); return true; } bool end_object() override { events.push_back("end_object()"); return true; } bool start_array(std::size_t elements) override { events.push_back("start_array(elements=" + std::to_string(elements) + ")"); return true; } bool end_array() override { events.push_back("end_array()"); return true; } bool key(string_t& val) override { events.push_back("key(val=" + val + ")"); return true; } bool binary(json::binary_t& val) override { events.push_back("binary(val=[...])"); return true; } bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override { events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")"); return false; } }; int main() { // a JSON text auto text = R"( { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": 100 }, "Animated" : false, "IDs": [116, 943, 234, -38793], "DeletionDate": null, "Distance": 12.723374634 } }] )"; // create a SAX event consumer object sax_event_consumer sec; // parse JSON bool result = json::sax_parse(text, &sec); // output the recorded events for (auto& event : sec.events) { std::cout << event << "\n"; } // output the result of sax_parse std::cout << "\nresult: " << std::boolalpha << result << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/type_error.cpp
.cpp
427
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { try { // calling push_back() on a string value json j = "string"; j.push_back("another string"); } catch (json::type_error& e) { // output exception information std::cout << "message: " << e.what() << '\n' << "exception id: " << e.id << std::endl; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/accept__string.cpp
.cpp
466
27
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // a valid JSON text auto valid_text = R"( { "numbers": [1, 2, 3] } )"; // an invalid JSON text auto invalid_text = R"( { "strings": ["extra", "comma", ] } )"; std::cout << std::boolalpha << json::accept(valid_text) << ' ' << json::accept(invalid_text) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/push_back__object_t__value.cpp
.cpp
584
26
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json object = {{"one", 1}, {"two", 2}}; json null; // print values std::cout << object << '\n'; std::cout << null << '\n'; // add values object.push_back(json::object_t::value_type("three", 3)); object += json::object_t::value_type("four", 4); null += json::object_t::value_type("A", "a"); null += json::object_t::value_type("B", "b"); // print values std::cout << object << '\n'; std::cout << null << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/basic_json__list_init_t.cpp
.cpp
593
22
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_empty_init_list = json({}); json j_object = { {"one", 1}, {"two", 2} }; json j_array = {1, 2, 3, 4}; json j_nested_object = { {"one", {1}}, {"two", {1, 2}} }; json j_nested_array = { {{1}, "one"}, {{1, 2}, "two"} }; // serialize the JSON value std::cout << j_empty_init_list << '\n'; std::cout << j_object << '\n'; std::cout << j_array << '\n'; std::cout << j_nested_object << '\n'; std::cout << j_nested_array << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/swap__string_t.cpp
.cpp
438
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON value json value = { "the good", "the bad", "the ugly" }; // create string_t json::string_t string = "the fast"; // swap the object stored in the JSON value value[1].swap(string); // output the values std::cout << "value = " << value << '\n'; std::cout << "string = " << string << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/clear.cpp
.cpp
832
35
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; // call clear() j_null.clear(); j_boolean.clear(); j_number_integer.clear(); j_number_float.clear(); j_object.clear(); j_array.clear(); j_string.clear(); // serialize the cleared values() std::cout << j_null << '\n'; std::cout << j_boolean << '\n'; std::cout << j_number_integer << '\n'; std::cout << j_number_float << '\n'; std::cout << j_object << '\n'; std::cout << j_array << '\n'; std::cout << j_string << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_ltlt__json_pointer.cpp
.cpp
246
14
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON poiner json::json_pointer ptr("/foo/bar/baz"); // write string representation to stream std::cout << ptr << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_object.cpp
.cpp
961
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_number_unsigned_integer = 12345678987654321u; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_object() std::cout << std::boolalpha; std::cout << j_null.is_object() << '\n'; std::cout << j_boolean.is_object() << '\n'; std::cout << j_number_integer.is_object() << '\n'; std::cout << j_number_unsigned_integer.is_object() << '\n'; std::cout << j_number_float.is_object() << '\n'; std::cout << j_object.is_object() << '\n'; std::cout << j_array.is_object() << '\n'; std::cout << j_string.is_object() << '\n'; std::cout << j_binary.is_object() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/erase__size_type.cpp
.cpp
259
17
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON array json j_array = {0, 1, 2, 3, 4, 5}; // call erase() j_array.erase(2); // print values std::cout << j_array << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_number.cpp
.cpp
961
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_unsigned_integer = 12345678987654321u; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_number() std::cout << std::boolalpha; std::cout << j_null.is_number() << '\n'; std::cout << j_boolean.is_number() << '\n'; std::cout << j_number_integer.is_number() << '\n'; std::cout << j_number_unsigned_integer.is_number() << '\n'; std::cout << j_number_float.is_number() << '\n'; std::cout << j_object.is_number() << '\n'; std::cout << j_array.is_number() << '\n'; std::cout << j_string.is_number() << '\n'; std::cout << j_binary.is_number() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/contains__json_pointer.cpp
.cpp
1,117
44
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // create a JSON value json j = { {"number", 1}, {"string", "foo"}, {"array", {1, 2}} }; std::cout << std::boolalpha << j.contains("/number"_json_pointer) << '\n' << j.contains("/string"_json_pointer) << '\n' << j.contains("/array"_json_pointer) << '\n' << j.contains("/array/1"_json_pointer) << '\n' << j.contains("/array/-"_json_pointer) << '\n' << j.contains("/array/4"_json_pointer) << '\n' << j.contains("/baz"_json_pointer) << std::endl; try { // try to use an array index with leading '0' j.contains("/array/01"_json_pointer); } catch (json::parse_error& e) { std::cout << e.what() << '\n'; } try { // try to use an array index that is not a number j.contains("/array/one"_json_pointer); } catch (json::parse_error& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/swap__array_t.cpp
.cpp
444
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON value json value = {{"array", {1, 2, 3, 4}}}; // create an array_t json::array_t array = {"Snap", "Crackle", "Pop"}; // swap the array stored in the JSON value value["array"].swap(array); // output the values std::cout << "value = " << value << '\n'; std::cout << "array = " << array << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/crend.cpp
.cpp
413
20
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create an array value json array = {1, 2, 3, 4, 5}; // get an iterator to the reverse-end json::const_reverse_iterator it = array.crend(); // increment the iterator to point to the first element --it; // serialize the element that the iterator points to std::cout << *it << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/value__keytype.c++17.cpp
.cpp
889
33
#include <iostream> #include <string_view> #include <nlohmann/json.hpp> using namespace std::string_view_literals; using json = nlohmann::json; int main() { // create a JSON object with different entry types json j = { {"integer", 1}, {"floating", 42.23}, {"string", "hello world"}, {"boolean", true}, {"object", {{"key1", 1}, {"key2", 2}}}, {"array", {1, 2, 3}} }; // access existing values int v_integer = j.value("integer"sv, 0); double v_floating = j.value("floating"sv, 47.11); // access nonexisting values and rely on default value std::string v_string = j.value("nonexisting"sv, "oops"); bool v_boolean = j.value("nonexisting"sv, false); // output values std::cout << std::boolalpha << v_integer << " " << v_floating << " " << v_string << " " << v_boolean << "\n"; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/insert__ilist.cpp
.cpp
367
18
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON array json v = {1, 2, 3, 4}; // insert range from v2 before the end of array v auto new_pos = v.insert(v.end(), {7, 8, 9}); // output new array and result of insert call std::cout << *new_pos << '\n'; std::cout << v << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/json_pointer__push_back.cpp
.cpp
419
22
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create empty JSON Pointer json::json_pointer ptr; std::cout << "\"" << ptr << "\"\n"; // call push_back() ptr.push_back("foo"); std::cout << "\"" << ptr << "\"\n"; ptr.push_back("0"); std::cout << "\"" << ptr << "\"\n"; ptr.push_back("bar"); std::cout << "\"" << ptr << "\"\n"; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/at__size_type_const.cpp
.cpp
755
38
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON array const json array = {"first", "2nd", "third", "fourth"}; // output element at index 2 (third element) std::cout << array.at(2) << '\n'; // exception type_error.304 try { // use at() on a non-array type const json str = "I am a string"; std::cout << str.at(0) << '\n'; } catch (json::type_error& e) { std::cout << e.what() << '\n'; } // exception out_of_range.401 try { // try to read beyond the array limit std::cout << array.at(5) << '\n'; } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/find__keytype.c++17.cpp
.cpp
617
23
#include <iostream> #include <string_view> #include <nlohmann/json.hpp> using namespace std::string_view_literals; using json = nlohmann::json; int main() { // create a JSON object json j_object = {{"one", 1}, {"two", 2}}; // call find auto it_two = j_object.find("two"sv); auto it_three = j_object.find("three"sv); // print values std::cout << std::boolalpha; std::cout << "\"two\" was found: " << (it_two != j_object.end()) << '\n'; std::cout << "value at key \"two\": " << *it_two << '\n'; std::cout << "\"three\" was found: " << (it_three != j_object.end()) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/binary_t.cpp
.cpp
265
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>, json::binary_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/nlohmann_define_type_intrusive_with_default_explicit.cpp
.cpp
1,755
56
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; namespace ns { class person { private: std::string name = "John Doe"; std::string address = "123 Fake St"; int age = -1; public: person() = default; person(std::string name_, std::string address_, int age_) : name(std::move(name_)), address(std::move(address_)), age(age_) {} friend void to_json(nlohmann::json& nlohmann_json_j, const person& nlohmann_json_t) { nlohmann_json_j["name"] = nlohmann_json_t.name; nlohmann_json_j["address"] = nlohmann_json_t.address; nlohmann_json_j["age"] = nlohmann_json_t.age; } friend void from_json(const nlohmann::json& nlohmann_json_j, person& nlohmann_json_t) { person nlohmann_json_default_obj; nlohmann_json_t.name = nlohmann_json_j.value("name", nlohmann_json_default_obj.name); nlohmann_json_t.address = nlohmann_json_j.value("address", nlohmann_json_default_obj.address); nlohmann_json_t.age = nlohmann_json_j.value("age", nlohmann_json_default_obj.age); } }; } // namespace ns int main() { ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60}; // serialization: person -> json json j = p; std::cout << "serialization: " << j << std::endl; // deserialization: json -> person json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json; auto p2 = j2.template get<ns::person>(); // incomplete deserialization: json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json; auto p3 = j3.template get<ns::person>(); std::cout << "roundtrip: " << json(p3) << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/json_pointer__operator__equal.cpp
.cpp
645
20
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // different JSON pointers json::json_pointer ptr0; json::json_pointer ptr1(""); json::json_pointer ptr2("/foo"); // compare JSON pointers std::cout << std::boolalpha << "\"" << ptr0 << "\" == \"" << ptr0 << "\": " << (ptr0 == ptr0) << '\n' << "\"" << ptr0 << "\" == \"" << ptr1 << "\": " << (ptr0 == ptr1) << '\n' << "\"" << ptr1 << "\" == \"" << ptr2 << "\": " << (ptr1 == ptr2) << '\n' << "\"" << ptr2 << "\" == \"" << ptr2 << "\": " << (ptr2 == ptr2) << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_binary.cpp
.cpp
961
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_unsigned_integer = 12345678987654321u; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_binary() std::cout << std::boolalpha; std::cout << j_null.is_binary() << '\n'; std::cout << j_boolean.is_binary() << '\n'; std::cout << j_number_integer.is_binary() << '\n'; std::cout << j_number_unsigned_integer.is_binary() << '\n'; std::cout << j_number_float.is_binary() << '\n'; std::cout << j_object.is_binary() << '\n'; std::cout << j_array.is_binary() << '\n'; std::cout << j_string.is_binary() << '\n'; std::cout << j_binary.is_binary() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_array__keytype_const.c++17.cpp
.cpp
353
19
#include <iostream> #include <string_view> #include <nlohmann/json.hpp> using namespace std::string_view_literals; using json = nlohmann::json; int main() { // create a JSON object const json object = { {"one", 1}, {"two", 2}, {"three", 2.9} }; // output element with key "two" std::cout << object["two"sv] << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/array_t.cpp
.cpp
217
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<std::vector<json>, json::array_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/get_ptr.cpp
.cpp
641
22
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON number json value = 17; // explicitly getting pointers auto p1 = value.get_ptr<const json::number_integer_t*>(); auto p2 = value.get_ptr<json::number_integer_t*>(); auto p3 = value.get_ptr<json::number_integer_t* const>(); auto p4 = value.get_ptr<const json::number_integer_t* const>(); auto p5 = value.get_ptr<json::number_float_t*>(); // print the pointees std::cout << *p1 << ' ' << *p2 << ' ' << *p3 << ' ' << *p4 << '\n'; std::cout << std::boolalpha << (p5 == nullptr) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/nlohmann_define_type_non_intrusive_macro.cpp
.cpp
975
42
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; namespace ns { struct person { std::string name; std::string address; int age; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age) } // namespace ns int main() { ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60}; // serialization: person -> json json j = p; std::cout << "serialization: " << j << std::endl; // deserialization: json -> person json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json; auto p2 = j2.template get<ns::person>(); // incomplete deserialization: json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json; try { auto p3 = j3.template get<ns::person>(); } catch (json::exception& e) { std::cout << "deserialization failed: " << e.what() << std::endl; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/find__object_t_key_type.cpp
.cpp
547
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON object json j_object = {{"one", 1}, {"two", 2}}; // call find auto it_two = j_object.find("two"); auto it_three = j_object.find("three"); // print values std::cout << std::boolalpha; std::cout << "\"two\" was found: " << (it_two != j_object.end()) << '\n'; std::cout << "value at key \"two\": " << *it_two << '\n'; std::cout << "\"three\" was found: " << (it_three != j_object.end()) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/basic_json__value_t.cpp
.cpp
764
26
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create the different JSON values with default values json j_null(json::value_t::null); json j_boolean(json::value_t::boolean); json j_number_integer(json::value_t::number_integer); json j_number_float(json::value_t::number_float); json j_object(json::value_t::object); json j_array(json::value_t::array); json j_string(json::value_t::string); // serialize the JSON values std::cout << j_null << '\n'; std::cout << j_boolean << '\n'; std::cout << j_number_integer << '\n'; std::cout << j_number_float << '\n'; std::cout << j_object << '\n'; std::cout << j_array << '\n'; std::cout << j_string << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__greaterequal.cpp
.cpp
825
25
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create several JSON values json array_1 = {1, 2, 3}; json array_2 = {1, 2, 4}; json object_1 = {{"A", "a"}, {"B", "b"}}; json object_2 = {{"B", "b"}, {"A", "a"}}; json number_1 = 17; json number_2 = 17.0000000000001L; json string_1 = "foo"; json string_2 = "bar"; // output values and comparisons std::cout << std::boolalpha; std::cout << array_1 << " >= " << array_2 << " " << (array_1 >= array_2) << '\n'; std::cout << object_1 << " >= " << object_2 << " " << (object_1 >= object_2) << '\n'; std::cout << number_1 << " >= " << number_2 << " " << (number_1 >= number_2) << '\n'; std::cout << string_1 << " >= " << string_2 << " " << (string_1 >= string_2) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/sax_parse__binary.cpp
.cpp
2,933
115
#include <iostream> #include <iomanip> #include <sstream> #include <nlohmann/json.hpp> using json = nlohmann::json; // a simple event consumer that collects string representations of the passed // values; note inheriting from json::json_sax_t is not required, but can // help not to forget a required function class sax_event_consumer : public json::json_sax_t { public: std::vector<std::string> events; bool null() override { events.push_back("null()"); return true; } bool boolean(bool val) override { events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")"); return true; } bool number_integer(number_integer_t val) override { events.push_back("number_integer(val=" + std::to_string(val) + ")"); return true; } bool number_unsigned(number_unsigned_t val) override { events.push_back("number_unsigned(val=" + std::to_string(val) + ")"); return true; } bool number_float(number_float_t val, const string_t& s) override { events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")"); return true; } bool string(string_t& val) override { events.push_back("string(val=" + val + ")"); return true; } bool start_object(std::size_t elements) override { events.push_back("start_object(elements=" + std::to_string(elements) + ")"); return true; } bool end_object() override { events.push_back("end_object()"); return true; } bool start_array(std::size_t elements) override { events.push_back("start_array(elements=" + std::to_string(elements) + ")"); return true; } bool end_array() override { events.push_back("end_array()"); return true; } bool key(string_t& val) override { events.push_back("key(val=" + val + ")"); return true; } bool binary(json::binary_t& val) override { events.push_back("binary(val=[...])"); return true; } bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override { events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")"); return false; } }; int main() { // CBOR byte string std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}}; // create a SAX event consumer object sax_event_consumer sec; // parse CBOR bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor); // output the recorded events for (auto& event : sec.events) { std::cout << event << "\n"; } // output the result of sax_parse std::cout << "\nresult: " << std::boolalpha << result << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_literal_json.cpp
.cpp
254
14
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { json j = R"( {"hello": "world", "answer": 42} )"_json; std::cout << std::setw(2) << j << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/from_ubjson.cpp
.cpp
574
21
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create byte vector std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D }; // deserialize it with UBJSON json j = json::from_ubjson(v); // print the deserialized JSON value std::cout << std::setw(2) << j << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/parse__allow_exceptions.cpp
.cpp
662
37
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // an invalid JSON text std::string text = R"( { "key": "value without closing quotes } )"; // parse with exceptions try { json j = json::parse(text); } catch (json::parse_error& e) { std::cout << e.what() << std::endl; } // parse without exceptions json j = json::parse(text, nullptr, false); if (j.is_discarded()) { std::cout << "the input is invalid JSON" << std::endl; } else { std::cout << "the input is valid JSON: " << j << std::endl; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/json_pointer__empty.cpp
.cpp
579
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // different JSON Pointers json::json_pointer ptr0; json::json_pointer ptr1(""); json::json_pointer ptr2("/foo"); json::json_pointer ptr3("/foo/0"); // call empty() std::cout << std::boolalpha << "\"" << ptr0 << "\": " << ptr0.empty() << '\n' << "\"" << ptr1 << "\": " << ptr1.empty() << '\n' << "\"" << ptr2 << "\": " << ptr2.empty() << '\n' << "\"" << ptr3 << "\": " << ptr3.empty() << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/parse__pointers.cpp
.cpp
360
16
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // a JSON text given as string that is not null-terminated const char* ptr = "[1,2,3]another value"; // parse and serialize JSON json j_complete = json::parse(ptr, ptr + 7); std::cout << std::setw(4) << j_complete << "\n\n"; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_ltlt__basic_json.cpp
.cpp
549
22
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; // serialize without indentation std::cout << j_object << "\n\n"; std::cout << j_array << "\n\n"; // serialize with indentation std::cout << std::setw(4) << j_object << "\n\n"; std::cout << std::setw(2) << j_array << "\n\n"; std::cout << std::setw(1) << std::setfill('\t') << j_object << "\n\n"; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/byte_container_with_subtype__has_subtype.cpp
.cpp
602
20
#include <iostream> #include <nlohmann/json.hpp> // define a byte container based on std::vector using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>; int main() { std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}}; // create container auto c1 = byte_container_with_subtype(bytes); // create container with subtype auto c2 = byte_container_with_subtype(bytes, 42); std::cout << std::boolalpha << "c1.has_subtype() = " << c1.has_subtype() << "\nc2.has_subtype() = " << c2.has_subtype() << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/string_t.cpp
.cpp
212
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<std::string, json::string_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/byte_container_with_subtype__subtype.cpp
.cpp
712
23
#include <iostream> #include <nlohmann/json.hpp> // define a byte container based on std::vector using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>; int main() { std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}}; // create container auto c1 = byte_container_with_subtype(bytes); // create container with subtype auto c2 = byte_container_with_subtype(bytes, 42); std::cout << "c1.subtype() = " << c1.subtype() << "\nc2.subtype() = " << c2.subtype() << std::endl; // in case no subtype is set, return special value assert(c1.subtype() == static_cast<byte_container_with_subtype::subtype_type>(-1)); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/at__keytype.c++17.cpp
.cpp
1,127
51
#include <iostream> #include <string_view> #include <nlohmann/json.hpp> using namespace std::string_view_literals; using json = nlohmann::json; int main() { // create JSON object json object = { {"the good", "il buono"}, {"the bad", "il cattivo"}, {"the ugly", "il brutto"} }; // output element with key "the ugly" using string_view std::cout << object.at("the ugly"sv) << '\n'; // change element with key "the bad" using string_view object.at("the bad"sv) = "il cattivo"; // output changed array std::cout << object << '\n'; // exception type_error.304 try { // use at() with string_view on a non-object type json str = "I am a string"; str.at("the good"sv) = "Another string"; } catch (json::type_error& e) { std::cout << e.what() << '\n'; } // exception out_of_range.401 try { // try to write at a nonexisting key using string_view object.at("the fast"sv) = "il rapido"; } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/get_binary.cpp
.cpp
408
17
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a binary vector std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE}; // create a binary JSON value with subtype 42 json j = json::binary(vec, 42); // output type and subtype std::cout << "type: " << j.type_name() << ", subtype: " << j.get_binary().subtype() << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_number_integer.cpp
.cpp
1,041
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_unsigned_integer = 12345678987654321u; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_number_integer() std::cout << std::boolalpha; std::cout << j_null.is_number_integer() << '\n'; std::cout << j_boolean.is_number_integer() << '\n'; std::cout << j_number_integer.is_number_integer() << '\n'; std::cout << j_number_unsigned_integer.is_number_integer() << '\n'; std::cout << j_number_float.is_number_integer() << '\n'; std::cout << j_object.is_number_integer() << '\n'; std::cout << j_array.is_number_integer() << '\n'; std::cout << j_string.is_number_integer() << '\n'; std::cout << j_binary.is_number_integer() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/value__object_t_key_type.cpp
.cpp
815
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON object with different entry types json j = { {"integer", 1}, {"floating", 42.23}, {"string", "hello world"}, {"boolean", true}, {"object", {{"key1", 1}, {"key2", 2}}}, {"array", {1, 2, 3}} }; // access existing values int v_integer = j.value("integer", 0); double v_floating = j.value("floating", 47.11); // access nonexisting values and rely on default value std::string v_string = j.value("nonexisting", "oops"); bool v_boolean = j.value("nonexisting", false); // output values std::cout << std::boolalpha << v_integer << " " << v_floating << " " << v_string << " " << v_boolean << "\n"; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/type_name.cpp
.cpp
1,021
28
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = -17; json j_number_unsigned = 42u; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; // call type_name() std::cout << j_null << " is a " << j_null.type_name() << '\n'; std::cout << j_boolean << " is a " << j_boolean.type_name() << '\n'; std::cout << j_number_integer << " is a " << j_number_integer.type_name() << '\n'; std::cout << j_number_unsigned << " is a " << j_number_unsigned.type_name() << '\n'; std::cout << j_number_float << " is a " << j_number_float.type_name() << '\n'; std::cout << j_object << " is an " << j_object.type_name() << '\n'; std::cout << j_array << " is an " << j_array.type_name() << '\n'; std::cout << j_string << " is a " << j_string.type_name() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/insert__range_object.cpp
.cpp
457
22
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create two JSON objects json j1 = {{"one", "eins"}, {"two", "zwei"}}; json j2 = {{"eleven", "elf"}, {"seventeen", "siebzehn"}}; // output objects std::cout << j1 << '\n'; std::cout << j2 << '\n'; // insert range from j2 to j1 j1.insert(j2.begin(), j2.end()); // output result of insert call std::cout << j1 << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/boolean_t.cpp
.cpp
206
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<bool, json::boolean_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/nlohmann_json_namespace.cpp
.cpp
353
15
#include <iostream> #include <nlohmann/json.hpp> // possible use case: use NLOHMANN_JSON_NAMESPACE instead of nlohmann using json = NLOHMANN_JSON_NAMESPACE::json; // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main() { std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/at__object_t_key_type_const.cpp
.cpp
862
43
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON object const json object = { {"the good", "il buono"}, {"the bad", "il cattivo"}, {"the ugly", "il brutto"} }; // output element with key "the ugly" std::cout << object.at("the ugly") << '\n'; // exception type_error.304 try { // use at() on a non-object type const json str = "I am a string"; std::cout << str.at("the good") << '\n'; } catch (json::type_error& e) { std::cout << e.what() << '\n'; } // exception out_of_range.401 try { // try to read from a nonexisting key std::cout << object.at("the fast") << '\n'; } catch (json::out_of_range) { std::cout << "out of range" << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/to_string.cpp
.cpp
472
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using std::to_string; int main() { // create values json j = {{"one", 1}, {"two", 2}}; int i = 42; // use ADL to select best to_string function auto j_str = to_string(j); // calling nlohmann::to_string auto i_str = to_string(i); // calling std::to_string // serialize without indentation std::cout << j_str << "\n\n" << i_str << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/patch.cpp
.cpp
738
34
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // the original document json doc = R"( { "baz": "qux", "foo": "bar" } )"_json; // the patch json patch = R"( [ { "op": "replace", "path": "/baz", "value": "boo" }, { "op": "add", "path": "/hello", "value": ["world"] }, { "op": "remove", "path": "/foo"} ] )"_json; // apply the patch json patched_doc = doc.patch(patch); // output original and patched document std::cout << std::setw(4) << doc << "\n\n" << std::setw(4) << patched_doc << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/insert__range.cpp
.cpp
473
21
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON array json v = {1, 2, 3, 4}; // create a JSON array to copy values from json v2 = {"one", "two", "three", "four"}; // insert range from v2 before the end of array v auto new_pos = v.insert(v.end(), v2.begin(), v2.end()); // output new array and result of insert call std::cout << *new_pos << '\n'; std::cout << v << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/nlohmann_json_version.cpp
.cpp
306
13
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << "JSON for Modern C++ version " << NLOHMANN_JSON_VERSION_MAJOR << "." << NLOHMANN_JSON_VERSION_MINOR << "." << NLOHMANN_JSON_VERSION_PATCH << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/push_back__initializer_list.cpp
.cpp
611
28
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json object = {{"one", 1}, {"two", 2}}; json null; // print values std::cout << object << '\n'; std::cout << null << '\n'; // add values: object.push_back({"three", 3}); // object is extended object += {"four", 4}; // object is extended null.push_back({"five", 5}); // null is converted to array // print values std::cout << object << '\n'; std::cout << null << '\n'; // would throw: //object.push_back({1, 2, 3}); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/get_to.cpp
.cpp
1,363
61
#include <iostream> #include <unordered_map> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON value with different types json json_types = { {"boolean", true}, { "number", { {"integer", 42}, {"floating-point", 17.23} } }, {"string", "Hello, world!"}, {"array", {1, 2, 3, 4, 5}}, {"null", nullptr} }; bool v1; int v2; short v3; float v4; int v5; std::string v6; std::vector<short> v7; std::unordered_map<std::string, json> v8; // use explicit conversions json_types["boolean"].get_to(v1); json_types["number"]["integer"].get_to(v2); json_types["number"]["integer"].get_to(v3); json_types["number"]["floating-point"].get_to(v4); json_types["number"]["floating-point"].get_to(v5); json_types["string"].get_to(v6); json_types["array"].get_to(v7); json_types.get_to(v8); // print the conversion results std::cout << v1 << '\n'; std::cout << v2 << ' ' << v3 << '\n'; std::cout << v4 << ' ' << v5 << '\n'; std::cout << v6 << '\n'; for (auto i : v7) { std::cout << i << ' '; } std::cout << "\n\n"; for (auto i : v8) { std::cout << i.first << ": " << i.second << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/count__object_t_key_type.cpp
.cpp
465
19
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON object json j_object = {{"one", 1}, {"two", 2}}; // call count() auto count_two = j_object.count("two"); auto count_three = j_object.count("three"); // print values std::cout << "number of elements with key \"two\": " << count_two << '\n'; std::cout << "number of elements with key \"three\": " << count_three << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__notequal.cpp
.cpp
827
25
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create several JSON values json array_1 = {1, 2, 3}; json array_2 = {1, 2, 4}; json object_1 = {{"A", "a"}, {"B", "b"}}; json object_2 = {{"B", "b"}, {"A", "a"}}; json number_1 = 17; json number_2 = 17.000000000000001L; json string_1 = "foo"; json string_2 = "bar"; // output values and comparisons std::cout << std::boolalpha; std::cout << array_1 << " != " << array_2 << " " << (array_1 != array_2) << '\n'; std::cout << object_1 << " != " << object_2 << " " << (object_1 != object_2) << '\n'; std::cout << number_1 << " != " << number_2 << " " << (number_1 != number_2) << '\n'; std::cout << string_1 << " != " << string_2 << " " << (string_1 != string_2) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/end.cpp
.cpp
406
20
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create an array value json array = {1, 2, 3, 4, 5}; // get an iterator to one past the last element json::iterator it = array.end(); // decrement the iterator to point to the last element --it; // serialize the element that the iterator points to std::cout << *it << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/front.cpp
.cpp
951
30
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_object_empty(json::value_t::object); json j_array = {1, 2, 4, 8, 16}; json j_array_empty(json::value_t::array); json j_string = "Hello, world"; // call front() //std::cout << j_null.front() << '\n'; // would throw std::cout << j_boolean.front() << '\n'; std::cout << j_number_integer.front() << '\n'; std::cout << j_number_float.front() << '\n'; std::cout << j_object.front() << '\n'; //std::cout << j_object_empty.front() << '\n'; // undefined behavior std::cout << j_array.front() << '\n'; //std::cout << j_array_empty.front() << '\n'; // undefined behavior std::cout << j_string.front() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/count__keytype.c++17.cpp
.cpp
535
21
#include <iostream> #include <string_view> #include <nlohmann/json.hpp> using namespace std::string_view_literals; using json = nlohmann::json; int main() { // create a JSON object json j_object = {{"one", 1}, {"two", 2}}; // call count() auto count_two = j_object.count("two"sv); auto count_three = j_object.count("three"sv); // print values std::cout << "number of elements with key \"two\": " << count_two << '\n'; std::cout << "number of elements with key \"three\": " << count_three << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/number_unsigned_t.cpp
.cpp
223
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<std::uint64_t, json::number_unsigned_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/fuzzing.md
.md
3,187
82
# Fuzz testing Each parser of the library (JSON, BJData, BSON, CBOR, MessagePack, and UBJSON) can be fuzz tested. Currently, [libFuzzer](https://llvm.org/docs/LibFuzzer.html) and [afl++](https://github.com/AFLplusplus/AFLplusplus) are supported. ## Corpus creation For most effective fuzzing, a [corpus](https://llvm.org/docs/LibFuzzer.html#corpus) should be provided. A corpus is a directory with some simple input files that cover several features of the parser and is hence a good starting point for mutations. ```shell TEST_DATA_VERSION=3.1.0 wget https://github.com/nlohmann/json_test_data/archive/refs/tags/v$TEST_DATA_VERSION.zip unzip v$TEST_DATA_VERSION.zip rm v$TEST_DATA_VERSION.zip for FORMAT in json bjdata bson cbor msgpack ubjson do rm -fr corpus_$FORMAT mkdir corpus_$FORMAT find json_test_data-$TEST_DATA_VERSION -size -5k -name "*.$FORMAT" -exec cp "{}" "corpus_$FORMAT" \; done rm -fr json_test_data-$TEST_DATA_VERSION ``` The generated corpus can be used with both libFuzzer and afl++. The remainder of this documentation assumes the corpus directories have been created in the `tests` directory. ## libFuzzer To use libFuzzer, you need to pass `-fsanitize=fuzzer` as `FUZZER_ENGINE`. In the `tests` directory, call ```shell make fuzzers FUZZER_ENGINE="-fsanitize=fuzzer" ``` This creates a fuzz tester binary for each parser that supports these [command line options](https://llvm.org/docs/LibFuzzer.html#options). In case your default compiler is not a Clang compiler that includes libFuzzer (Clang 6.0 or later), you need to set the `CXX` variable accordingly. Note the compiler provided by Xcode (AppleClang) does not contain libFuzzer. Please install Clang via Homebrew calling `brew install llvm` and add `CXX=$(brew --prefix llvm)/bin/clang` to the `make` call: ```shell make fuzzers FUZZER_ENGINE="-fsanitize=fuzzer" CXX=$(brew --prefix llvm)/bin/clang ``` Then pass the corpus directory as command-line argument (assuming it is located in `tests`): ```shell ./parse_cbor_fuzzer corpus_cbor ``` The fuzzer should be able to run indefinitely without crashing. In case of a crash, the tested input is dumped into a file starting with `crash-`. ## afl++ To use afl++, you need to pass `-fsanitize=fuzzer` as `FUZZER_ENGINE`. It will be replaced by a `libAFLDriver.a` to re-use the same code written for libFuzzer with afl++. Furthermore, set `afl-clang-fast++` as compiler. ```shell CXX=afl-clang-fast++ make fuzzers FUZZER_ENGINE="-fsanitize=fuzzer" ``` Then the fuzzer is called like this in the `tests` directory: ```shell afl-fuzz -i corpus_cbor -o out -- ./parse_cbor_fuzzer ``` The fuzzer should be able to run indefinitely without crashing. In case of a crash, the tested input is written to the directory `out`. ## OSS-Fuzz The library is further fuzz-tested 24/7 by Google's [OSS-Fuzz project](https://github.com/google/oss-fuzz). It uses the same `fuzzers` target as above and also relies on the `FUZZER_ENGINE` variable. See the used [build script](https://github.com/google/oss-fuzz/blob/master/projects/json/build.sh) for more information. In case the build at OSS-Fuzz fails, an issue will be created automatically.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_fetch_content2/project/main.cpp
.cpp
416
17
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include <nlohmann/json.hpp> int main(int argc, char** argv) { nlohmann::json j; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/reports/2016-09-09-nativejson_benchmark/conformance_Nlohmann (C++11).md
.md
43,054
671
<!DOCTYPE html> <html lang="en" class=""> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#"> <meta charset='utf-8'> <link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/frameworks-3a71f36dec04358c4f2f42280fb2cf5c38856f935a3f609eab0a1ae31b1d635a.css" media="all" rel="stylesheet" /> <link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/github-5c885e880e980dc7f119393287b84906d930ccaff83f6bff8ae2c086b87ca4d8.css" media="all" rel="stylesheet" /> <link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/site-4ef7bbe907458c89cb1f7f5c5e6c4cd87e03acf66b1817325e644920d2a83330.css" media="all" rel="stylesheet" /> <link as="script" href="https://assets-cdn.github.com/assets/frameworks-88471af1fec40ff9418efbe2ddd15b6896af8d772f8179004c254dffc25ea490.js" rel="preload" /> <link as="script" href="https://assets-cdn.github.com/assets/github-e18e11a943ff2eb9394c72d4ec8b76592c454915b5839ae177d422777a046e29.js" rel="preload" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Language" content="en"> <meta name="viewport" content="width=device-width"> <title>nativejson-benchmark/conformance_Nlohmann (C++11).md at master · miloyip/nativejson-benchmark · GitHub</title> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png"> <meta property="fb:app_id" content="1401488693436528"> <meta content="https://avatars2.githubusercontent.com/u/1195774?v=3&amp;s=400" name="twitter:image:src" /><meta content="@github" name="twitter:site" /><meta content="summary" name="twitter:card" /><meta content="miloyip/nativejson-benchmark" name="twitter:title" /><meta content="nativejson-benchmark - C/C++ JSON parser/generator benchmark" name="twitter:description" /> <meta content="https://avatars2.githubusercontent.com/u/1195774?v=3&amp;s=400" property="og:image" /><meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="miloyip/nativejson-benchmark" property="og:title" /><meta content="https://github.com/miloyip/nativejson-benchmark" property="og:url" /><meta content="nativejson-benchmark - C/C++ JSON parser/generator benchmark" property="og:description" /> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <link rel="assets" href="https://assets-cdn.github.com/"> <meta name="pjax-timeout" content="1000"> <meta name="request-id" content="D4563DA7:75ED:525C921:57D6FEBB" data-pjax-transient> <meta name="msapplication-TileImage" content="/windows-tile.png"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="selected-link" value="repo_source" data-pjax-transient> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-analytics" content="UA-3769691-2"> <meta content="collector.githubapp.com" name="octolytics-host" /><meta content="github" name="octolytics-app-id" /><meta content="D4563DA7:75ED:525C921:57D6FEBB" name="octolytics-dimension-request_id" /> <meta content="/&lt;user-name&gt;/&lt;repo-name&gt;/blob/show" data-pjax-transient="true" name="analytics-location" /> <meta class="js-ga-set" name="dimension1" content="Logged Out"> <meta name="hostname" content="github.com"> <meta name="user-login" content=""> <meta name="expected-hostname" content="github.com"> <meta name="js-proxy-site-detection-payload" content="N2RkMmY1ZjE1MTA4MzRhYTA5NDNkMjliNDU3OTA3ZTdlMGNmNDZjN2QyODBiZjM3MmYzMjFjNzY1ZjIwNjY4NHx7InJlbW90ZV9hZGRyZXNzIjoiMjEyLjg2LjYxLjE2NyIsInJlcXVlc3RfaWQiOiJENDU2M0RBNzo3NUVEOjUyNUM5MjE6NTdENkZFQkIiLCJ0aW1lc3RhbXAiOjE0NzM3MDc3MDh9"> <link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#4078c0"> <link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico"> <meta name="html-safe-nonce" content="deea0f406df2fb95709865c5ee80a255d8c47fa9"> <meta content="736eea9d74cf34fe850d2180e8a5f0a1cc7bc0be" name="form-nonce" /> <meta http-equiv="x-pjax-version" content="f302977937abe3fe1c9a4d4bed913565"> <meta name="description" content="nativejson-benchmark - C/C++ JSON parser/generator benchmark"> <meta name="go-import" content="github.com/miloyip/nativejson-benchmark git https://github.com/miloyip/nativejson-benchmark.git"> <meta content="1195774" name="octolytics-dimension-user_id" /><meta content="miloyip" name="octolytics-dimension-user_login" /><meta content="22976798" name="octolytics-dimension-repository_id" /><meta content="miloyip/nativejson-benchmark" name="octolytics-dimension-repository_nwo" /><meta content="true" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="22976798" name="octolytics-dimension-repository_network_root_id" /><meta content="miloyip/nativejson-benchmark" name="octolytics-dimension-repository_network_root_nwo" /> <link href="https://github.com/miloyip/nativejson-benchmark/commits/master.atom" rel="alternate" title="Recent Commits to nativejson-benchmark:master" type="application/atom+xml"> <link rel="canonical" href="https://github.com/miloyip/nativejson-benchmark/blob/master/sample/conformance_Nlohmann%20(C%2B%2B11).md" data-pjax-transient> </head> <body class="logged-out env-production vis-public page-blob"> <div id="js-pjax-loader-bar" class="pjax-loader-bar"><div class="progress"></div></div> <a href="#start-of-content" tabindex="1" class="accessibility-aid js-skip-to-content">Skip to content</a> <header class="site-header js-details-container" role="banner"> <div class="container-responsive"> <a class="header-logo-invertocat" href="https://github.com/" aria-label="Homepage" data-ga-click="(Logged out) Header, go to homepage, icon:logo-wordmark"> <svg aria-hidden="true" class="octicon octicon-mark-github" height="32" version="1.1" viewBox="0 0 16 16" width="32"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path></svg> </a> <button class="btn-link float-right site-header-toggle js-details-target" type="button" aria-label="Toggle navigation"> <svg aria-hidden="true" class="octicon octicon-three-bars" height="24" version="1.1" viewBox="0 0 12 16" width="18"><path d="M11.41 9H.59C0 9 0 8.59 0 8c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zm0-4H.59C0 5 0 4.59 0 4c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zM.59 11H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1H.59C0 13 0 12.59 0 12c0-.59 0-1 .59-1z"></path></svg> </button> <div class="site-header-menu"> <nav class="site-header-nav site-header-nav-main"> <a href="/personal" class="js-selected-navigation-item nav-item nav-item-personal" data-ga-click="Header, click, Nav menu - item:personal" data-selected-links="/personal /personal"> Personal </a> <a href="/open-source" class="js-selected-navigation-item nav-item nav-item-opensource" data-ga-click="Header, click, Nav menu - item:opensource" data-selected-links="/open-source /open-source"> Open source </a> <a href="/business" class="js-selected-navigation-item nav-item nav-item-business" data-ga-click="Header, click, Nav menu - item:business" data-selected-links="/business /business/partners /business/features /business/customers /business"> Business </a> <a href="/explore" class="js-selected-navigation-item nav-item nav-item-explore" data-ga-click="Header, click, Nav menu - item:explore" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship /explore"> Explore </a> </nav> <div class="site-header-actions"> <a class="btn btn-primary site-header-actions-btn" href="/join?source=header-repo" data-ga-click="(Logged out) Header, clicked Sign up, text:sign-up">Sign up</a> <a class="btn site-header-actions-btn mr-2" href="/login?return_to=%2Fmiloyip%2Fnativejson-benchmark%2Fblob%2Fmaster%2Fsample%2Fconformance_Nlohmann%2520%28C%252B%252B11%29.md" data-ga-click="(Logged out) Header, clicked Sign in, text:sign-in">Sign in</a> </div> <nav class="site-header-nav site-header-nav-secondary"> <a class="nav-item" href="/pricing">Pricing</a> <a class="nav-item" href="/blog">Blog</a> <a class="nav-item" href="https://help.github.com">Support</a> <a class="nav-item header-search-link" href="https://github.com/search">Search GitHub</a> <div class="header-search scoped-search site-scoped-search js-site-search" role="search"> <!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="/miloyip/nativejson-benchmark/search" class="js-site-search-form" data-scoped-search-url="/miloyip/nativejson-benchmark/search" data-unscoped-search-url="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div> <label class="form-control header-search-wrapper js-chromeless-input-container"> <div class="header-search-scope">This repository</div> <input type="text" class="form-control header-search-input js-site-search-focus js-site-search-field is-clearable" data-hotkey="s" name="q" placeholder="Search" aria-label="Search this repository" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off"> </label> </form></div> </nav> </div> </div> </header> <div id="start-of-content" class="accessibility-aid"></div> <div id="js-flash-container"> </div> <div role="main"> <div itemscope itemtype="http://schema.org/SoftwareSourceCode"> <div id="js-repo-pjax-container" data-pjax-container> <div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav"> <div class="container repohead-details-container"> <ul class="pagehead-actions"> <li> <a href="/login?return_to=%2Fmiloyip%2Fnativejson-benchmark" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to watch a repository" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"></path></svg> Watch </a> <a class="social-count" href="/miloyip/nativejson-benchmark/watchers" aria-label="40 users are watching this repository"> 40 </a> </li> <li> <a href="/login?return_to=%2Fmiloyip%2Fnativejson-benchmark" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to star a repository" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"></path></svg> Star </a> <a class="social-count js-social-count" href="/miloyip/nativejson-benchmark/stargazers" aria-label="352 users starred this repository"> 352 </a> </li> <li> <a href="/login?return_to=%2Fmiloyip%2Fnativejson-benchmark" class="btn btn-sm btn-with-count tooltipped tooltipped-n" aria-label="You must be signed in to fork a repository" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-repo-forked" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> Fork </a> <a href="/miloyip/nativejson-benchmark/network" class="social-count" aria-label="59 users are forked this repository"> 59 </a> </li> </ul> <h1 class="public "> <svg aria-hidden="true" class="octicon octicon-repo" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"></path></svg> <span class="author" itemprop="author"><a href="/miloyip" class="url fn" rel="author">miloyip</a></span><!-- --><span class="path-divider">/</span><!-- --><strong itemprop="name"><a href="/miloyip/nativejson-benchmark" data-pjax="#js-repo-pjax-container">nativejson-benchmark</a></strong> </h1> </div> <div class="container"> <nav class="reponav js-repo-nav js-sidenav-container-pjax" itemscope itemtype="http://schema.org/BreadcrumbList" role="navigation" data-pjax="#js-repo-pjax-container"> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a href="/miloyip/nativejson-benchmark" aria-selected="true" class="js-selected-navigation-item selected reponav-item" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches /miloyip/nativejson-benchmark" itemprop="url"> <svg aria-hidden="true" class="octicon octicon-code" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"></path></svg> <span itemprop="name">Code</span> <meta itemprop="position" content="1"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a href="/miloyip/nativejson-benchmark/issues" class="js-selected-navigation-item reponav-item" data-hotkey="g i" data-selected-links="repo_issues repo_labels repo_milestones /miloyip/nativejson-benchmark/issues" itemprop="url"> <svg aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"></path></svg> <span itemprop="name">Issues</span> <span class="counter">8</span> <meta itemprop="position" content="2"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a href="/miloyip/nativejson-benchmark/pulls" class="js-selected-navigation-item reponav-item" data-hotkey="g p" data-selected-links="repo_pulls /miloyip/nativejson-benchmark/pulls" itemprop="url"> <svg aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg> <span itemprop="name">Pull requests</span> <span class="counter">1</span> <meta itemprop="position" content="3"> </a> </span> <a href="/miloyip/nativejson-benchmark/pulse" class="js-selected-navigation-item reponav-item" data-selected-links="pulse /miloyip/nativejson-benchmark/pulse"> <svg aria-hidden="true" class="octicon octicon-pulse" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M11.5 8L8.8 5.4 6.6 8.5 5.5 1.6 2.38 8H0v2h3.6l.9-1.8.9 5.4L9 8.5l1.6 1.5H14V8z"></path></svg> Pulse </a> <a href="/miloyip/nativejson-benchmark/graphs" class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors /miloyip/nativejson-benchmark/graphs"> <svg aria-hidden="true" class="octicon octicon-graph" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"></path></svg> Graphs </a> </nav> </div> </div> <div class="container new-discussion-timeline experiment-repo-nav"> <div class="repository-content"> <a href="/miloyip/nativejson-benchmark/blob/95f27ebcf9a96c7ca4cee26467ed5420140090fb/sample/conformance_Nlohmann%20(C%2B%2B11).md" class="d-none js-permalink-shortcut" data-hotkey="y">Permalink</a> <!-- blob contrib key: blob_contributors:v21:0bf9e3593dedd91db6c9dc69e13b7f95 --> <div class="file-navigation js-zeroclipboard-container"> <div class="select-menu branch-select-menu js-menu-container js-select-menu float-left"> <button class="btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w" type="button" aria-label="Switch branches or tags" tabindex="0" aria-haspopup="true"> <i>Branch:</i> <span class="js-select-button css-truncate-target">master</span> </button> <div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax aria-hidden="true"> <div class="select-menu-modal"> <div class="select-menu-header"> <svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"></path></svg> <span class="select-menu-title">Switch branches/tags</span> </div> <div class="select-menu-filters"> <div class="select-menu-text-filter"> <input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Filter branches/tags"> </div> <div class="select-menu-tabs"> <ul> <li class="select-menu-tab"> <a href="#" data-tab-filter="branches" data-filter-placeholder="Filter branches/tags" class="js-select-menu-tab" role="tab">Branches</a> </li> <li class="select-menu-tab"> <a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a> </li> </ul> </div> </div> <div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu"> <div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring"> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/Stixjson/sample/conformance_Nlohmann%20(C++11).md" data-name="Stixjson" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> Stixjson </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/ccan/sample/conformance_Nlohmann%20(C++11).md" data-name="ccan" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> ccan </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/jbson/sample/conformance_Nlohmann%20(C++11).md" data-name="jbson" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> jbson </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/jute/sample/conformance_Nlohmann%20(C++11).md" data-name="jute" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> jute </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/lastjson/sample/conformance_Nlohmann%20(C++11).md" data-name="lastjson" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> lastjson </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/libjson/sample/conformance_Nlohmann%20(C++11).md" data-name="libjson" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> libjson </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open selected" href="/miloyip/nativejson-benchmark/blob/master/sample/conformance_Nlohmann%20(C++11).md" data-name="master" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> master </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/qt/sample/conformance_Nlohmann%20(C++11).md" data-name="qt" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> qt </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/tunnuz/sample/conformance_Nlohmann%20(C++11).md" data-name="tunnuz" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> tunnuz </span> </a> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/blob/ujson/sample/conformance_Nlohmann%20(C++11).md" data-name="ujson" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target js-select-menu-filter-text"> ujson </span> </a> </div> <div class="select-menu-no-results">Nothing to show</div> </div> <div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags"> <div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring"> <a class="select-menu-item js-navigation-item js-navigation-open " href="/miloyip/nativejson-benchmark/tree/v1.0.0/sample/conformance_Nlohmann%20(C%2B%2B11).md" data-name="v1.0.0" data-skip-pjax="true" rel="nofollow"> <svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"></path></svg> <span class="select-menu-item-text css-truncate-target" title="v1.0.0"> v1.0.0 </span> </a> </div> <div class="select-menu-no-results">Nothing to show</div> </div> </div> </div> </div> <div class="btn-group float-right"> <a href="/miloyip/nativejson-benchmark/find/master" class="js-pjax-capture-input btn btn-sm" data-pjax data-hotkey="t"> Find file </a> <button aria-label="Copy file path to clipboard" class="js-zeroclipboard btn btn-sm zeroclipboard-button tooltipped tooltipped-s" data-copied-hint="Copied!" type="button">Copy path</button> </div> <div class="breadcrumb js-zeroclipboard-target"> <span class="repo-root js-repo-root"><span class="js-path-segment"><a href="/miloyip/nativejson-benchmark"><span>nativejson-benchmark</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a href="/miloyip/nativejson-benchmark/tree/master/sample"><span>sample</span></a></span><span class="separator">/</span><strong class="final-path">conformance_Nlohmann (C++11).md</strong> </div> </div> <div class="commit-tease"> <span class="float-right"> <a class="commit-tease-sha" href="/miloyip/nativejson-benchmark/commit/a4a9f10f41c515d6abb0f019ab9f5d021ed4bb9e" data-pjax> a4a9f10 </a> <relative-time datetime="2016-09-09T03:15:21Z">Sep 9, 2016</relative-time> </span> <div> <img alt="@miloyip" class="avatar" height="20" src="https://avatars3.githubusercontent.com/u/1195774?v=3&amp;s=40" width="20" /> <a href="/miloyip" class="user-mention" rel="author">miloyip</a> <a href="/miloyip/nativejson-benchmark/commit/a4a9f10f41c515d6abb0f019ab9f5d021ed4bb9e" class="message" data-pjax="true" title="Update sample result for 41 libraries Fixed #43">Update sample result for 41 libraries</a> </div> <div class="commit-tease-contributors"> <button type="button" class="btn-link muted-link contributors-toggle" data-facebox="#blob_contributors_box"> <strong>1</strong> contributor </button> </div> <div id="blob_contributors_box" style="display:none"> <h2 class="facebox-header" data-facebox-id="facebox-header">Users who have contributed to this file</h2> <ul class="facebox-user-list" data-facebox-id="facebox-description"> <li class="facebox-user-list-item"> <img alt="@miloyip" height="24" src="https://avatars1.githubusercontent.com/u/1195774?v=3&amp;s=48" width="24" /> <a href="/miloyip">miloyip</a> </li> </ul> </div> </div> <div class="file"> <div class="file-header"> <div class="file-actions"> <div class="btn-group"> <a href="/miloyip/nativejson-benchmark/raw/master/sample/conformance_Nlohmann%20(C%2B%2B11).md" class="btn btn-sm " id="raw-url">Raw</a> <a href="/miloyip/nativejson-benchmark/blame/master/sample/conformance_Nlohmann%20(C%2B%2B11).md" class="btn btn-sm js-update-url-with-hash">Blame</a> <a href="/miloyip/nativejson-benchmark/commits/master/sample/conformance_Nlohmann%20(C%2B%2B11).md" class="btn btn-sm " rel="nofollow">History</a> </div> <button type="button" class="btn-octicon disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg aria-hidden="true" class="octicon octicon-pencil" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 0 1 1.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"></path></svg> </button> <button type="button" class="btn-octicon btn-octicon-danger disabled tooltipped tooltipped-nw" aria-label="You must be signed in to make or propose changes"> <svg aria-hidden="true" class="octicon octicon-trashcan" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"></path></svg> </button> </div> <div class="file-info"> 59 lines (37 sloc) <span class="file-info-divider"></span> 545 Bytes </div> </div> <div id="readme" class="readme blob instapaper_body"> <article class="markdown-body entry-content" itemprop="text"><h1><a id="user-content-conformance-of-nlohmann-c11" class="anchor" href="#conformance-of-nlohmann-c11" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>Conformance of Nlohmann (C++11)</h1> <h2><a id="user-content-1-parse-validation" class="anchor" href="#1-parse-validation" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>1. Parse Validation</h2> <p>Summary: 34 of 34 are correct.</p> <h2><a id="user-content-2-parse-double" class="anchor" href="#2-parse-double" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>2. Parse Double</h2> <p>Summary: 66 of 66 are correct.</p> <h2><a id="user-content-3-parse-string" class="anchor" href="#3-parse-string" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>3. Parse String</h2> <p>Summary: 9 of 9 are correct.</p> <h2><a id="user-content-4-roundtrip" class="anchor" href="#4-roundtrip" aria-hidden="true"><svg aria-hidden="true" class="octicon octicon-link" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>4. Roundtrip</h2> <ul> <li>Fail:</li> </ul> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">5e-324</span>]</pre></div> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">4.94065645841247e-324</span>]</pre></div> <ul> <li>Fail:</li> </ul> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">2.225073858507201e-308</span>]</pre></div> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">2.2250738585072e-308</span>]</pre></div> <ul> <li>Fail:</li> </ul> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">2.2250738585072014e-308</span>]</pre></div> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">2.2250738585072e-308</span>]</pre></div> <ul> <li>Fail:</li> </ul> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">1.7976931348623157e308</span>]</pre></div> <div class="highlight highlight-source-js"><pre>[<span class="pl-c1">1.79769313486232e+308</span>]</pre></div> <p>Summary: 23 of 27 are correct.</p> </article> </div> </div> <button type="button" data-facebox="#jump-to-line" data-facebox-class="linejump" data-hotkey="l" class="d-none">Jump to Line</button> <div id="jump-to-line" style="display:none"> <!-- </textarea> --><!-- '"` --><form accept-charset="UTF-8" action="" class="js-jump-to-line-form" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div> <input class="form-control linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line&hellip;" aria-label="Jump to line" autofocus> <button type="submit" class="btn">Go</button> </form></div> </div> <div class="modal-backdrop js-touch-events"></div> </div> </div> </div> </div> <div class="container site-footer-container"> <div class="site-footer" role="contentinfo"> <ul class="site-footer-links float-right"> <li><a href="https://github.com/contact" data-ga-click="Footer, go to contact, text:contact">Contact GitHub</a></li> <li><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li> <li><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li> <li><a href="https://shop.github.com" data-ga-click="Footer, go to shop, text:shop">Shop</a></li> <li><a href="https://github.com/blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li> <li><a href="https://github.com/about" data-ga-click="Footer, go to about, text:about">About</a></li> </ul> <a href="https://github.com" aria-label="Homepage" class="site-footer-mark" title="GitHub"> <svg aria-hidden="true" class="octicon octicon-mark-github" height="24" version="1.1" viewBox="0 0 16 16" width="24"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path></svg> </a> <ul class="site-footer-links"> <li>&copy; 2016 <span title="0.18611s from github-fe151-cp1-prd.iad.github.net">GitHub</span>, Inc.</li> <li><a href="https://github.com/site/terms" data-ga-click="Footer, go to terms, text:terms">Terms</a></li> <li><a href="https://github.com/site/privacy" data-ga-click="Footer, go to privacy, text:privacy">Privacy</a></li> <li><a href="https://github.com/security" data-ga-click="Footer, go to security, text:security">Security</a></li> <li><a href="https://status.github.com/" data-ga-click="Footer, go to status, text:status">Status</a></li> <li><a href="https://help.github.com" data-ga-click="Footer, go to help, text:help">Help</a></li> </ul> </div> </div> <div id="ajax-error-message" class="ajax-error-message flash flash-error"> <svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"></path></svg> <button type="button" class="flash-close js-flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"></path></svg> </button> You can't perform that action at this time. </div> <script crossorigin="anonymous" src="https://assets-cdn.github.com/assets/compat-40e365359d1c4db1e36a55be458e60f2b7c24d58b5a00ae13398480e7ba768e0.js"></script> <script crossorigin="anonymous" src="https://assets-cdn.github.com/assets/frameworks-88471af1fec40ff9418efbe2ddd15b6896af8d772f8179004c254dffc25ea490.js"></script> <script async="async" crossorigin="anonymous" src="https://assets-cdn.github.com/assets/github-e18e11a943ff2eb9394c72d4ec8b76592c454915b5839ae177d422777a046e29.js"></script> <div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none"> <svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"></path></svg> <span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span> <span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span> </div> <div class="facebox" id="facebox" style="display:none;"> <div class="facebox-popup"> <div class="facebox-content" role="dialog" aria-labelledby="facebox-header" aria-describedby="facebox-description"> </div> <button type="button" class="facebox-close js-facebox-close" aria-label="Close modal"> <svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"></path></svg> </button> </div> </div> </body> </html>
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_import/project/main.cpp
.cpp
416
17
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include <nlohmann/json.hpp> int main(int argc, char** argv) { nlohmann::json j; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-unicode1.cpp
.cpp
26,991
621
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" // for some reason including this after the json header leads to linker errors with VS 2017... #include <locale> #include <nlohmann/json.hpp> using nlohmann::json; #include <fstream> #include <sstream> #include <iomanip> #include "make_test_data_available.hpp" TEST_CASE("Unicode (1/5)" * doctest::skip()) { SECTION("\\uxxxx sequences") { // create an escaped string from a code point const auto 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::stringstream ss; ss << "\\u" << std::setw(4) << std::setfill('0') << std::hex << cp; return ss.str(); }; SECTION("correct sequences") { // 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 += "\""; CAPTURE(json_text) json _; CHECK_NOTHROW(_ = json::parse(json_text)); } } SECTION("incorrect sequences") { SECTION("incorrect surrogate values") { json _; CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uDC00\\uDC00\""), "[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uDC00'", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD7FF\\uDC00\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uD7FF\\uDC00'", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800]\""), "[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800]'", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\v\""), "[json.exception.parse_error.101] parse error at line 1, column 9: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800\\v'", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\u123\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: '\\u' must be followed by 4 hex digits; last read: '\"\\uD800\\u123\"'", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\uDBFF\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800\\uDBFF'", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\uE000\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800\\uE000'", json::parse_error&); } } #if 0 // NOLINT(readability-avoid-unconditional-preprocessor-if) SECTION("incorrect sequences") { SECTION("high surrogate without low surrogate") { // 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) + "\""; CAPTURE(json_text) CHECK_THROWS_AS(json::parse(json_text), json::parse_error&); } } SECTION("high surrogate with wrong low surrogate") { // 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) + "\""; CAPTURE(json_text) CHECK_THROWS_AS(json::parse(json_text), json::parse_error&); } } } SECTION("low surrogate without high surrogate") { // 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) + "\""; CAPTURE(json_text) CHECK_THROWS_AS(json::parse(json_text), json::parse_error&); } } } #endif } SECTION("read all unicode characters") { // read a file with all unicode characters stored as single-character // strings in a JSON array std::ifstream f(TEST_DATA_DIRECTORY "/json_nlohmann_tests/all_unicode.json"); json j; CHECK_NOTHROW(f >> j); // the array has 1112064 + 1 elements (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 (const auto& s : j) { // skip non-string JSON values if (!s.is_string()) { continue; } auto ptr = s.get<std::string>(); // tilde must be followed by 0 or 1 if (ptr == "~") { ptr += "0"; } // JSON Pointers must begin with "/" ptr.insert(0, "/"); CHECK_NOTHROW(json::json_pointer("/" + ptr)); // check escape/unescape roundtrip auto escaped = nlohmann::detail::escape(ptr); nlohmann::detail::unescape(escaped); CHECK(escaped == ptr); } } } SECTION("ignore byte-order-mark") { SECTION("in a stream") { // read a file with a UTF-8 BOM std::ifstream f(TEST_DATA_DIRECTORY "/json_nlohmann_tests/bom.json"); json j; CHECK_NOTHROW(f >> j); } SECTION("with an iterator") { std::string i = "\xef\xbb\xbf{\n \"foo\": true\n}"; json _; CHECK_NOTHROW(_ = json::parse(i.begin(), i.end())); } } SECTION("error for incomplete/wrong BOM") { json _; CHECK_THROWS_AS(_ = json::parse("\xef\xbb"), json::parse_error&); CHECK_THROWS_AS(_ = json::parse("\xef\xbb\xbb"), json::parse_error&); } } namespace { void roundtrip(bool success_expected, const std::string& s); void roundtrip(bool success_expected, const std::string& s) { CAPTURE(s) json _; // create JSON string value const json j = s; // create JSON text const std::string ps = std::string("\"") + s + "\""; if (success_expected) { // serialization succeeds CHECK_NOTHROW(j.dump()); // exclude parse test for U+0000 if (s[0] != '\0') { // parsing JSON text succeeds CHECK_NOTHROW(_ = json::parse(ps)); } // roundtrip succeeds CHECK_NOTHROW(_ = json::parse(j.dump())); // after roundtrip, the same string is stored const json jr = json::parse(j.dump()); CHECK(jr.get<std::string>() == s); } else { // serialization fails CHECK_THROWS_AS(j.dump(), json::type_error&); // parsing JSON text fails CHECK_THROWS_AS(_ = json::parse(ps), json::parse_error&); } } } // namespace TEST_CASE("Markus Kuhn's UTF-8 decoder capability and stress test") { // Markus Kuhn <http://www.cl.cam.ac.uk/~mgk25/> - 2015-08-28 - CC BY 4.0 // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt SECTION("1 Some correct UTF-8 text") { roundtrip(true, "κόσμε"); } SECTION("2 Boundary condition test cases") { SECTION("2.1 First possible sequence of a certain length") { // 2.1.1 1 byte (U-00000000) roundtrip(true, std::string("\0", 1)); // 2.1.2 2 bytes (U-00000080) roundtrip(true, "\xc2\x80"); // 2.1.3 3 bytes (U-00000800) roundtrip(true, "\xe0\xa0\x80"); // 2.1.4 4 bytes (U-00010000) roundtrip(true, "\xf0\x90\x80\x80"); // 2.1.5 5 bytes (U-00200000) roundtrip(false, "\xF8\x88\x80\x80\x80"); // 2.1.6 6 bytes (U-04000000) roundtrip(false, "\xFC\x84\x80\x80\x80\x80"); } SECTION("2.2 Last possible sequence of a certain length") { // 2.2.1 1 byte (U-0000007F) roundtrip(true, "\x7f"); // 2.2.2 2 bytes (U-000007FF) roundtrip(true, "\xdf\xbf"); // 2.2.3 3 bytes (U-0000FFFF) roundtrip(true, "\xef\xbf\xbf"); // 2.2.4 4 bytes (U-001FFFFF) roundtrip(false, "\xF7\xBF\xBF\xBF"); // 2.2.5 5 bytes (U-03FFFFFF) roundtrip(false, "\xFB\xBF\xBF\xBF\xBF"); // 2.2.6 6 bytes (U-7FFFFFFF) roundtrip(false, "\xFD\xBF\xBF\xBF\xBF\xBF"); } SECTION("2.3 Other boundary conditions") { // 2.3.1 U-0000D7FF = ed 9f bf roundtrip(true, "\xed\x9f\xbf"); // 2.3.2 U-0000E000 = ee 80 80 roundtrip(true, "\xee\x80\x80"); // 2.3.3 U-0000FFFD = ef bf bd roundtrip(true, "\xef\xbf\xbd"); // 2.3.4 U-0010FFFF = f4 8f bf bf roundtrip(true, "\xf4\x8f\xbf\xbf"); // 2.3.5 U-00110000 = f4 90 80 80 roundtrip(false, "\xf4\x90\x80\x80"); } } SECTION("3 Malformed sequences") { SECTION("3.1 Unexpected continuation bytes") { // Each unexpected continuation byte should be separately signalled as a // malformed sequence of its own. // 3.1.1 First continuation byte 0x80 roundtrip(false, "\x80"); // 3.1.2 Last continuation byte 0xbf roundtrip(false, "\xbf"); // 3.1.3 2 continuation bytes roundtrip(false, "\x80\xbf"); // 3.1.4 3 continuation bytes roundtrip(false, "\x80\xbf\x80"); // 3.1.5 4 continuation bytes roundtrip(false, "\x80\xbf\x80\xbf"); // 3.1.6 5 continuation bytes roundtrip(false, "\x80\xbf\x80\xbf\x80"); // 3.1.7 6 continuation bytes roundtrip(false, "\x80\xbf\x80\xbf\x80\xbf"); // 3.1.8 7 continuation bytes roundtrip(false, "\x80\xbf\x80\xbf\x80\xbf\x80"); // 3.1.9 Sequence of all 64 possible continuation bytes (0x80-0xbf) roundtrip(false, "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf"); } SECTION("3.2 Lonely start characters") { // 3.2.1 All 32 first bytes of 2-byte sequences (0xc0-0xdf) roundtrip(false, "\xc0 \xc1 \xc2 \xc3 \xc4 \xc5 \xc6 \xc7 \xc8 \xc9 \xca \xcb \xcc \xcd \xce \xcf \xd0 \xd1 \xd2 \xd3 \xd4 \xd5 \xd6 \xd7 \xd8 \xd9 \xda \xdb \xdc \xdd \xde \xdf"); // 3.2.2 All 16 first bytes of 3-byte sequences (0xe0-0xef) roundtrip(false, "\xe0 \xe1 \xe2 \xe3 \xe4 \xe5 \xe6 \xe7 \xe8 \xe9 \xea \xeb \xec \xed \xee \xef"); // 3.2.3 All 8 first bytes of 4-byte sequences (0xf0-0xf7) roundtrip(false, "\xf0 \xf1 \xf2 \xf3 \xf4 \xf5 \xf6 \xf7"); // 3.2.4 All 4 first bytes of 5-byte sequences (0xf8-0xfb) roundtrip(false, "\xf8 \xf9 \xfa \xfb"); // 3.2.5 All 2 first bytes of 6-byte sequences (0xfc-0xfd) roundtrip(false, "\xfc \xfd"); } SECTION("3.3 Sequences with last continuation byte missing") { // All bytes of an incomplete sequence should be signalled as a single // malformed sequence, i.e., you should see only a single replacement // character in each of the next 10 tests. (Characters as in section 2) // 3.3.1 2-byte sequence with last byte missing (U+0000) roundtrip(false, "\xc0"); // 3.3.2 3-byte sequence with last byte missing (U+0000) roundtrip(false, "\xe0\x80"); // 3.3.3 4-byte sequence with last byte missing (U+0000) roundtrip(false, "\xf0\x80\x80"); // 3.3.4 5-byte sequence with last byte missing (U+0000) roundtrip(false, "\xf8\x80\x80\x80"); // 3.3.5 6-byte sequence with last byte missing (U+0000) roundtrip(false, "\xfc\x80\x80\x80\x80"); // 3.3.6 2-byte sequence with last byte missing (U-000007FF) roundtrip(false, "\xdf"); // 3.3.7 3-byte sequence with last byte missing (U-0000FFFF) roundtrip(false, "\xef\xbf"); // 3.3.8 4-byte sequence with last byte missing (U-001FFFFF) roundtrip(false, "\xf7\xbf\xbf"); // 3.3.9 5-byte sequence with last byte missing (U-03FFFFFF) roundtrip(false, "\xfb\xbf\xbf\xbf"); // 3.3.10 6-byte sequence with last byte missing (U-7FFFFFFF) roundtrip(false, "\xfd\xbf\xbf\xbf\xbf"); } SECTION("3.4 Concatenation of incomplete sequences") { // All the 10 sequences of 3.3 concatenated, you should see 10 malformed // sequences being signalled: roundtrip(false, "\xc0\xe0\x80\xf0\x80\x80\xf8\x80\x80\x80\xfc\x80\x80\x80\x80\xdf\xef\xbf\xf7\xbf\xbf\xfb\xbf\xbf\xbf\xfd\xbf\xbf\xbf\xbf"); } SECTION("3.5 Impossible bytes") { // The following two bytes cannot appear in a correct UTF-8 string // 3.5.1 fe roundtrip(false, "\xfe"); // 3.5.2 ff roundtrip(false, "\xff"); // 3.5.3 fe fe ff ff roundtrip(false, "\xfe\xfe\xff\xff"); } } SECTION("4 Overlong sequences") { // The following sequences are not malformed according to the letter of // the Unicode 2.0 standard. However, they are longer then necessary and // a correct UTF-8 encoder is not allowed to produce them. A "safe UTF-8 // decoder" should reject them just like malformed sequences for two // reasons: (1) It helps to debug applications if overlong sequences are // not treated as valid representations of characters, because this helps // to spot problems more quickly. (2) Overlong sequences provide // alternative representations of characters, that could maliciously be // used to bypass filters that check only for ASCII characters. For // instance, a 2-byte encoded line feed (LF) would not be caught by a // line counter that counts only 0x0a bytes, but it would still be // processed as a line feed by an unsafe UTF-8 decoder later in the // pipeline. From a security point of view, ASCII compatibility of UTF-8 // sequences means also, that ASCII characters are *only* allowed to be // represented by ASCII bytes in the range 0x00-0x7f. To ensure this // aspect of ASCII compatibility, use only "safe UTF-8 decoders" that // reject overlong UTF-8 sequences for which a shorter encoding exists. SECTION("4.1 Examples of an overlong ASCII character") { // With a safe UTF-8 decoder, all of the following five overlong // representations of the ASCII character slash ("/") should be rejected // like a malformed UTF-8 sequence, for instance by substituting it with // a replacement character. If you see a slash below, you do not have a // safe UTF-8 decoder! // 4.1.1 U+002F = c0 af roundtrip(false, "\xc0\xaf"); // 4.1.2 U+002F = e0 80 af roundtrip(false, "\xe0\x80\xaf"); // 4.1.3 U+002F = f0 80 80 af roundtrip(false, "\xf0\x80\x80\xaf"); // 4.1.4 U+002F = f8 80 80 80 af roundtrip(false, "\xf8\x80\x80\x80\xaf"); // 4.1.5 U+002F = fc 80 80 80 80 af roundtrip(false, "\xfc\x80\x80\x80\x80\xaf"); } SECTION("4.2 Maximum overlong sequences") { // Below you see the highest Unicode value that is still resulting in an // overlong sequence if represented with the given number of bytes. This // is a boundary test for safe UTF-8 decoders. All five characters should // be rejected like malformed UTF-8 sequences. // 4.2.1 U-0000007F = c1 bf roundtrip(false, "\xc1\xbf"); // 4.2.2 U-000007FF = e0 9f bf roundtrip(false, "\xe0\x9f\xbf"); // 4.2.3 U-0000FFFF = f0 8f bf bf roundtrip(false, "\xf0\x8f\xbf\xbf"); // 4.2.4 U-001FFFFF = f8 87 bf bf bf roundtrip(false, "\xf8\x87\xbf\xbf\xbf"); // 4.2.5 U-03FFFFFF = fc 83 bf bf bf bf roundtrip(false, "\xfc\x83\xbf\xbf\xbf\xbf"); } SECTION("4.3 Overlong representation of the NUL character") { // The following five sequences should also be rejected like malformed // UTF-8 sequences and should not be treated like the ASCII NUL // character. // 4.3.1 U+0000 = c0 80 roundtrip(false, "\xc0\x80"); // 4.3.2 U+0000 = e0 80 80 roundtrip(false, "\xe0\x80\x80"); // 4.3.3 U+0000 = f0 80 80 80 roundtrip(false, "\xf0\x80\x80\x80"); // 4.3.4 U+0000 = f8 80 80 80 80 roundtrip(false, "\xf8\x80\x80\x80\x80"); // 4.3.5 U+0000 = fc 80 80 80 80 80 roundtrip(false, "\xfc\x80\x80\x80\x80\x80"); } } SECTION("5 Illegal code positions") { // The following UTF-8 sequences should be rejected like malformed // sequences, because they never represent valid ISO 10646 characters and // a UTF-8 decoder that accepts them might introduce security problems // comparable to overlong UTF-8 sequences. SECTION("5.1 Single UTF-16 surrogates") { // 5.1.1 U+D800 = ed a0 80 roundtrip(false, "\xed\xa0\x80"); // 5.1.2 U+DB7F = ed ad bf roundtrip(false, "\xed\xad\xbf"); // 5.1.3 U+DB80 = ed ae 80 roundtrip(false, "\xed\xae\x80"); // 5.1.4 U+DBFF = ed af bf roundtrip(false, "\xed\xaf\xbf"); // 5.1.5 U+DC00 = ed b0 80 roundtrip(false, "\xed\xb0\x80"); // 5.1.6 U+DF80 = ed be 80 roundtrip(false, "\xed\xbe\x80"); // 5.1.7 U+DFFF = ed bf bf roundtrip(false, "\xed\xbf\xbf"); } SECTION("5.2 Paired UTF-16 surrogates") { // 5.2.1 U+D800 U+DC00 = ed a0 80 ed b0 80 roundtrip(false, "\xed\xa0\x80\xed\xb0\x80"); // 5.2.2 U+D800 U+DFFF = ed a0 80 ed bf bf roundtrip(false, "\xed\xa0\x80\xed\xbf\xbf"); // 5.2.3 U+DB7F U+DC00 = ed ad bf ed b0 80 roundtrip(false, "\xed\xad\xbf\xed\xb0\x80"); // 5.2.4 U+DB7F U+DFFF = ed ad bf ed bf bf roundtrip(false, "\xed\xad\xbf\xed\xbf\xbf"); // 5.2.5 U+DB80 U+DC00 = ed ae 80 ed b0 80 roundtrip(false, "\xed\xae\x80\xed\xb0\x80"); // 5.2.6 U+DB80 U+DFFF = ed ae 80 ed bf bf roundtrip(false, "\xed\xae\x80\xed\xbf\xbf"); // 5.2.7 U+DBFF U+DC00 = ed af bf ed b0 80 roundtrip(false, "\xed\xaf\xbf\xed\xb0\x80"); // 5.2.8 U+DBFF U+DFFF = ed af bf ed bf bf roundtrip(false, "\xed\xaf\xbf\xed\xbf\xbf"); } SECTION("5.3 Noncharacter code positions") { // The following "noncharacters" are "reserved for internal use" by // applications, and according to older versions of the Unicode Standard // "should never be interchanged". Unicode Corrigendum #9 dropped the // latter restriction. Nevertheless, their presence in incoming UTF-8 data // can remain a potential security risk, depending on what use is made of // these codes subsequently. Examples of such internal use: // // - Some file APIs with 16-bit characters may use the integer value -1 // = U+FFFF to signal an end-of-file (EOF) or error condition. // // - In some UTF-16 receivers, code point U+FFFE might trigger a // byte-swap operation (to convert between UTF-16LE and UTF-16BE). // // With such internal use of noncharacters, it may be desirable and safer // to block those code points in UTF-8 decoders, as they should never // occur legitimately in incoming UTF-8 data, and could trigger unsafe // behaviour in subsequent processing. // Particularly problematic noncharacters in 16-bit applications: // 5.3.1 U+FFFE = ef bf be roundtrip(true, "\xef\xbf\xbe"); // 5.3.2 U+FFFF = ef bf bf roundtrip(true, "\xef\xbf\xbf"); // 5.3.3 U+FDD0 .. U+FDEF roundtrip(true, "\xEF\xB7\x90"); roundtrip(true, "\xEF\xB7\x91"); roundtrip(true, "\xEF\xB7\x92"); roundtrip(true, "\xEF\xB7\x93"); roundtrip(true, "\xEF\xB7\x94"); roundtrip(true, "\xEF\xB7\x95"); roundtrip(true, "\xEF\xB7\x96"); roundtrip(true, "\xEF\xB7\x97"); roundtrip(true, "\xEF\xB7\x98"); roundtrip(true, "\xEF\xB7\x99"); roundtrip(true, "\xEF\xB7\x9A"); roundtrip(true, "\xEF\xB7\x9B"); roundtrip(true, "\xEF\xB7\x9C"); roundtrip(true, "\xEF\xB7\x9D"); roundtrip(true, "\xEF\xB7\x9E"); roundtrip(true, "\xEF\xB7\x9F"); roundtrip(true, "\xEF\xB7\xA0"); roundtrip(true, "\xEF\xB7\xA1"); roundtrip(true, "\xEF\xB7\xA2"); roundtrip(true, "\xEF\xB7\xA3"); roundtrip(true, "\xEF\xB7\xA4"); roundtrip(true, "\xEF\xB7\xA5"); roundtrip(true, "\xEF\xB7\xA6"); roundtrip(true, "\xEF\xB7\xA7"); roundtrip(true, "\xEF\xB7\xA8"); roundtrip(true, "\xEF\xB7\xA9"); roundtrip(true, "\xEF\xB7\xAA"); roundtrip(true, "\xEF\xB7\xAB"); roundtrip(true, "\xEF\xB7\xAC"); roundtrip(true, "\xEF\xB7\xAD"); roundtrip(true, "\xEF\xB7\xAE"); roundtrip(true, "\xEF\xB7\xAF"); // 5.3.4 U+nFFFE U+nFFFF (for n = 1..10) roundtrip(true, "\xF0\x9F\xBF\xBF"); roundtrip(true, "\xF0\xAF\xBF\xBF"); roundtrip(true, "\xF0\xBF\xBF\xBF"); roundtrip(true, "\xF1\x8F\xBF\xBF"); roundtrip(true, "\xF1\x9F\xBF\xBF"); roundtrip(true, "\xF1\xAF\xBF\xBF"); roundtrip(true, "\xF1\xBF\xBF\xBF"); roundtrip(true, "\xF2\x8F\xBF\xBF"); roundtrip(true, "\xF2\x9F\xBF\xBF"); roundtrip(true, "\xF2\xAF\xBF\xBF"); } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-udt.cpp
.cpp
22,617
865
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" // disable -Wnoexcept due to class Evil DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wnoexcept") #include <nlohmann/json.hpp> using nlohmann::json; #ifdef JSON_TEST_NO_GLOBAL_UDLS using namespace nlohmann::literals; // NOLINT(google-build-using-namespace) #endif #include <map> #include <memory> #include <string> #include <utility> namespace udt { enum class country { china, france, russia }; struct age { int m_val; age(int rhs = 0) : m_val(rhs) {} }; struct name { std::string m_val; name(std::string rhs = "") : m_val(std::move(rhs)) {} }; struct address { std::string m_val; address(std::string rhs = "") : m_val(std::move(rhs)) {} }; struct person { age m_age{}; name m_name{}; country m_country{}; person() = default; person(const age& a, name n, const country& c) : m_age(a), m_name(std::move(n)), m_country(c) {} }; struct contact { person m_person{}; address m_address{}; contact() = default; contact(person p, address a) : m_person(std::move(p)), m_address(std::move(a)) {} }; struct contact_book { name m_book_name{}; std::vector<contact> m_contacts{}; contact_book() = default; contact_book(name n, std::vector<contact> c) : m_book_name(std::move(n)), m_contacts(std::move(c)) {} }; } // namespace udt // to_json methods namespace udt { // templates because of the custom_json tests (see below) template <typename BasicJsonType> static void to_json(BasicJsonType& j, age a) { j = a.m_val; } template <typename BasicJsonType> static void to_json(BasicJsonType& j, const name& n) { j = n.m_val; } template <typename BasicJsonType> static void to_json(BasicJsonType& j, country c) { switch (c) { case country::china: j = "中华人民共和国"; return; case country::france: j = "France"; return; case country::russia: j = "Российская Федерация"; return; default: break; } } template <typename BasicJsonType> static void to_json(BasicJsonType& j, const person& p) { j = BasicJsonType{{"age", p.m_age}, {"name", p.m_name}, {"country", p.m_country}}; } static void to_json(nlohmann::json& j, const address& a) { j = a.m_val; } static void to_json(nlohmann::json& j, const contact& c) { j = json{{"person", c.m_person}, {"address", c.m_address}}; } static void to_json(nlohmann::json& j, const contact_book& cb) { j = json{{"name", cb.m_book_name}, {"contacts", cb.m_contacts}}; } // operators static bool operator==(age lhs, age rhs) { return lhs.m_val == rhs.m_val; } static bool operator==(const address& lhs, const address& rhs) { return lhs.m_val == rhs.m_val; } static bool operator==(const name& lhs, const name& rhs) { return lhs.m_val == rhs.m_val; } static bool operator==(const person& lhs, const person& rhs) { return std::tie(lhs.m_name, lhs.m_age) == std::tie(rhs.m_name, rhs.m_age); } static bool operator==(const contact& lhs, const contact& rhs) { return std::tie(lhs.m_person, lhs.m_address) == std::tie(rhs.m_person, rhs.m_address); } static bool operator==(const contact_book& lhs, const contact_book& rhs) { return std::tie(lhs.m_book_name, lhs.m_contacts) == std::tie(rhs.m_book_name, rhs.m_contacts); } } // namespace udt // from_json methods namespace udt { template <typename BasicJsonType> static void from_json(const BasicJsonType& j, age& a) { a.m_val = j.template get<int>(); } template <typename BasicJsonType> static void from_json(const BasicJsonType& j, name& n) { n.m_val = j.template get<std::string>(); } template <typename BasicJsonType> static void from_json(const BasicJsonType& j, country& c) { const auto str = j.template get<std::string>(); const std::map<std::string, country> m = { {"中华人民共和国", country::china}, {"France", country::france}, {"Российская Федерация", country::russia} }; const auto it = m.find(str); // TODO(nlohmann) test exceptions c = it->second; } template <typename BasicJsonType> static void from_json(const BasicJsonType& j, person& p) { p.m_age = j["age"].template get<age>(); p.m_name = j["name"].template get<name>(); p.m_country = j["country"].template get<country>(); } static void from_json(const nlohmann::json& j, address& a) { a.m_val = j.get<std::string>(); } static void from_json(const nlohmann::json& j, contact& c) { c.m_person = j["person"].get<person>(); c.m_address = j["address"].get<address>(); } static void from_json(const nlohmann::json& j, contact_book& cb) { cb.m_book_name = j["name"].get<name>(); cb.m_contacts = j["contacts"].get<std::vector<contact>>(); } } // namespace udt TEST_CASE("basic usage" * doctest::test_suite("udt")) { // a bit narcissistic maybe :) ? const udt::age a { 23 }; const udt::name n{"theo"}; const udt::country c{udt::country::france}; const udt::person sfinae_addict{a, n, c}; const udt::person senior_programmer{{42}, {"王芳"}, udt::country::china}; const udt::address addr{"Paris"}; const udt::contact cpp_programmer{sfinae_addict, addr}; const udt::contact_book book{{"C++"}, {cpp_programmer, {senior_programmer, addr}}}; SECTION("conversion to json via free-functions") { CHECK(json(a) == json(23)); CHECK(json(n) == json("theo")); CHECK(json(c) == json("France")); CHECK(json(sfinae_addict) == R"({"name":"theo", "age":23, "country":"France"})"_json); CHECK(json("Paris") == json(addr)); CHECK(json(cpp_programmer) == R"({"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"})"_json); CHECK( json(book) == R"({"name":"C++", "contacts" : [{"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"}, {"person" : {"age":42, "country":"中华人民共和国", "name":"王芳"}, "address":"Paris"}]})"_json); } SECTION("conversion from json via free-functions") { const auto big_json = R"({"name":"C++", "contacts" : [{"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"}, {"person" : {"age":42, "country":"中华人民共和国", "name":"王芳"}, "address":"Paris"}]})"_json; SECTION("via explicit calls to get") { const auto parsed_book = big_json.get<udt::contact_book>(); const auto book_name = big_json["name"].get<udt::name>(); const auto contacts = big_json["contacts"].get<std::vector<udt::contact>>(); const auto contact_json = big_json["contacts"].at(0); const auto contact = contact_json.get<udt::contact>(); const auto person = contact_json["person"].get<udt::person>(); const auto address = contact_json["address"].get<udt::address>(); const auto age = contact_json["person"]["age"].get<udt::age>(); const auto country = contact_json["person"]["country"].get<udt::country>(); const auto name = contact_json["person"]["name"].get<udt::name>(); CHECK(age == a); CHECK(name == n); CHECK(country == c); CHECK(address == addr); CHECK(person == sfinae_addict); CHECK(contact == cpp_programmer); CHECK(contacts == book.m_contacts); CHECK(book_name == udt::name{"C++"}); CHECK(book == parsed_book); } SECTION("via explicit calls to get_to") { udt::person person; udt::name name; json person_json = big_json["contacts"][0]["person"]; CHECK(person_json.get_to(person) == sfinae_addict); // correct reference gets returned person_json["name"].get_to(name).m_val = "new name"; CHECK(name.m_val == "new name"); } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("implicit conversions") { const udt::contact_book parsed_book = big_json; const udt::name book_name = big_json["name"]; const std::vector<udt::contact> contacts = big_json["contacts"]; const auto contact_json = big_json["contacts"].at(0); const udt::contact contact = contact_json; const udt::person person = contact_json["person"]; const udt::address address = contact_json["address"]; const udt::age age = contact_json["person"]["age"]; const udt::country country = contact_json["person"]["country"]; const udt::name name = contact_json["person"]["name"]; CHECK(age == a); CHECK(name == n); CHECK(country == c); CHECK(address == addr); CHECK(person == sfinae_addict); CHECK(contact == cpp_programmer); CHECK(contacts == book.m_contacts); CHECK(book_name == udt::name{"C++"}); CHECK(book == parsed_book); } #endif } } namespace udt { struct legacy_type { std::string number{}; legacy_type() = default; legacy_type(std::string n) : number(std::move(n)) {} }; } // namespace udt namespace nlohmann { template <typename T> struct adl_serializer<std::shared_ptr<T>> { static void to_json(json& j, const std::shared_ptr<T>& opt) { if (opt) { j = *opt; } else { j = nullptr; } } static void from_json(const json& j, std::shared_ptr<T>& opt) { if (j.is_null()) { opt = nullptr; } else { opt.reset(new T(j.get<T>())); // NOLINT(cppcoreguidelines-owning-memory) } } }; template <> struct adl_serializer<udt::legacy_type> { static void to_json(json& j, const udt::legacy_type& l) { j = std::stoi(l.number); } static void from_json(const json& j, udt::legacy_type& l) { l.number = std::to_string(j.get<int>()); } }; } // namespace nlohmann TEST_CASE("adl_serializer specialization" * doctest::test_suite("udt")) { SECTION("partial specialization") { SECTION("to_json") { std::shared_ptr<udt::person> optPerson; json j = optPerson; CHECK(j.is_null()); optPerson.reset(new udt::person{{42}, {"John Doe"}, udt::country::russia}); // NOLINT(cppcoreguidelines-owning-memory,modernize-make-shared) j = optPerson; CHECK_FALSE(j.is_null()); CHECK(j.get<udt::person>() == *optPerson); } SECTION("from_json") { auto person = udt::person{{42}, {"John Doe"}, udt::country::russia}; json j = person; auto optPerson = j.get<std::shared_ptr<udt::person>>(); REQUIRE(optPerson); CHECK(*optPerson == person); j = nullptr; optPerson = j.get<std::shared_ptr<udt::person>>(); CHECK(!optPerson); } } SECTION("total specialization") { SECTION("to_json") { udt::legacy_type const lt{"4242"}; json const j = lt; CHECK(j.get<int>() == 4242); } SECTION("from_json") { json const j = 4242; auto lt = j.get<udt::legacy_type>(); CHECK(lt.number == "4242"); } } } namespace nlohmann { template <> struct adl_serializer<std::vector<float>> { using type = std::vector<float>; static void to_json(json& j, const type& /*type*/) { j = "hijacked!"; } static void from_json(const json& /*unnamed*/, type& opt) { opt = {42.0, 42.0, 42.0}; } // preferred version static type from_json(const json& /*unnamed*/) { return {4.0, 5.0, 6.0}; } }; } // namespace nlohmann TEST_CASE("even supported types can be specialized" * doctest::test_suite("udt")) { json const j = std::vector<float> {1.0, 2.0, 3.0}; CHECK(j.dump() == R"("hijacked!")"); auto f = j.get<std::vector<float>>(); // the single argument from_json method is preferred CHECK((f == std::vector<float> {4.0, 5.0, 6.0})); } namespace nlohmann { template <typename T> struct adl_serializer<std::unique_ptr<T>> { static void to_json(json& j, const std::unique_ptr<T>& opt) { if (opt) { j = *opt; } else { j = nullptr; } } // this is the overload needed for non-copyable types, static std::unique_ptr<T> from_json(const json& j) { if (j.is_null()) { return nullptr; } return std::unique_ptr<T>(new T(j.get<T>())); } }; } // namespace nlohmann TEST_CASE("Non-copyable types" * doctest::test_suite("udt")) { SECTION("to_json") { std::unique_ptr<udt::person> optPerson; json j = optPerson; CHECK(j.is_null()); optPerson.reset(new udt::person{{42}, {"John Doe"}, udt::country::russia}); // NOLINT(cppcoreguidelines-owning-memory,modernize-make-unique) j = optPerson; CHECK_FALSE(j.is_null()); CHECK(j.get<udt::person>() == *optPerson); } SECTION("from_json") { auto person = udt::person{{42}, {"John Doe"}, udt::country::russia}; json j = person; auto optPerson = j.get<std::unique_ptr<udt::person>>(); REQUIRE(optPerson); CHECK(*optPerson == person); j = nullptr; optPerson = j.get<std::unique_ptr<udt::person>>(); CHECK(!optPerson); } } // custom serializer - advanced usage // pack structs that are pod-types (but not scalar types) // relies on adl for any other type template <typename T, typename = void> struct pod_serializer { // use adl for non-pods, or scalar types template < typename BasicJsonType, typename U = T, typename std::enable_if < !(std::is_pod<U>::value && std::is_class<U>::value), int >::type = 0 > static void from_json(const BasicJsonType& j, U& t) { using nlohmann::from_json; from_json(j, t); } // special behaviour for pods template < typename BasicJsonType, typename U = T, typename std::enable_if < std::is_pod<U>::value && std::is_class<U>::value, int >::type = 0 > static void from_json(const BasicJsonType& j, U& t) { std::uint64_t value = 0; // The following block is no longer relevant in this serializer, make another one that shows the issue // the problem arises only when one from_json method is defined without any constraint // // Why cannot we simply use: j.get<std::uint64_t>() ? // Well, with the current experiment, the get method looks for a from_json // function, which we are currently defining! // This would end up in a stack overflow. Calling nlohmann::from_json is a // workaround (is it?). // I shall find a good way to avoid this once all constructors are converted // to free methods // // In short, constructing a json by constructor calls to_json // calling get calls from_json, for now, we cannot do this in custom // serializers nlohmann::from_json(j, value); auto* bytes = static_cast<char*>(static_cast<void*>(&value)); std::memcpy(&t, bytes, sizeof(value)); } template < typename BasicJsonType, typename U = T, typename std::enable_if < !(std::is_pod<U>::value && std::is_class<U>::value), int >::type = 0 > static void to_json(BasicJsonType& j, const T& t) { using nlohmann::to_json; to_json(j, t); } template < typename BasicJsonType, typename U = T, typename std::enable_if < std::is_pod<U>::value && std::is_class<U>::value, int >::type = 0 > static void to_json(BasicJsonType& j, const T& t) noexcept { const auto* bytes = static_cast< const unsigned char*>(static_cast<const void*>(&t)); std::uint64_t value = 0; std::memcpy(&value, bytes, sizeof(value)); nlohmann::to_json(j, value); } }; namespace udt { struct small_pod { int begin; char middle; short end; }; struct non_pod { std::string s{}; non_pod() = default; non_pod(std::string S) : s(std::move(S)) {} }; template <typename BasicJsonType> static void to_json(BasicJsonType& j, const non_pod& np) { j = np.s; } template <typename BasicJsonType> static void from_json(const BasicJsonType& j, non_pod& np) { np.s = j.template get<std::string>(); } static bool operator==(small_pod lhs, small_pod rhs) noexcept { return std::tie(lhs.begin, lhs.middle, lhs.end) == std::tie(rhs.begin, rhs.middle, rhs.end); } static bool operator==(const non_pod& lhs, const non_pod& rhs) noexcept { return lhs.s == rhs.s; } static std::ostream& operator<<(std::ostream& os, small_pod l) { return os << "begin: " << l.begin << ", middle: " << l.middle << ", end: " << l.end; } } // namespace udt TEST_CASE("custom serializer for pods" * doctest::test_suite("udt")) { using custom_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, double, std::allocator, pod_serializer>; auto p = udt::small_pod{42, '/', 42}; custom_json const j = p; auto p2 = j.get<udt::small_pod>(); CHECK(p == p2); auto np = udt::non_pod{{"non-pod"}}; custom_json const j2 = np; auto np2 = j2.get<udt::non_pod>(); CHECK(np == np2); } template <typename T, typename> struct another_adl_serializer; using custom_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, double, std::allocator, another_adl_serializer>; template <typename T, typename> struct another_adl_serializer { static void from_json(const custom_json& j, T& t) { using nlohmann::from_json; from_json(j, t); } static void to_json(custom_json& j, const T& t) { using nlohmann::to_json; to_json(j, t); } }; TEST_CASE("custom serializer that does adl by default" * doctest::test_suite("udt")) { auto me = udt::person{{23}, {"theo"}, udt::country::france}; json const j = me; custom_json const cj = me; CHECK(j.dump() == cj.dump()); CHECK(me == j.get<udt::person>()); CHECK(me == cj.get<udt::person>()); } TEST_CASE("different basic_json types conversions") { SECTION("null") { json const j; custom_json cj = j; CHECK(cj == nullptr); } SECTION("boolean") { json const j = true; custom_json cj = j; CHECK(cj == true); } SECTION("discarded") { json const j(json::value_t::discarded); custom_json cj; CHECK_NOTHROW(cj = j); CHECK(cj.type() == custom_json::value_t::discarded); } SECTION("array") { json const j = {1, 2, 3}; custom_json const cj = j; CHECK((cj == std::vector<int> {1, 2, 3})); } SECTION("integer") { json const j = 42; custom_json cj = j; CHECK(cj == 42); } SECTION("float") { json const j = 42.0; custom_json cj = j; CHECK(cj == 42.0); } SECTION("unsigned") { json const j = 42u; custom_json cj = j; CHECK(cj == 42u); } SECTION("string") { json const j = "forty-two"; custom_json cj = j; CHECK(cj == "forty-two"); } SECTION("binary") { json j = json::binary({1, 2, 3}, 42); custom_json cj = j; CHECK(cj.get_binary().subtype() == 42); std::vector<std::uint8_t> cv = cj.get_binary(); std::vector<std::uint8_t> v = j.get_binary(); CHECK(cv == v); } SECTION("object") { json const j = {{"forty", "two"}}; custom_json cj = j; auto m = j.get<std::map<std::string, std::string>>(); CHECK(cj == m); } SECTION("get<custom_json>") { json const j = 42; custom_json cj = j.get<custom_json>(); CHECK(cj == 42); } } namespace { struct incomplete; // std::is_constructible is broken on macOS' libc++ // use the cppreference implementation template <typename T, typename = void> struct is_constructible_patched : std::false_type {}; template <typename T> struct is_constructible_patched<T, decltype(void(json(std::declval<T>())))> : std::true_type {}; } // namespace TEST_CASE("an incomplete type does not trigger a compiler error in non-evaluated context" * doctest::test_suite("udt")) { static_assert(!is_constructible_patched<json, incomplete>::value, ""); } namespace { class Evil { public: Evil() = default; template <typename T> Evil(T t) : m_i(sizeof(t)) { static_cast<void>(t); // fix MSVC's C4100 warning } int m_i = 0; }; void from_json(const json& /*unused*/, Evil& /*unused*/) {} } // namespace TEST_CASE("Issue #924") { // Prevent get<std::vector<Evil>>() to throw auto j = json::array(); CHECK_NOTHROW(j.get<Evil>()); CHECK_NOTHROW(j.get<std::vector<Evil>>()); // silence Wunused-template warnings Evil e(1); CHECK(e.m_i >= 0); } TEST_CASE("Issue #1237") { struct non_convertible_type {}; static_assert(!std::is_convertible<json, non_convertible_type>::value, ""); } namespace { class no_iterator_type { public: no_iterator_type(std::initializer_list<int> l) : _v(l) {} std::vector<int>::const_iterator begin() const { return _v.begin(); } std::vector<int>::const_iterator end() const { return _v.end(); } private: std::vector<int> _v; }; } // namespace TEST_CASE("compatible array type, without iterator type alias") { no_iterator_type const vec{1, 2, 3}; json const j = vec; } DOCTEST_GCC_SUPPRESS_WARNING_POP
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-algorithms.cpp
.cpp
12,285
370
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #include <algorithm> #include <nlohmann/json.hpp> using nlohmann::json; TEST_CASE("algorithms") { json j_array = {13, 29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz"}; json j_object = {{"one", 1}, {"two", 2}}; SECTION("non-modifying sequence operations") { SECTION("std::all_of") { CHECK(std::all_of(j_array.begin(), j_array.end(), [](const json & value) { return !value.empty(); })); CHECK(std::all_of(j_object.begin(), j_object.end(), [](const json & value) { return value.type() == json::value_t::number_integer; })); } SECTION("std::any_of") { CHECK(std::any_of(j_array.begin(), j_array.end(), [](const json & value) { return value.is_string() && value.get<std::string>() == "foo"; })); CHECK(std::any_of(j_object.begin(), j_object.end(), [](const json & value) { return value.get<int>() > 1; })); } SECTION("std::none_of") { CHECK(std::none_of(j_array.begin(), j_array.end(), [](const json & value) { return value.empty(); })); CHECK(std::none_of(j_object.begin(), j_object.end(), [](const json & value) { return value.get<int>() <= 0; })); } SECTION("std::for_each") { SECTION("reading") { int sum = 0; std::for_each(j_array.cbegin(), j_array.cend(), [&sum](const json & value) { if (value.is_number()) { sum += static_cast<int>(value); } }); CHECK(sum == 45); } SECTION("writing") { auto add17 = [](json & value) { if (value.is_array()) { value.push_back(17); } }; std::for_each(j_array.begin(), j_array.end(), add17); CHECK(j_array[6] == json({1, 2, 3, 17})); } } SECTION("std::count") { CHECK(std::count(j_array.begin(), j_array.end(), json(true)) == 1); } SECTION("std::count_if") { CHECK(std::count_if(j_array.begin(), j_array.end(), [](const json & value) { return (value.is_number()); }) == 3); CHECK(std::count_if(j_array.begin(), j_array.end(), [](const json&) { return true; }) == 9); } SECTION("std::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()); CHECK(*res.first == json({{"one", 1}, {"two", 2}})); CHECK(*res.second == json({{"one", 1}, {"two", 2}, {"three", 3}})); } SECTION("std::equal") { SECTION("using operator==") { CHECK(std::equal(j_array.begin(), j_array.end(), j_array.begin())); CHECK(std::equal(j_object.begin(), j_object.end(), j_object.begin())); CHECK(!std::equal(j_array.begin(), j_array.end(), j_object.begin())); } SECTION("using user-defined comparison") { // 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"}; CHECK(!std::equal(j_array.begin(), j_array.end(), j_array2.begin())); CHECK(std::equal(j_array.begin(), j_array.end(), j_array2.begin(), [](const json & a, const json & b) { return (a.size() == b.size()); })); } } SECTION("std::find") { auto it = std::find(j_array.begin(), j_array.end(), json(false)); CHECK(std::distance(j_array.begin(), it) == 5); } SECTION("std::find_if") { auto it = std::find_if(j_array.begin(), j_array.end(), [](const json & value) { return value.is_boolean(); }); CHECK(std::distance(j_array.begin(), it) == 4); } SECTION("std::find_if_not") { auto it = std::find_if_not(j_array.begin(), j_array.end(), [](const json & value) { return value.is_number(); }); CHECK(std::distance(j_array.begin(), it) == 3); } SECTION("std::adjacent_find") { CHECK(std::adjacent_find(j_array.begin(), j_array.end()) == j_array.end()); CHECK(std::adjacent_find(j_array.begin(), j_array.end(), [](const json & v1, const json & v2) { return v1.type() == v2.type(); }) == j_array.begin()); } } SECTION("modifying sequence operations") { SECTION("std::reverse") { std::reverse(j_array.begin(), j_array.end()); CHECK(j_array == json({"baz", "foo", {1, 2, 3}, false, true, {{"one", 1}, {"two", 2}}, 3, 29, 13})); } SECTION("std::rotate") { std::rotate(j_array.begin(), j_array.begin() + 1, j_array.end()); CHECK(j_array == json({29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz", 13})); } SECTION("std::partition") { auto it = std::partition(j_array.begin(), j_array.end(), [](const json & v) { return v.is_string(); }); CHECK(std::distance(j_array.begin(), it) == 2); CHECK(!it[2].is_string()); } } SECTION("sorting operations") { SECTION("std::sort") { SECTION("with standard comparison") { json j = {13, 29, 3, {{"one", 1}, {"two", 2}}, true, false, {1, 2, 3}, "foo", "baz", nullptr}; std::sort(j.begin(), j.end()); CHECK(j == json({nullptr, false, true, 3, 13, 29, {{"one", 1}, {"two", 2}}, {1, 2, 3}, "baz", "foo"})); } SECTION("with user-defined comparison") { 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(); }); CHECK(j == json({nullptr, 3, {{"one", 1}, {"two", 2}}, {1, 2, 3}})); } SECTION("sorting an object") { json j({{"one", 1}, {"two", 2}}); CHECK_THROWS_WITH_AS(std::sort(j.begin(), j.end()), "[json.exception.invalid_iterator.209] cannot use offsets with object iterators", json::invalid_iterator&); } } SECTION("std::partial_sort") { 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()); CHECK(j == json({nullptr, false, true, 3, {{"one", 1}, {"two", 2}}, 29, {1, 2, 3}, "foo", "baz", 13})); } } SECTION("set operations") { SECTION("std::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)); CHECK(j3 == json({1, 2, 2, 3, 4, 5, 6, 7, 8})); } } SECTION("std::set_difference") { 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)); CHECK(j3 == json({4, 6, 8})); } SECTION("std::set_intersection") { 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)); CHECK(j3 == json({1, 2, 3, 5, 7})); } SECTION("std::set_union") { 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)); CHECK(j3 == json({1, 2, 3, 4, 5, 6, 7, 8})); } SECTION("std::set_symmetric_difference") { 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)); CHECK(j3 == json({1, 3, 4, 5, 6, 7, 8})); } } SECTION("heap operations") { std::make_heap(j_array.begin(), j_array.end()); CHECK(std::is_heap(j_array.begin(), j_array.end())); std::sort_heap(j_array.begin(), j_array.end()); CHECK(j_array == json({false, true, 3, 13, 29, {{"one", 1}, {"two", 2}}, {1, 2, 3}, "baz", "foo"})); } SECTION("iota") { SECTION("int") { json json_arr = {0, 5, 2, 4, 10, 20, 30, 40, 50, 1}; std::iota(json_arr.begin(), json_arr.end(), 0); CHECK(json_arr == json({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); } SECTION("double") { json json_arr = {0.5, 1.5, 1.3, 4.1, 10.2, 20.5, 30.6, 40.1, 50.22, 1.5}; std::iota(json_arr.begin(), json_arr.end(), 0.5); CHECK(json_arr == json({0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5})); } SECTION("char") { json json_arr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '0', '1'}; std::iota(json_arr.begin(), json_arr.end(), '0'); CHECK(json_arr == json({'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'})); } } SECTION("copy") { SECTION("copy without if") { json dest_arr; const json source_arr = {1, 2, 3, 4}; std::copy(source_arr.begin(), source_arr.end(), std::back_inserter(dest_arr)); CHECK(dest_arr == source_arr); } SECTION("copy if") { json dest_arr; const json source_arr = {0, 3, 6, 9, 12, 15, 20}; std::copy_if(source_arr.begin(), source_arr.end(), std::back_inserter(dest_arr), [](const json & _value) { return _value.get<int>() % 3 == 0; }); CHECK(dest_arr == json({0, 3, 6, 9, 12, 15})); } SECTION("copy n") { const json source_arr = {0, 1, 2, 3, 4, 5, 6, 7}; json dest_arr; const unsigned char numToCopy = 2; std::copy_n(source_arr.begin(), numToCopy, std::back_inserter(dest_arr)); CHECK(dest_arr == json{0, 1}); } SECTION("copy n chars") { const json source_arr = {'1', '2', '3', '4', '5', '6', '7'}; json dest_arr; const unsigned char numToCopy = 4; std::copy_n(source_arr.begin(), numToCopy, std::back_inserter(dest_arr)); CHECK(dest_arr == json{'1', '2', '3', '4'}); } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-wstring.cpp
.cpp
2,469
100
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #include <nlohmann/json.hpp> using nlohmann::json; // ICPC errors out on multibyte character sequences in source files #ifndef __INTEL_COMPILER namespace { bool wstring_is_utf16(); bool wstring_is_utf16() { return (std::wstring(L"💩") == std::wstring(L"\U0001F4A9")); } bool u16string_is_utf16(); bool u16string_is_utf16() { return (std::u16string(u"💩") == std::u16string(u"\U0001F4A9")); } bool u32string_is_utf32(); bool u32string_is_utf32() { return (std::u32string(U"💩") == std::u32string(U"\U0001F4A9")); } } // namespace TEST_CASE("wide strings") { SECTION("std::wstring") { if (wstring_is_utf16()) { std::wstring const w = L"[12.2,\"Ⴥaäö💤🧢\"]"; json const j = json::parse(w); CHECK(j.dump() == "[12.2,\"Ⴥaäö💤🧢\"]"); } } SECTION("invalid std::wstring") { if (wstring_is_utf16()) { std::wstring const w = L"\"\xDBFF"; json _; CHECK_THROWS_AS(_ = json::parse(w), json::parse_error&); } } SECTION("std::u16string") { if (u16string_is_utf16()) { std::u16string const w = u"[12.2,\"Ⴥaäö💤🧢\"]"; json const j = json::parse(w); CHECK(j.dump() == "[12.2,\"Ⴥaäö💤🧢\"]"); } } SECTION("invalid std::u16string") { if (wstring_is_utf16()) { std::u16string const w = u"\"\xDBFF"; json _; CHECK_THROWS_AS(_ = json::parse(w), json::parse_error&); } } SECTION("std::u32string") { if (u32string_is_utf32()) { std::u32string const w = U"[12.2,\"Ⴥaäö💤🧢\"]"; json const j = json::parse(w); CHECK(j.dump() == "[12.2,\"Ⴥaäö💤🧢\"]"); } } SECTION("invalid std::u32string") { if (u32string_is_utf32()) { std::u32string const w = U"\"\x110000"; json _; CHECK_THROWS_AS(_ = json::parse(w), json::parse_error&); } } } #endif
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-iterators1.cpp
.cpp
50,621
1,631
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #define JSON_TESTS_PRIVATE #include <nlohmann/json.hpp> using nlohmann::json; TEST_CASE("iterators 1") { SECTION("basic behavior") { SECTION("uninitialized") { json::iterator it; CHECK(it.m_object == nullptr); json::const_iterator cit; CHECK(cit.m_object == nullptr); } SECTION("boolean") { json j = true; json j_const(j); SECTION("json + begin/end") { json::iterator it = j.begin(); CHECK(it != j.end()); CHECK(*it == j); it++; CHECK(it != j.begin()); CHECK(it == j.end()); it--; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); ++it; CHECK(it != j.begin()); CHECK(it == j.end()); --it; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); } SECTION("const json + begin/end") { json::const_iterator it = j_const.begin(); CHECK(it != j_const.end()); CHECK(*it == j_const); it++; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); it--; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); ++it; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); --it; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); } SECTION("json + cbegin/cend") { json::const_iterator it = j.cbegin(); CHECK(it != j.cend()); CHECK(*it == j); it++; CHECK(it != j.cbegin()); CHECK(it == j.cend()); it--; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); ++it; CHECK(it != j.cbegin()); CHECK(it == j.cend()); --it; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); } SECTION("const json + cbegin/cend") { json::const_iterator it = j_const.cbegin(); CHECK(it != j_const.cend()); CHECK(*it == j_const); it++; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); it--; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); --it; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); } SECTION("json + rbegin/rend") { json::reverse_iterator it = j.rbegin(); CHECK(it != j.rend()); CHECK(*it == j); it++; CHECK(it != j.rbegin()); CHECK(it == j.rend()); it--; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); ++it; CHECK(it != j.rbegin()); CHECK(it == j.rend()); --it; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it = j.crbegin(); CHECK(it != j.crend()); CHECK(*it == j); it++; CHECK(it != j.crbegin()); CHECK(it == j.crend()); it--; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); ++it; CHECK(it != j.crbegin()); CHECK(it == j.crend()); --it; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it = j_const.crbegin(); CHECK(it != j_const.crend()); CHECK(*it == j_const); it++; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); it--; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); --it; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); } SECTION("additional tests") { SECTION("!(begin != begin)") { CHECK(!(j.begin() != j.begin())); } SECTION("!(end != end)") { CHECK(!(j.end() != j.end())); } SECTION("begin < end") { CHECK(j.begin() < j.end()); } SECTION("begin <= end") { CHECK(j.begin() <= j.end()); } SECTION("end > begin") { CHECK(j.end() > j.begin()); } SECTION("end >= begin") { CHECK(j.end() >= j.begin()); } SECTION("end == end") { CHECK(j.end() == j.end()); } SECTION("end <= end") { CHECK(j.end() <= j.end()); } SECTION("begin == begin") { CHECK(j.begin() == j.begin()); } SECTION("begin <= begin") { CHECK(j.begin() <= j.begin()); } SECTION("begin >= begin") { CHECK(j.begin() >= j.begin()); } SECTION("!(begin == end)") { CHECK(!(j.begin() == j.end())); } SECTION("begin != end") { CHECK(j.begin() != j.end()); } SECTION("begin+1 == end") { CHECK(j.begin() + 1 == j.end()); } SECTION("begin == end-1") { CHECK(j.begin() == j.end() - 1); } SECTION("begin != end+1") { CHECK(j.begin() != j.end() + 1); } SECTION("end != end+1") { CHECK(j.end() != j.end() + 1); } SECTION("begin+1 != begin+2") { CHECK(j.begin() + 1 != j.begin() + 2); } SECTION("begin+1 < begin+2") { CHECK(j.begin() + 1 < j.begin() + 2); } SECTION("begin+1 <= begin+2") { CHECK(j.begin() + 1 <= j.begin() + 2); } SECTION("end+1 != end+2") { CHECK(j.end() + 1 != j.end() + 2); } } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(it.value() == json(true)); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(cit.value() == json(true)); auto rit = j.rend(); auto crit = j.crend(); CHECK_THROWS_WITH_AS(rit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(rit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } SECTION("string") { json j = "hello world"; json j_const(j); SECTION("json + begin/end") { json::iterator it = j.begin(); CHECK(it != j.end()); CHECK(*it == j); it++; CHECK(it != j.begin()); CHECK(it == j.end()); it--; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); ++it; CHECK(it != j.begin()); CHECK(it == j.end()); --it; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); } SECTION("const json + begin/end") { json::const_iterator it = j_const.begin(); CHECK(it != j_const.end()); CHECK(*it == j_const); it++; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); it--; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); ++it; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); --it; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); } SECTION("json + cbegin/cend") { json::const_iterator it = j.cbegin(); CHECK(it != j.cend()); CHECK(*it == j); it++; CHECK(it != j.cbegin()); CHECK(it == j.cend()); it--; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); ++it; CHECK(it != j.cbegin()); CHECK(it == j.cend()); --it; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); } SECTION("const json + cbegin/cend") { json::const_iterator it = j_const.cbegin(); CHECK(it != j_const.cend()); CHECK(*it == j_const); it++; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); it--; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); --it; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); } SECTION("json + rbegin/rend") { json::reverse_iterator it = j.rbegin(); CHECK(it != j.rend()); CHECK(*it == j); it++; CHECK(it != j.rbegin()); CHECK(it == j.rend()); it--; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); ++it; CHECK(it != j.rbegin()); CHECK(it == j.rend()); --it; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it = j.crbegin(); CHECK(it != j.crend()); CHECK(*it == j); it++; CHECK(it != j.crbegin()); CHECK(it == j.crend()); it--; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); ++it; CHECK(it != j.crbegin()); CHECK(it == j.crend()); --it; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it = j_const.crbegin(); CHECK(it != j_const.crend()); CHECK(*it == j_const); it++; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); it--; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); --it; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(it.value() == json("hello world")); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(cit.value() == json("hello world")); auto rit = j.rend(); auto crit = j.crend(); CHECK_THROWS_WITH_AS(rit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(rit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } SECTION("array") { json j = {1, 2, 3}; json j_const(j); SECTION("json + begin/end") { json::iterator it_begin = j.begin(); json::iterator it_end = j.end(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j[0]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[2]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("const json + begin/end") { json::const_iterator it_begin = j_const.begin(); json::const_iterator it_end = j_const.end(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j_const[0]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j_const[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j_const[2]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("json + cbegin/cend") { json::const_iterator it_begin = j.cbegin(); json::const_iterator it_end = j.cend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j[0]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[2]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("const json + cbegin/cend") { json::const_iterator it_begin = j_const.cbegin(); json::const_iterator it_end = j_const.cend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j[0]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[2]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("json + rbegin/rend") { json::reverse_iterator it_begin = j.rbegin(); json::reverse_iterator it_end = j.rend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j[2]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[0]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it_begin = j.crbegin(); json::const_reverse_iterator it_end = j.crend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j[2]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[0]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it_begin = j_const.crbegin(); json::const_reverse_iterator it_end = j_const.crend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j[2]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[1]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j[0]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(it.value() == json(1)); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(cit.value() == json(1)); } } SECTION("object") { json j = {{"A", 1}, {"B", 2}, {"C", 3}}; json j_const(j); SECTION("json + begin/end") { json::iterator it_begin = j.begin(); json::iterator it_end = j.end(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j["A"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["C"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("const json + begin/end") { json::const_iterator it_begin = j_const.begin(); json::const_iterator it_end = j_const.end(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j_const["A"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j_const["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j_const["C"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("json + cbegin/cend") { json::const_iterator it_begin = j.cbegin(); json::const_iterator it_end = j.cend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j["A"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["C"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("const json + cbegin/cend") { json::const_iterator it_begin = j_const.cbegin(); json::const_iterator it_end = j_const.cend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j_const["A"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j_const["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j_const["C"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("json + rbegin/rend") { json::reverse_iterator it_begin = j.rbegin(); json::reverse_iterator it_end = j.rend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j["C"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["A"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it_begin = j.crbegin(); json::const_reverse_iterator it_end = j.crend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j["C"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["A"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it_begin = j_const.crbegin(); json::const_reverse_iterator it_end = j_const.crend(); auto it = it_begin; CHECK(it != it_end); CHECK(*it == j["C"]); it++; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["B"]); ++it; CHECK(it != it_begin); CHECK(it != it_end); CHECK(*it == j["A"]); ++it; CHECK(it != it_begin); CHECK(it == it_end); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK(it.key() == "A"); CHECK(it.value() == json(1)); CHECK(cit.key() == "A"); CHECK(cit.value() == json(1)); } } SECTION("number (integer)") { json j = 23; json j_const(j); SECTION("json + begin/end") { json::iterator it = j.begin(); CHECK(it != j.end()); CHECK(*it == j); it++; CHECK(it != j.begin()); CHECK(it == j.end()); it--; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); ++it; CHECK(it != j.begin()); CHECK(it == j.end()); --it; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); } SECTION("const json + begin/end") { json::const_iterator it = j_const.begin(); CHECK(it != j_const.end()); CHECK(*it == j_const); it++; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); it--; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); ++it; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); --it; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); } SECTION("json + cbegin/cend") { json::const_iterator it = j.cbegin(); CHECK(it != j.cend()); CHECK(*it == j); it++; CHECK(it != j.cbegin()); CHECK(it == j.cend()); it--; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); ++it; CHECK(it != j.cbegin()); CHECK(it == j.cend()); --it; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); } SECTION("const json + cbegin/cend") { json::const_iterator it = j_const.cbegin(); CHECK(it != j_const.cend()); CHECK(*it == j_const); it++; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); it--; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); --it; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); } SECTION("json + rbegin/rend") { json::reverse_iterator it = j.rbegin(); CHECK(it != j.rend()); CHECK(*it == j); it++; CHECK(it != j.rbegin()); CHECK(it == j.rend()); it--; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); ++it; CHECK(it != j.rbegin()); CHECK(it == j.rend()); --it; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it = j.crbegin(); CHECK(it != j.crend()); CHECK(*it == j); it++; CHECK(it != j.crbegin()); CHECK(it == j.crend()); it--; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); ++it; CHECK(it != j.crbegin()); CHECK(it == j.crend()); --it; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it = j_const.crbegin(); CHECK(it != j_const.crend()); CHECK(*it == j_const); it++; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); it--; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); --it; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(it.value() == json(23)); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(cit.value() == json(23)); auto rit = j.rend(); auto crit = j.crend(); CHECK_THROWS_WITH_AS(rit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(rit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } SECTION("number (unsigned)") { json j = 23u; json j_const(j); SECTION("json + begin/end") { json::iterator it = j.begin(); CHECK(it != j.end()); CHECK(*it == j); it++; CHECK(it != j.begin()); CHECK(it == j.end()); it--; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); ++it; CHECK(it != j.begin()); CHECK(it == j.end()); --it; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); } SECTION("const json + begin/end") { json::const_iterator it = j_const.begin(); CHECK(it != j_const.end()); CHECK(*it == j_const); it++; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); it--; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); ++it; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); --it; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); } SECTION("json + cbegin/cend") { json::const_iterator it = j.cbegin(); CHECK(it != j.cend()); CHECK(*it == j); it++; CHECK(it != j.cbegin()); CHECK(it == j.cend()); it--; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); ++it; CHECK(it != j.cbegin()); CHECK(it == j.cend()); --it; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); } SECTION("const json + cbegin/cend") { json::const_iterator it = j_const.cbegin(); CHECK(it != j_const.cend()); CHECK(*it == j_const); it++; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); it--; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); --it; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); } SECTION("json + rbegin/rend") { json::reverse_iterator it = j.rbegin(); CHECK(it != j.rend()); CHECK(*it == j); it++; CHECK(it != j.rbegin()); CHECK(it == j.rend()); it--; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); ++it; CHECK(it != j.rbegin()); CHECK(it == j.rend()); --it; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it = j.crbegin(); CHECK(it != j.crend()); CHECK(*it == j); it++; CHECK(it != j.crbegin()); CHECK(it == j.crend()); it--; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); ++it; CHECK(it != j.crbegin()); CHECK(it == j.crend()); --it; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it = j_const.crbegin(); CHECK(it != j_const.crend()); CHECK(*it == j_const); it++; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); it--; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); --it; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(it.value() == json(23)); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(cit.value() == json(23)); auto rit = j.rend(); auto crit = j.crend(); CHECK_THROWS_WITH_AS(rit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(rit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } SECTION("number (float)") { json j = 23.42; json j_const(j); SECTION("json + begin/end") { json::iterator it = j.begin(); CHECK(it != j.end()); CHECK(*it == j); it++; CHECK(it != j.begin()); CHECK(it == j.end()); it--; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); ++it; CHECK(it != j.begin()); CHECK(it == j.end()); --it; CHECK(it == j.begin()); CHECK(it != j.end()); CHECK(*it == j); } SECTION("const json + begin/end") { json::const_iterator it = j_const.begin(); CHECK(it != j_const.end()); CHECK(*it == j_const); it++; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); it--; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); ++it; CHECK(it != j_const.begin()); CHECK(it == j_const.end()); --it; CHECK(it == j_const.begin()); CHECK(it != j_const.end()); CHECK(*it == j_const); } SECTION("json + cbegin/cend") { json::const_iterator it = j.cbegin(); CHECK(it != j.cend()); CHECK(*it == j); it++; CHECK(it != j.cbegin()); CHECK(it == j.cend()); it--; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); ++it; CHECK(it != j.cbegin()); CHECK(it == j.cend()); --it; CHECK(it == j.cbegin()); CHECK(it != j.cend()); CHECK(*it == j); } SECTION("const json + cbegin/cend") { json::const_iterator it = j_const.cbegin(); CHECK(it != j_const.cend()); CHECK(*it == j_const); it++; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); it--; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.cbegin()); CHECK(it == j_const.cend()); --it; CHECK(it == j_const.cbegin()); CHECK(it != j_const.cend()); CHECK(*it == j_const); } SECTION("json + rbegin/rend") { json::reverse_iterator it = j.rbegin(); CHECK(it != j.rend()); CHECK(*it == j); it++; CHECK(it != j.rbegin()); CHECK(it == j.rend()); it--; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); ++it; CHECK(it != j.rbegin()); CHECK(it == j.rend()); --it; CHECK(it == j.rbegin()); CHECK(it != j.rend()); CHECK(*it == j); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it = j.crbegin(); CHECK(it != j.crend()); CHECK(*it == j); it++; CHECK(it != j.crbegin()); CHECK(it == j.crend()); it--; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); ++it; CHECK(it != j.crbegin()); CHECK(it == j.crend()); --it; CHECK(it == j.crbegin()); CHECK(it != j.crend()); CHECK(*it == j); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it = j_const.crbegin(); CHECK(it != j_const.crend()); CHECK(*it == j_const); it++; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); it--; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); ++it; CHECK(it != j_const.crbegin()); CHECK(it == j_const.crend()); --it; CHECK(it == j_const.crbegin()); CHECK(it != j_const.crend()); CHECK(*it == j_const); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(it.value() == json(23.42)); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK(cit.value() == json(23.42)); auto rit = j.rend(); auto crit = j.crend(); CHECK_THROWS_WITH_AS(rit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(rit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } SECTION("null") { json j = nullptr; json j_const(j); SECTION("json + begin/end") { json::iterator it = j.begin(); CHECK(it == j.end()); } SECTION("const json + begin/end") { json::const_iterator it_begin = j_const.begin(); json::const_iterator it_end = j_const.end(); CHECK(it_begin == it_end); } SECTION("json + cbegin/cend") { json::const_iterator it_begin = j.cbegin(); json::const_iterator it_end = j.cend(); CHECK(it_begin == it_end); } SECTION("const json + cbegin/cend") { json::const_iterator it_begin = j_const.cbegin(); json::const_iterator it_end = j_const.cend(); CHECK(it_begin == it_end); } SECTION("json + rbegin/rend") { json::reverse_iterator it = j.rbegin(); CHECK(it == j.rend()); } SECTION("json + crbegin/crend") { json::const_reverse_iterator it = j.crbegin(); CHECK(it == j.crend()); } SECTION("const json + crbegin/crend") { json::const_reverse_iterator it = j_const.crbegin(); CHECK(it == j_const.crend()); } SECTION("key/value") { auto it = j.begin(); auto cit = j_const.cbegin(); CHECK_THROWS_WITH_AS(it.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(it.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(cit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(cit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); auto rit = j.rend(); auto crit = j.crend(); CHECK_THROWS_WITH_AS(rit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(rit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.key(), "[json.exception.invalid_iterator.207] cannot use key() for non-object iterators", json::invalid_iterator&); CHECK_THROWS_WITH_AS(crit.value(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } } SECTION("conversion from iterator to const iterator") { SECTION("boolean") { json j = true; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("string") { json j = "hello world"; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("array") { json j = {1, 2, 3}; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("object") { json j = {{"A", 1}, {"B", 2}, {"C", 3}}; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("number (integer)") { json j = 23; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("number (unsigned)") { json j = 23u; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("number (float)") { json j = 23.42; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } SECTION("null") { json j = nullptr; json::const_iterator it = j.begin(); CHECK(it == j.cbegin()); it = j.begin(); CHECK(it == j.cbegin()); } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-regression2.cpp
.cpp
29,577
942
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT // cmake/test.cmake selects the C++ standard versions with which to build a // unit test based on the presence of JSON_HAS_CPP_<VERSION> macros. // When using macros that are only defined for particular versions of the standard // (e.g., JSON_HAS_FILESYSTEM for C++17 and up), please mention the corresponding // version macro in a comment close by, like this: // JSON_HAS_CPP_<VERSION> (do not remove; see note at top of file) #include "doctest_compatibility.h" // for some reason including this after the json header leads to linker errors with VS 2017... #include <locale> #define JSON_TESTS_PRIVATE #include <nlohmann/json.hpp> using json = nlohmann::json; using ordered_json = nlohmann::ordered_json; #ifdef JSON_TEST_NO_GLOBAL_UDLS using namespace nlohmann::literals; // NOLINT(google-build-using-namespace) #endif #include <cstdio> #include <list> #include <type_traits> #include <utility> #ifdef JSON_HAS_CPP_17 #include <any> #include <variant> #endif #ifdef JSON_HAS_CPP_20 #if __has_include(<span>) #include <span> #endif #endif // NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") ///////////////////////////////////////////////////////////////////// // for #1021 ///////////////////////////////////////////////////////////////////// using float_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, float>; ///////////////////////////////////////////////////////////////////// // for #1647 ///////////////////////////////////////////////////////////////////// namespace { struct NonDefaultFromJsonStruct {}; inline bool operator==(NonDefaultFromJsonStruct const& /*unused*/, NonDefaultFromJsonStruct const& /*unused*/) { return true; } enum class for_1647 { one, two }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays): this is a false positive NLOHMANN_JSON_SERIALIZE_ENUM(for_1647, { {for_1647::one, "one"}, {for_1647::two, "two"}, }) } // namespace ///////////////////////////////////////////////////////////////////// // for #1299 ///////////////////////////////////////////////////////////////////// struct Data { Data() = default; Data(std::string a_, std::string b_) : a(std::move(a_)) , b(std::move(b_)) {} std::string a{}; std::string b{}; }; void from_json(const json& j, Data& data); void from_json(const json& j, Data& data) { j["a"].get_to(data.a); j["b"].get_to(data.b); } bool operator==(Data const& lhs, Data const& rhs); bool operator==(Data const& lhs, Data const& rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; } //bool operator!=(Data const& lhs, Data const& rhs) //{ // return !(lhs == rhs); //} namespace nlohmann { template<> struct adl_serializer<NonDefaultFromJsonStruct> { static NonDefaultFromJsonStruct from_json(json const& /*unused*/) noexcept { return {}; } }; } // namespace nlohmann ///////////////////////////////////////////////////////////////////// // for #1805 ///////////////////////////////////////////////////////////////////// struct NotSerializableData { int mydata; float myfloat; }; ///////////////////////////////////////////////////////////////////// // for #2574 ///////////////////////////////////////////////////////////////////// struct NonDefaultConstructible { explicit NonDefaultConstructible(int a) : x(a) {} int x; }; namespace nlohmann { template<> struct adl_serializer<NonDefaultConstructible> { static NonDefaultConstructible from_json(json const& j) { return NonDefaultConstructible(j.get<int>()); } }; } // namespace nlohmann ///////////////////////////////////////////////////////////////////// // for #2824 ///////////////////////////////////////////////////////////////////// class sax_no_exception : public nlohmann::detail::json_sax_dom_parser<json> { public: explicit sax_no_exception(json& j) : nlohmann::detail::json_sax_dom_parser<json>(j, false) {} static bool parse_error(std::size_t /*position*/, const std::string& /*last_token*/, const json::exception& ex) { error_string = new std::string(ex.what()); // NOLINT(cppcoreguidelines-owning-memory) return false; } static std::string* error_string; }; std::string* sax_no_exception::error_string = nullptr; ///////////////////////////////////////////////////////////////////// // for #2982 ///////////////////////////////////////////////////////////////////// template<class T> class my_allocator : public std::allocator<T> { public: using std::allocator<T>::allocator; my_allocator() = default; template<class U> my_allocator(const my_allocator<U>& /*unused*/) { } template <class U> struct rebind { using other = my_allocator<U>; }; }; ///////////////////////////////////////////////////////////////////// // for #3077 ///////////////////////////////////////////////////////////////////// class FooAlloc {}; class Foo { public: explicit Foo(const FooAlloc& /* unused */ = FooAlloc()) {} bool value = false; }; class FooBar { public: Foo foo{}; }; inline void from_json(const nlohmann::json& j, FooBar& fb) { j.at("value").get_to(fb.foo.value); } ///////////////////////////////////////////////////////////////////// // for #3171 ///////////////////////////////////////////////////////////////////// struct for_3171_base // NOLINT(cppcoreguidelines-special-member-functions) { for_3171_base(const std::string& /*unused*/ = {}) {} virtual ~for_3171_base() = default; virtual void _from_json(const json& j) { j.at("str").get_to(str); } std::string str{}; }; struct for_3171_derived : public for_3171_base { for_3171_derived() = default; explicit for_3171_derived(const std::string& /*unused*/) { } }; inline void from_json(const json& j, for_3171_base& tb) { tb._from_json(j); } ///////////////////////////////////////////////////////////////////// // for #3312 ///////////////////////////////////////////////////////////////////// #ifdef JSON_HAS_CPP_20 struct for_3312 { std::string name; }; inline void from_json(const json& j, for_3312& obj) { j.at("name").get_to(obj.name); } #endif ///////////////////////////////////////////////////////////////////// // for #3204 ///////////////////////////////////////////////////////////////////// struct for_3204_foo { for_3204_foo() = default; explicit for_3204_foo(std::string /*unused*/) {} // NOLINT(performance-unnecessary-value-param) }; struct for_3204_bar { enum constructed_from_t { constructed_from_none = 0, constructed_from_foo = 1, constructed_from_json = 2 }; explicit for_3204_bar(std::function<void(for_3204_foo)> /*unused*/) noexcept // NOLINT(performance-unnecessary-value-param) : constructed_from(constructed_from_foo) {} explicit for_3204_bar(std::function<void(json)> /*unused*/) noexcept // NOLINT(performance-unnecessary-value-param) : constructed_from(constructed_from_json) {} constructed_from_t constructed_from = constructed_from_none; }; ///////////////////////////////////////////////////////////////////// // for #3333 ///////////////////////////////////////////////////////////////////// struct for_3333 final { for_3333(int x_ = 0, int y_ = 0) : x(x_), y(y_) {} template <class T> for_3333(const T& /*unused*/) { CHECK(false); } int x = 0; int y = 0; }; template <> inline for_3333::for_3333(const json& j) : for_3333(j.value("x", 0), j.value("y", 0)) {} TEST_CASE("regression tests 2") { SECTION("issue #1001 - Fix memory leak during parser callback") { const auto* geojsonExample = R"( { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} }, { "type": "Feature", "geometry": { "type": "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ] }, "properties": { "prop0": "value0", "prop1": 0.0 } }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }, "properties": { "prop0": "value0", "prop1": {"this": "that"} } } ] })"; const json::parser_callback_t cb = [&](int /*level*/, json::parse_event_t event, json & parsed) noexcept { // skip uninteresting events if (event == json::parse_event_t::value && !parsed.is_primitive()) { return false; } switch (event) { case json::parse_event_t::key: { return true; } case json::parse_event_t::value: { return false; } case json::parse_event_t::object_start: { return true; } case json::parse_event_t::object_end: { return false; } case json::parse_event_t::array_start: { return true; } case json::parse_event_t::array_end: { return false; } default: { return true; } } }; auto j = json::parse(geojsonExample, cb, true); CHECK(j == json()); } SECTION("issue #1021 - to/from_msgpack only works with standard typization") { float_json j = 1000.0; CHECK(float_json::from_cbor(float_json::to_cbor(j)) == j); CHECK(float_json::from_msgpack(float_json::to_msgpack(j)) == j); CHECK(float_json::from_ubjson(float_json::to_ubjson(j)) == j); float_json j2 = {1000.0, 2000.0, 3000.0}; CHECK(float_json::from_ubjson(float_json::to_ubjson(j2, true, true)) == j2); } SECTION("issue #1045 - Using STL algorithms with JSON containers with expected results?") { json diffs = nlohmann::json::array(); json m1{{"key1", 42}}; json m2{{"key2", 42}}; auto p1 = m1.items(); auto p2 = m2.items(); using it_type = decltype(p1.begin()); std::set_difference( p1.begin(), p1.end(), p2.begin(), p2.end(), std::inserter(diffs, diffs.end()), [&](const it_type & e1, const it_type & e2) -> bool { using comper_pair = std::pair<std::string, decltype(e1.value())>; // Trying to avoid unneeded copy return comper_pair(e1.key(), e1.value()) < comper_pair(e2.key(), e2.value()); // Using pair comper }); CHECK(diffs.size() == 1); // Note the change here, was 2 } #ifdef JSON_HAS_CPP_17 SECTION("issue #1292 - Serializing std::variant causes stack overflow") { static_assert(!std::is_constructible<json, std::variant<int, float>>::value, "unexpected value"); } #endif SECTION("issue #1299 - compile error in from_json converting to container " "with std::pair") { const json j = { {"1", {{"a", "testa_1"}, {"b", "testb_1"}}}, {"2", {{"a", "testa_2"}, {"b", "testb_2"}}}, {"3", {{"a", "testa_3"}, {"b", "testb_3"}}}, }; std::map<std::string, Data> expected { {"1", {"testa_1", "testb_1"}}, {"2", {"testa_2", "testb_2"}}, {"3", {"testa_3", "testb_3"}}, }; const auto data = j.get<decltype(expected)>(); CHECK(expected == data); } SECTION("issue #1445 - buffer overflow in dumping invalid utf-8 strings") { SECTION("a bunch of -1, ensure_ascii=true") { const auto length = 300; json dump_test; dump_test["1"] = std::string(length, -1); std::string expected = R"({"1":")"; for (int i = 0; i < length; ++i) { expected += "\\ufffd"; } expected += "\"}"; auto s = dump_test.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace); CHECK(s == expected); } SECTION("a bunch of -2, ensure_ascii=false") { const auto length = 500; json dump_test; dump_test["1"] = std::string(length, -2); std::string expected = R"({"1":")"; for (int i = 0; i < length; ++i) { expected += "\xEF\xBF\xBD"; } expected += "\"}"; auto s = dump_test.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); CHECK(s == expected); } SECTION("test case in issue #1445") { nlohmann::json dump_test; const std::array<int, 108> data = { {109, 108, 103, 125, -122, -53, 115, 18, 3, 0, 102, 19, 1, 15, -110, 13, -3, -1, -81, 32, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -80, 2, 0, 0, 96, -118, 46, -116, 46, 109, -84, -87, 108, 14, 109, -24, -83, 13, -18, -51, -83, -52, -115, 14, 6, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 3, 0, 0, 0, 35, -74, -73, 55, 57, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, 0, -96, -54, -28, -26} }; std::string s; for (const int i : data) { s += static_cast<char>(i); } dump_test["1"] = s; dump_test.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace); } } SECTION("issue #1447 - Integer Overflow (OSS-Fuzz 12506)") { const json j = json::parse("[-9223372036854775808]"); CHECK(j.dump() == "[-9223372036854775808]"); } SECTION("issue #1708 - minimum value of int64_t can be outputted") { constexpr auto smallest = (std::numeric_limits<int64_t>::min)(); const json j = smallest; CHECK(j.dump() == std::to_string(smallest)); } SECTION("issue #1727 - Contains with non-const lvalue json_pointer picks the wrong overload") { const json j = {{"root", {{"settings", {{"logging", true}}}}}}; auto jptr1 = "/root/settings/logging"_json_pointer; auto jptr2 = json::json_pointer{"/root/settings/logging"}; CHECK(j.contains(jptr1)); CHECK(j.contains(jptr2)); } SECTION("issue #1647 - compile error when deserializing enum if both non-default from_json and non-member operator== exists for other type") { // does not compile on ICPC when targeting C++20 #if !(defined(__INTEL_COMPILER) && __cplusplus >= 202000) { const json j; NonDefaultFromJsonStruct x(j); NonDefaultFromJsonStruct y; CHECK(x == y); } #endif auto val = nlohmann::json("one").get<for_1647>(); CHECK(val == for_1647::one); const json j = val; } SECTION("issue #1715 - json::from_cbor does not respect allow_exceptions = false when input is string literal") { SECTION("string literal") { const json cbor = json::from_cbor("B", true, false); CHECK(cbor.is_discarded()); } SECTION("string array") { const std::array<char, 2> input = {{'B', 0x00}}; const json cbor = json::from_cbor(input, true, false); CHECK(cbor.is_discarded()); } SECTION("std::string") { const json cbor = json::from_cbor(std::string("B"), true, false); CHECK(cbor.is_discarded()); } } SECTION("issue #1805 - A pair<T1, T2> is json constructible only if T1 and T2 are json constructible") { static_assert(!std::is_constructible<json, std::pair<std::string, NotSerializableData>>::value, "unexpected result"); static_assert(!std::is_constructible<json, std::pair<NotSerializableData, std::string>>::value, "unexpected result"); static_assert(std::is_constructible<json, std::pair<int, std::string>>::value, "unexpected result"); } SECTION("issue #1825 - A tuple<Args..> is json constructible only if all T in Args are json constructible") { static_assert(!std::is_constructible<json, std::tuple<std::string, NotSerializableData>>::value, "unexpected result"); static_assert(!std::is_constructible<json, std::tuple<NotSerializableData, std::string>>::value, "unexpected result"); static_assert(std::is_constructible<json, std::tuple<int, std::string>>::value, "unexpected result"); } SECTION("issue #1983 - JSON patch diff for op=add formation is not as per standard (RFC 6902)") { const auto source = R"({ "foo": [ "1", "2" ] })"_json; const auto target = R"({"foo": [ "1", "2", "3" ]})"_json; const auto result = json::diff(source, target); CHECK(result.dump() == R"([{"op":"add","path":"/foo/-","value":"3"}])"); } SECTION("issue #2067 - cannot serialize binary data to text JSON") { const std::array<unsigned char, 23> data = {{0x81, 0xA4, 0x64, 0x61, 0x74, 0x61, 0xC4, 0x0F, 0x33, 0x30, 0x30, 0x32, 0x33, 0x34, 0x30, 0x31, 0x30, 0x37, 0x30, 0x35, 0x30, 0x31, 0x30}}; const json j = json::from_msgpack(data.data(), data.size()); CHECK_NOTHROW( j.dump(4, // Indent ' ', // Indent char false, // Ensure ascii json::error_handler_t::strict // Error )); } SECTION("PR #2181 - regression bug with lvalue") { // see https://github.com/nlohmann/json/pull/2181#issuecomment-653326060 const json j{{"x", "test"}}; const std::string defval = "default value"; auto val = j.value("x", defval); auto val2 = j.value("y", defval); } SECTION("issue #2293 - eof doesn't cause parsing to stop") { const std::vector<uint8_t> data = { 0x7B, 0x6F, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x20, 0x4F, 0x42 }; const json result = json::from_cbor(data, true, false); CHECK(result.is_discarded()); } SECTION("issue #2315 - json.update and vector<pair>does not work with ordered_json") { nlohmann::ordered_json jsonAnimals = {{"animal", "dog"}}; const nlohmann::ordered_json jsonCat = {{"animal", "cat"}}; jsonAnimals.update(jsonCat); CHECK(jsonAnimals["animal"] == "cat"); auto jsonAnimals_parsed = nlohmann::ordered_json::parse(jsonAnimals.dump()); CHECK(jsonAnimals == jsonAnimals_parsed); const std::vector<std::pair<std::string, int64_t>> intData = {std::make_pair("aaaa", 11), std::make_pair("bbb", 222) }; nlohmann::ordered_json jsonObj; for (const auto& data : intData) { jsonObj[data.first] = data.second; } CHECK(jsonObj["aaaa"] == 11); CHECK(jsonObj["bbb"] == 222); } SECTION("issue #2330 - ignore_comment=true fails on multiple consecutive lines starting with comments") { const std::string ss = "//\n//\n{\n}\n"; const json j = json::parse(ss, nullptr, true, true); CHECK(j.dump() == "{}"); } #ifdef JSON_HAS_CPP_20 #if __has_include(<span>) SECTION("issue #2546 - parsing containers of std::byte") { const char DATA[] = R"("Hello, world!")"; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) const auto s = std::as_bytes(std::span(DATA)); const json j = json::parse(s); CHECK(j.dump() == "\"Hello, world!\""); } #endif #endif SECTION("issue #2574 - Deserialization to std::array, std::pair, and std::tuple with non-default constructable types fails") { SECTION("std::array") { { const json j = {7, 4}; auto arr = j.get<std::array<NonDefaultConstructible, 2>>(); CHECK(arr[0].x == 7); CHECK(arr[1].x == 4); } { const json j = 7; CHECK_THROWS_AS((j.get<std::array<NonDefaultConstructible, 1>>()), json::type_error); } } SECTION("std::pair") { { const json j = {3, 8}; auto p = j.get<std::pair<NonDefaultConstructible, NonDefaultConstructible>>(); CHECK(p.first.x == 3); CHECK(p.second.x == 8); } { const json j = {4, 1}; auto p = j.get<std::pair<int, NonDefaultConstructible>>(); CHECK(p.first == 4); CHECK(p.second.x == 1); } { const json j = {6, 7}; auto p = j.get<std::pair<NonDefaultConstructible, int>>(); CHECK(p.first.x == 6); CHECK(p.second == 7); } { const json j = 7; CHECK_THROWS_AS((j.get<std::pair<NonDefaultConstructible, int>>()), json::type_error); } } SECTION("std::tuple") { { const json j = {9}; auto t = j.get<std::tuple<NonDefaultConstructible>>(); CHECK(std::get<0>(t).x == 9); } { const json j = {9, 8, 7}; auto t = j.get<std::tuple<NonDefaultConstructible, int, NonDefaultConstructible>>(); CHECK(std::get<0>(t).x == 9); CHECK(std::get<1>(t) == 8); CHECK(std::get<2>(t).x == 7); } { const json j = 7; CHECK_THROWS_AS((j.get<std::tuple<NonDefaultConstructible>>()), json::type_error); } } } SECTION("issue #2865 - ASAN detects memory leaks") { // the code below is expected to not leak memory { nlohmann::json o; const std::string s = "bar"; nlohmann::to_json(o["foo"], s); nlohmann::json p = o; // call to_json with a non-null JSON value nlohmann::to_json(p["foo"], s); } { nlohmann::json o; const std::string s = "bar"; nlohmann::to_json(o["foo"], s); // call to_json with a non-null JSON value nlohmann::to_json(o["foo"], s); } } SECTION("issue #2824 - encoding of json::exception::what()") { json j; sax_no_exception sax(j); CHECK(!json::sax_parse("xyz", &sax)); CHECK(*sax_no_exception::error_string == "[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - invalid literal; last read: 'x'"); delete sax_no_exception::error_string; // NOLINT(cppcoreguidelines-owning-memory) } SECTION("issue #2825 - Properly constrain the basic_json conversion operator") { static_assert(std::is_copy_assignable<nlohmann::ordered_json>::value, "ordered_json must be copy assignable"); } SECTION("issue #2958 - Inserting in unordered json using a pointer retains the leading slash") { const std::string p = "/root"; json test1; test1[json::json_pointer(p)] = json::object(); CHECK(test1.dump() == "{\"root\":{}}"); ordered_json test2; test2[ordered_json::json_pointer(p)] = json::object(); CHECK(test2.dump() == "{\"root\":{}}"); // json::json_pointer and ordered_json::json_pointer are the same type; behave as above ordered_json test3; test3[json::json_pointer(p)] = json::object(); CHECK(std::is_same<json::json_pointer::string_t, ordered_json::json_pointer::string_t>::value); CHECK(test3.dump() == "{\"root\":{}}"); } SECTION("issue #2982 - to_{binary format} does not provide a mechanism for specifying a custom allocator for the returned type") { std::vector<std::uint8_t, my_allocator<std::uint8_t>> my_vector; json j = {1, 2, 3, 4}; json::to_cbor(j, my_vector); json k = json::from_cbor(my_vector); CHECK(j == k); } #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM // JSON_HAS_CPP_17 (do not remove; see note at top of file) SECTION("issue #3070 - Version 3.10.3 breaks backward-compatibility with 3.10.2 ") { nlohmann::detail::std_fs::path text_path("/tmp/text.txt"); const json j(text_path); const auto j_path = j.get<nlohmann::detail::std_fs::path>(); CHECK(j_path == text_path); #if DOCTEST_CLANG || DOCTEST_GCC >= DOCTEST_COMPILER(8, 4, 0) // only known to work on Clang and GCC >=8.4 CHECK_THROWS_WITH_AS(nlohmann::detail::std_fs::path(json(1)), "[json.exception.type_error.302] type must be string, but is number", json::type_error); #endif } #endif SECTION("issue #3077 - explicit constructor with default does not compile") { json j; j[0]["value"] = true; std::vector<FooBar> foo; j.get_to(foo); } SECTION("issue #3108 - ordered_json doesn't support range based erase") { ordered_json j = {1, 2, 2, 4}; auto last = std::unique(j.begin(), j.end()); j.erase(last, j.end()); CHECK(j.dump() == "[1,2,4]"); j.erase(std::remove_if(j.begin(), j.end(), [](const ordered_json & val) { return val == 2; }), j.end()); CHECK(j.dump() == "[1,4]"); } SECTION("issue #3343 - json and ordered_json are not interchangable") { json::object_t jobj({ { "product", "one" } }); ordered_json::object_t ojobj({{"product", "one"}}); auto jit = jobj.begin(); auto ojit = ojobj.begin(); CHECK(jit->first == ojit->first); CHECK(jit->second.get<std::string>() == ojit->second.get<std::string>()); } SECTION("issue #3171 - if class is_constructible from std::string wrong from_json overload is being selected, compilation failed") { const json j{{ "str", "value"}}; // failed with: error: no match for ‘operator=’ (operand types are ‘for_3171_derived’ and ‘const nlohmann::basic_json<>::string_t’ // {aka ‘const std::__cxx11::basic_string<char>’}) // s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); auto td = j.get<for_3171_derived>(); CHECK(td.str == "value"); } #ifdef JSON_HAS_CPP_20 SECTION("issue #3312 - Parse to custom class from unordered_json breaks on G++11.2.0 with C++20") { // see test for #3171 const ordered_json j = {{"name", "class"}}; for_3312 obj{}; j.get_to(obj); CHECK(obj.name == "class"); } #endif #if defined(JSON_HAS_CPP_17) && JSON_USE_IMPLICIT_CONVERSIONS SECTION("issue #3428 - Error occurred when converting nlohmann::json to std::any") { const json j; const std::any a1 = j; std::any&& a2 = j; CHECK(a1.type() == typeid(j)); CHECK(a2.type() == typeid(j)); } #endif SECTION("issue #3204 - ambiguous regression") { for_3204_bar bar_from_foo([](for_3204_foo) noexcept {}); // NOLINT(performance-unnecessary-value-param) for_3204_bar bar_from_json([](json) noexcept {}); // NOLINT(performance-unnecessary-value-param) CHECK(bar_from_foo.constructed_from == for_3204_bar::constructed_from_foo); CHECK(bar_from_json.constructed_from == for_3204_bar::constructed_from_json); } SECTION("issue #3333 - Ambiguous conversion from nlohmann::basic_json<> to custom class") { const json j { {"x", 1}, {"y", 2} }; for_3333 p = j; CHECK(p.x == 1); CHECK(p.y == 2); } } DOCTEST_CLANG_SUPPRESS_WARNING_POP
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-class_iterator.cpp
.cpp
17,188
469
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #define JSON_TESTS_PRIVATE #include <nlohmann/json.hpp> using nlohmann::json; template<typename Iter> using can_post_increment_temporary = decltype((std::declval<Iter>()++)++); template<typename Iter> using can_post_decrement_temporary = decltype((std::declval<Iter>()--)--); TEST_CASE("iterator class") { SECTION("construction") { SECTION("constructor") { SECTION("null") { json j(json::value_t::null); json::iterator const it(&j); } SECTION("object") { json j(json::value_t::object); json::iterator const it(&j); } SECTION("array") { json j(json::value_t::array); json::iterator const it(&j); } } SECTION("copy assignment") { json j(json::value_t::null); json::iterator const it(&j); json::iterator it2(&j); it2 = it; } } SECTION("initialization") { SECTION("set_begin") { SECTION("null") { json j(json::value_t::null); json::iterator it(&j); it.set_begin(); CHECK((it == j.begin())); } SECTION("object") { json j(json::value_t::object); json::iterator it(&j); it.set_begin(); CHECK((it == j.begin())); } SECTION("array") { json j(json::value_t::array); json::iterator it(&j); it.set_begin(); CHECK((it == j.begin())); } } SECTION("set_end") { SECTION("null") { json j(json::value_t::null); json::iterator it(&j); it.set_end(); CHECK((it == j.end())); } SECTION("object") { json j(json::value_t::object); json::iterator it(&j); it.set_end(); CHECK((it == j.end())); } SECTION("array") { json j(json::value_t::array); json::iterator it(&j); it.set_end(); CHECK((it == j.end())); } } } SECTION("element access") { SECTION("operator*") { SECTION("null") { json j(json::value_t::null); json::iterator const it = j.begin(); CHECK_THROWS_WITH_AS(*it, "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("number") { json j(17); json::iterator it = j.begin(); CHECK(*it == json(17)); it = j.end(); CHECK_THROWS_WITH_AS(*it, "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("object") { json j({{"foo", "bar"}}); json::iterator const it = j.begin(); CHECK(*it == json("bar")); } SECTION("array") { json j({1, 2, 3, 4}); json::iterator const it = j.begin(); CHECK(*it == json(1)); } } SECTION("operator->") { SECTION("null") { json j(json::value_t::null); json::iterator const it = j.begin(); CHECK_THROWS_WITH_AS(std::string(it->type_name()), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("number") { json j(17); json::iterator it = j.begin(); CHECK(std::string(it->type_name()) == "number"); it = j.end(); CHECK_THROWS_WITH_AS(std::string(it->type_name()), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("object") { json j({{"foo", "bar"}}); json::iterator const it = j.begin(); CHECK(std::string(it->type_name()) == "string"); } SECTION("array") { json j({1, 2, 3, 4}); json::iterator const it = j.begin(); CHECK(std::string(it->type_name()) == "number"); } } } SECTION("increment/decrement") { SECTION("post-increment") { SECTION("null") { json j(json::value_t::null); json::iterator it = j.begin(); CHECK((it.m_it.primitive_iterator.m_it == 1)); it++; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("number") { json j(17); json::iterator it = j.begin(); CHECK((it.m_it.primitive_iterator.m_it == 0)); it++; CHECK((it.m_it.primitive_iterator.m_it == 1)); it++; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json j({{"foo", "bar"}}); json::iterator it = j.begin(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); it++; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); } SECTION("array") { json j({1, 2, 3, 4}); json::iterator it = j.begin(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); } } SECTION("pre-increment") { SECTION("null") { json j(json::value_t::null); json::iterator it = j.begin(); CHECK((it.m_it.primitive_iterator.m_it == 1)); ++it; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("number") { json j(17); json::iterator it = j.begin(); CHECK((it.m_it.primitive_iterator.m_it == 0)); ++it; CHECK((it.m_it.primitive_iterator.m_it == 1)); ++it; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json j({{"foo", "bar"}}); json::iterator it = j.begin(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); ++it; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); } SECTION("array") { json j({1, 2, 3, 4}); json::iterator it = j.begin(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); } } SECTION("post-decrement") { SECTION("null") { json j(json::value_t::null); json::iterator const it = j.end(); CHECK((it.m_it.primitive_iterator.m_it == 1)); } SECTION("number") { json j(17); json::iterator it = j.end(); CHECK((it.m_it.primitive_iterator.m_it == 1)); it--; CHECK((it.m_it.primitive_iterator.m_it == 0)); it--; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json j({{"foo", "bar"}}); json::iterator it = j.end(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); it--; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); } SECTION("array") { json j({1, 2, 3, 4}); json::iterator it = j.end(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); } } SECTION("pre-decrement") { SECTION("null") { json j(json::value_t::null); json::iterator const it = j.end(); CHECK((it.m_it.primitive_iterator.m_it == 1)); } SECTION("number") { json j(17); json::iterator it = j.end(); CHECK((it.m_it.primitive_iterator.m_it == 1)); --it; CHECK((it.m_it.primitive_iterator.m_it == 0)); --it; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json j({{"foo", "bar"}}); json::iterator it = j.end(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); --it; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); } SECTION("array") { json j({1, 2, 3, 4}); json::iterator it = j.end(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); } } } SECTION("equality-preserving") { SECTION("post-increment") { SECTION("primitive_iterator_t") { using Iter = nlohmann::detail::primitive_iterator_t; CHECK(std::is_same < decltype(std::declval<Iter&>()++), Iter >::value); } SECTION("iter_impl") { using Iter = nlohmann::detail::iter_impl<json>; CHECK(std::is_same < decltype(std::declval<Iter&>()++), Iter >::value); } SECTION("json_reverse_iterator") { using Base = nlohmann::detail::iter_impl<json>; using Iter = nlohmann::detail::json_reverse_iterator<Base>; CHECK(std::is_same < decltype(std::declval<Iter&>()++), Iter >::value); } } SECTION("post-decrement") { SECTION("primitive_iterator_t") { using Iter = nlohmann::detail::primitive_iterator_t; CHECK(std::is_same < decltype(std::declval<Iter&>()--), Iter >::value); } SECTION("iter_impl") { using Iter = nlohmann::detail::iter_impl<json>; CHECK(std::is_same < decltype(std::declval<Iter&>()--), Iter >::value ); } SECTION("json_reverse_iterator") { using Base = nlohmann::detail::iter_impl<json>; using Iter = nlohmann::detail::json_reverse_iterator<Base>; CHECK(std::is_same < decltype(std::declval<Iter&>()--), Iter >::value ); } } } // prevent "accidental mutation of a temporary object" SECTION("cert-dcl21-cpp") { using nlohmann::detail::is_detected; SECTION("post-increment") { SECTION("primitive_iterator_t") { using Iter = nlohmann::detail::primitive_iterator_t; CHECK_FALSE(is_detected<can_post_increment_temporary, Iter&>::value); } SECTION("iter_impl") { using Iter = nlohmann::detail::iter_impl<json>; CHECK_FALSE(is_detected<can_post_increment_temporary, Iter&>::value); } SECTION("json_reverse_iterator") { using Base = nlohmann::detail::iter_impl<json>; using Iter = nlohmann::detail::json_reverse_iterator<Base>; CHECK_FALSE(is_detected<can_post_increment_temporary, Iter&>::value); } } SECTION("post-decrement") { SECTION("primitive_iterator_t") { using Iter = nlohmann::detail::primitive_iterator_t; CHECK_FALSE(is_detected<can_post_decrement_temporary, Iter&>::value); } SECTION("iter_impl") { using Iter = nlohmann::detail::iter_impl<json>; CHECK_FALSE(is_detected<can_post_decrement_temporary, Iter&>::value); } SECTION("json_reverse_iterator") { using Base = nlohmann::detail::iter_impl<json>; using Iter = nlohmann::detail::json_reverse_iterator<Base>; CHECK_FALSE(is_detected<can_post_decrement_temporary, Iter&>::value); } } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-noexcept.cpp
.cpp
3,554
75
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" // disable -Wnoexcept due to struct pod_bis DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wnoexcept") #include <nlohmann/json.hpp> using nlohmann::json; namespace { enum test {}; struct pod {}; struct pod_bis {}; void to_json(json& /*unused*/, pod /*unused*/) noexcept; void to_json(json& /*unused*/, pod_bis /*unused*/); void from_json(const json& /*unused*/, pod /*unused*/) noexcept; void from_json(const json& /*unused*/, pod_bis /*unused*/); void to_json(json& /*unused*/, pod /*unused*/) noexcept {} void to_json(json& /*unused*/, pod_bis /*unused*/) {} void from_json(const json& /*unused*/, pod /*unused*/) noexcept {} void from_json(const json& /*unused*/, pod_bis /*unused*/) {} static_assert(noexcept(json{}), ""); static_assert(noexcept(nlohmann::to_json(std::declval<json&>(), 2)), ""); static_assert(noexcept(nlohmann::to_json(std::declval<json&>(), 2.5)), ""); static_assert(noexcept(nlohmann::to_json(std::declval<json&>(), true)), ""); static_assert(noexcept(nlohmann::to_json(std::declval<json&>(), test{})), ""); static_assert(noexcept(nlohmann::to_json(std::declval<json&>(), pod{})), ""); static_assert(!noexcept(nlohmann::to_json(std::declval<json&>(), pod_bis{})), ""); static_assert(noexcept(json(2)), ""); static_assert(noexcept(json(test{})), ""); static_assert(noexcept(json(pod{})), ""); static_assert(noexcept(std::declval<json>().get<pod>()), ""); static_assert(!noexcept(std::declval<json>().get<pod_bis>()), ""); static_assert(noexcept(json(pod{})), ""); } // namespace TEST_CASE("noexcept") { // silence -Wunneeded-internal-declaration errors static_cast<void>(static_cast<void(*)(json&, pod)>(&to_json)); static_cast<void>(static_cast<void(*)(json&, pod_bis)>(&to_json)); static_cast<void>(static_cast<void(*)(const json&, pod)>(&from_json)); static_cast<void>(static_cast<void(*)(const json&, pod_bis)>(&from_json)); SECTION("nothrow-copy-constructible exceptions") { // for ERR60-CPP (https://github.com/nlohmann/json/issues/531): // Exceptions should be nothrow-copy-constructible. However, compilers // treat std::runtime_exception differently in this regard. Therefore, // we can only demand nothrow-copy-constructibility for our exceptions // if std::runtime_exception is. CHECK(std::is_nothrow_copy_constructible<json::exception>::value == std::is_nothrow_copy_constructible<std::runtime_error>::value); CHECK(std::is_nothrow_copy_constructible<json::parse_error>::value == std::is_nothrow_copy_constructible<std::runtime_error>::value); CHECK(std::is_nothrow_copy_constructible<json::invalid_iterator>::value == std::is_nothrow_copy_constructible<std::runtime_error>::value); CHECK(std::is_nothrow_copy_constructible<json::type_error>::value == std::is_nothrow_copy_constructible<std::runtime_error>::value); CHECK(std::is_nothrow_copy_constructible<json::out_of_range>::value == std::is_nothrow_copy_constructible<std::runtime_error>::value); CHECK(std::is_nothrow_copy_constructible<json::other_error>::value == std::is_nothrow_copy_constructible<std::runtime_error>::value); } } DOCTEST_GCC_SUPPRESS_WARNING_POP
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/test_utils.hpp
.hpp
1,011
34
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #pragma once #include <cstdint> // uint8_t #include <fstream> // ifstream, istreambuf_iterator, ios #include <vector> // vector namespace utils { inline std::vector<std::uint8_t> read_binary_file(const std::string& filename) { std::ifstream file(filename, std::ios::binary); file.unsetf(std::ios::skipws); file.seekg(0, std::ios::end); const auto size = file.tellg(); file.seekg(0, std::ios::beg); std::vector<std::uint8_t> byte_vector; byte_vector.reserve(static_cast<std::size_t>(size)); byte_vector.insert(byte_vector.begin(), std::istream_iterator<std::uint8_t>(file), std::istream_iterator<std::uint8_t>()); return byte_vector; } } // namespace utils
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-conversions.cpp
.cpp
54,637
1,573
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // Copyright (c) 2013-2022 Niels Lohmann <http://nlohmann.me>. // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT // cmake/test.cmake selects the C++ standard versions with which to build a // unit test based on the presence of JSON_HAS_CPP_<VERSION> macros. // When using macros that are only defined for particular versions of the standard // (e.g., JSON_HAS_FILESYSTEM for C++17 and up), please mention the corresponding // version macro in a comment close by, like this: // JSON_HAS_CPP_<VERSION> (do not remove; see note at top of file) #include "doctest_compatibility.h" #define JSON_TESTS_PRIVATE #include <nlohmann/json.hpp> using nlohmann::json; #include <deque> #include <forward_list> #include <list> #include <set> #include <unordered_map> #include <unordered_set> #include <valarray> // NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") TEST_CASE("value conversion") { SECTION("get an object (explicit)") { const json::object_t o_reference = {{"object", json::object()}, {"array", {1, 2, 3, 4}}, {"number", 42}, {"boolean", false}, {"null", nullptr}, {"string", "Hello world"} }; json j(o_reference); SECTION("json::object_t") { json::object_t const o = j.get<json::object_t>(); CHECK(json(o) == j); } SECTION("std::map<json::string_t, json>") { const std::map<json::string_t, json> o = j.get<std::map<json::string_t, json>>(); CHECK(json(o) == j); } SECTION("std::multimap<json::string_t, json>") { const std::multimap<json::string_t, json> o = j.get<std::multimap<json::string_t, json>>(); CHECK(json(o) == j); } SECTION("std::unordered_map<json::string_t, json>") { const std::unordered_map<json::string_t, json> o = j.get<std::unordered_map<json::string_t, json>>(); CHECK(json(o) == j); } SECTION("std::unordered_multimap<json::string_t, json>") { const std::unordered_multimap<json::string_t, json> o = j.get<std::unordered_multimap<json::string_t, json>>(); CHECK(json(o) == j); } SECTION("exception in case of a non-object type") { CHECK_THROWS_WITH_AS( json(json::value_t::null).get<json::object_t>(), "[json.exception.type_error.302] type must be object, but is null", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::array).get<json::object_t>(), "[json.exception.type_error.302] type must be object, but is array", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::string).get<json::object_t>(), "[json.exception.type_error.302] type must be object, but is string", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::boolean).get<json::object_t>(), "[json.exception.type_error.302] type must be object, " "but is boolean", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_integer).get<json::object_t>(), "[json.exception.type_error.302] type must be object, but is number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_unsigned).get<json::object_t>(), "[json.exception.type_error.302] type must be object, but is number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_float).get<json::object_t>(), "[json.exception.type_error.302] type must be object, but is number", json::type_error&); } } SECTION("get an object (explicit, get_to)") { const json::object_t o_reference = {{"object", json::object()}, {"array", {1, 2, 3, 4}}, {"number", 42}, {"boolean", false}, {"null", nullptr}, {"string", "Hello world"} }; json j(o_reference); SECTION("json::object_t") { json::object_t o = {{"previous", "value"}}; j.get_to(o); CHECK(json(o) == j); } SECTION("std::map<json::string_t, json>") { std::map<json::string_t, json> o{{"previous", "value"}}; j.get_to(o); CHECK(json(o) == j); } SECTION("std::multimap<json::string_t, json>") { std::multimap<json::string_t, json> o{{"previous", "value"}}; j.get_to(o); CHECK(json(o) == j); } SECTION("std::unordered_map<json::string_t, json>") { std::unordered_map<json::string_t, json> o{{"previous", "value"}}; j.get_to(o); CHECK(json(o) == j); } SECTION("std::unordered_multimap<json::string_t, json>") { std::unordered_multimap<json::string_t, json> o{{"previous", "value"}}; j.get_to(o); CHECK(json(o) == j); } } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get an object (implicit)") { const json::object_t o_reference = {{"object", json::object()}, {"array", {1, 2, 3, 4}}, {"number", 42}, {"boolean", false}, {"null", nullptr}, {"string", "Hello world"} }; json j(o_reference); SECTION("json::object_t") { const json::object_t o = j; CHECK(json(o) == j); } SECTION("std::map<json::string_t, json>") { const std::map<json::string_t, json> o = j; CHECK(json(o) == j); } SECTION("std::multimap<json::string_t, json>") { const std::multimap<json::string_t, json> o = j; CHECK(json(o) == j); } SECTION("std::unordered_map<json::string_t, json>") { const std::unordered_map<json::string_t, json> o = j; CHECK(json(o) == j); } SECTION("std::unordered_multimap<json::string_t, json>") { const std::unordered_multimap<json::string_t, json> o = j; CHECK(json(o) == j); } } #endif SECTION("get an array (explicit)") { const json::array_t a_reference{json(1), json(1u), json(2.2), json(false), json("string"), json()}; json j(a_reference); SECTION("json::array_t") { const json::array_t a = j.get<json::array_t>(); CHECK(json(a) == j); } SECTION("std::list<json>") { const std::list<json> a = j.get<std::list<json>>(); CHECK(json(a) == j); } SECTION("std::forward_list<json>") { const std::forward_list<json> a = j.get<std::forward_list<json>>(); CHECK(json(a) == j); CHECK_THROWS_WITH_AS( json(json::value_t::null).get<std::forward_list<json>>(), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); } SECTION("std::vector<json>") { const std::vector<json> a = j.get<std::vector<json>>(); CHECK(json(a) == j); CHECK_THROWS_WITH_AS( json(json::value_t::null).get<std::vector<json>>(), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); #if !defined(JSON_NOEXCEPTION) SECTION("reserve is called on containers that supports it") { // make sure all values are properly copied const json j2({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); auto v2 = j2.get<std::vector<int>>(); CHECK(v2.size() == 10); } #endif } SECTION("built-in arrays") { const char str[] = "a string"; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) const int nbs[] = {0, 1, 2}; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) const json j2 = nbs; const json j3 = str; auto v = j2.get<std::vector<int>>(); auto s = j3.get<std::string>(); CHECK(std::equal(v.begin(), v.end(), std::begin(nbs))); CHECK(s == str); } SECTION("std::deque<json>") { const std::deque<json> a = j.get<std::deque<json>>(); CHECK(json(a) == j); } SECTION("exception in case of a non-array type") { CHECK_THROWS_WITH_AS( json(json::value_t::object).get<std::vector<int>>(), "[json.exception.type_error.302] type must be array, but is object", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::null).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::object).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is object", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::string).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is string", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::boolean).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is boolean", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_integer).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_unsigned).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_float).get<json::array_t>(), "[json.exception.type_error.302] type must be array, but is number", json::type_error&); } } SECTION("get an array (explicit, get_to)") { const json::array_t a_reference{json(1), json(1u), json(2.2), json(false), json("string"), json()}; json j(a_reference); SECTION("json::array_t") { json::array_t a{"previous", "value"}; j.get_to(a); CHECK(json(a) == j); } SECTION("std::valarray<json>") { std::valarray<json> a{"previous", "value"}; j.get_to(a); CHECK(json(a) == j); } SECTION("std::list<json>") { std::list<json> a{"previous", "value"}; j.get_to(a); CHECK(json(a) == j); } SECTION("std::forward_list<json>") { std::forward_list<json> a{"previous", "value"}; j.get_to(a); CHECK(json(a) == j); } SECTION("std::vector<json>") { std::vector<json> a{"previous", "value"}; j.get_to(a); CHECK(json(a) == j); } SECTION("built-in arrays") { const int nbs[] = {0, 1, 2}; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) int nbs2[] = {0, 0, 0}; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) const json j2 = nbs; j2.get_to(nbs2); CHECK(std::equal(std::begin(nbs), std::end(nbs), std::begin(nbs2))); } SECTION("std::deque<json>") { std::deque<json> a{"previous", "value"}; j.get_to(a); CHECK(json(a) == j); } } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get an array (implicit)") { const json::array_t a_reference{json(1), json(1u), json(2.2), json(false), json("string"), json()}; json j(a_reference); SECTION("json::array_t") { const json::array_t a = j; CHECK(json(a) == j); } SECTION("std::list<json>") { const std::list<json> a = j; CHECK(json(a) == j); } SECTION("std::forward_list<json>") { const std::forward_list<json> a = j; CHECK(json(a) == j); } SECTION("std::vector<json>") { const std::vector<json> a = j; CHECK(json(a) == j); } SECTION("std::deque<json>") { const std::deque<json> a = j; CHECK(json(a) == j); } } #endif SECTION("get a string (explicit)") { const json::string_t s_reference{"Hello world"}; json j(s_reference); SECTION("string_t") { const json::string_t s = j.get<json::string_t>(); CHECK(json(s) == j); } SECTION("std::string") { const std::string s = j.get<std::string>(); CHECK(json(s) == j); } #if defined(JSON_HAS_CPP_17) SECTION("std::string_view") { std::string_view const s = j.get<std::string_view>(); CHECK(json(s) == j); } #endif SECTION("exception in case of a non-string type") { CHECK_THROWS_WITH_AS( json(json::value_t::null).get<json::string_t>(), "[json.exception.type_error.302] type must be string, but is null", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::object).get<json::string_t>(), "[json.exception.type_error.302] type must be string, but is object", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::array).get<json::string_t>(), "[json.exception.type_error.302] type must be string, but is array", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::boolean).get<json::string_t>(), "[json.exception.type_error.302] type must be string, " "but is boolean", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_integer).get<json::string_t>(), "[json.exception.type_error.302] type must be string, but is number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_unsigned).get<json::string_t>(), "[json.exception.type_error.302] type must be string, but is number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_float).get<json::string_t>(), "[json.exception.type_error.302] type must be string, but is number", json::type_error&); } #if defined(JSON_HAS_CPP_17) SECTION("exception in case of a non-string type using string_view") { CHECK_THROWS_WITH_AS(json(json::value_t::null).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is null", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::object).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is object", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::array).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is array", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::boolean).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is boolean", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::number_integer).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is number", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::number_unsigned).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is number", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::number_float).get<std::string_view>(), "[json.exception.type_error.302] type must be string, but is number", json::type_error&); } #endif } SECTION("get a string (explicit, get_to)") { const json::string_t s_reference{"Hello world"}; json j(s_reference); SECTION("string_t") { json::string_t s = "previous value"; j.get_to(s); CHECK(json(s) == j); } SECTION("std::string") { std::string s = "previous value"; j.get_to(s); CHECK(json(s) == j); } #if defined(JSON_HAS_CPP_17) SECTION("std::string_view") { std::string const s = "previous value"; std::string_view sv = s; j.get_to(sv); CHECK(json(sv) == j); } #endif } SECTION("get null (explicit)") { std::nullptr_t n = nullptr; const json j(n); auto n2 = j.get<std::nullptr_t>(); CHECK(n2 == n); CHECK_THROWS_WITH_AS(json(json::value_t::string).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is string", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::object).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is object", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::array).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is array", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::boolean).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is boolean", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::number_integer).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is number", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::number_unsigned).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is number", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::number_float).get<std::nullptr_t>(), "[json.exception.type_error.302] type must be null, but is number", json::type_error&); } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get a string (implicit)") { const json::string_t s_reference{"Hello world"}; json j(s_reference); SECTION("string_t") { const json::string_t s = j; CHECK(json(s) == j); } #if defined(JSON_HAS_CPP_17) SECTION("std::string_view") { std::string_view const s = j.get<std::string_view>(); CHECK(json(s) == j); } #endif SECTION("std::string") { const std::string s = j; CHECK(json(s) == j); } } #endif SECTION("get a boolean (explicit)") { const json::boolean_t b_reference{true}; json j(b_reference); SECTION("boolean_t") { auto b = j.get<json::boolean_t>(); CHECK(json(b) == j); } SECTION("uint8_t") { auto n = j.get<uint8_t>(); CHECK(n == 1); } SECTION("bool") { const bool b = j.get<bool>(); CHECK(json(b) == j); } SECTION("exception in case of a non-number type") { CHECK_THROWS_AS(json(json::value_t::string).get<uint8_t>(), json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::null).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, but is null", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::object).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, " "but is object", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::array).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, but is array", json::type_error&); CHECK_THROWS_WITH_AS(json(json::value_t::string).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, " "but is string", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_integer).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, but is " "number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_unsigned).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, but is " "number", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::number_float).get<json::boolean_t>(), "[json.exception.type_error.302] type must be boolean, but is " "number", json::type_error&); } } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get a boolean (implicit)") { const json::boolean_t b_reference{true}; json j(b_reference); SECTION("boolean_t") { const json::boolean_t b = j; CHECK(json(b) == j); } SECTION("bool") { const bool b = j; CHECK(json(b) == j); } } #endif SECTION("get an integer number (explicit)") { const json::number_integer_t n_reference{42}; json j(n_reference); const json::number_unsigned_t n_unsigned_reference{42u}; json j_unsigned(n_unsigned_reference); SECTION("number_integer_t") { auto n = j.get<json::number_integer_t>(); CHECK(json(n) == j); } SECTION("number_unsigned_t") { auto n = j_unsigned.get<json::number_unsigned_t>(); CHECK(json(n) == j_unsigned); } SECTION("short") { auto n = j.get<short>(); CHECK(json(n) == j); } SECTION("unsigned short") { auto n = j.get<unsigned short>(); CHECK(json(n) == j); } SECTION("int") { const int n = j.get<int>(); CHECK(json(n) == j); } SECTION("unsigned int") { auto n = j.get<unsigned int>(); CHECK(json(n) == j); } SECTION("long") { const long n = j.get<long>(); CHECK(json(n) == j); } SECTION("unsigned long") { auto n = j.get<unsigned long>(); CHECK(json(n) == j); } SECTION("long long") { auto n = j.get<long long>(); CHECK(json(n) == j); } SECTION("unsigned long long") { auto n = j.get<unsigned long long>(); CHECK(json(n) == j); } SECTION("int8_t") { auto n = j.get<int8_t>(); CHECK(json(n) == j); } SECTION("int16_t") { auto n = j.get<int16_t>(); CHECK(json(n) == j); } SECTION("int32_t") { auto n = j.get<int32_t>(); CHECK(json(n) == j); } SECTION("int64_t") { auto n = j.get<int64_t>(); CHECK(json(n) == j); } SECTION("int8_fast_t") { auto n = j.get<int_fast8_t>(); CHECK(json(n) == j); } SECTION("int16_fast_t") { auto n = j.get<int_fast16_t>(); CHECK(json(n) == j); } SECTION("int32_fast_t") { auto n = j.get<int_fast32_t>(); CHECK(json(n) == j); } SECTION("int64_fast_t") { auto n = j.get<int_fast64_t>(); CHECK(json(n) == j); } SECTION("int8_least_t") { auto n = j.get<int_least8_t>(); CHECK(json(n) == j); } SECTION("int16_least_t") { auto n = j.get<int_least16_t>(); CHECK(json(n) == j); } SECTION("int32_least_t") { auto n = j.get<int_least32_t>(); CHECK(json(n) == j); } SECTION("int64_least_t") { auto n = j.get<int_least64_t>(); CHECK(json(n) == j); } SECTION("uint8_t") { auto n = j.get<uint8_t>(); CHECK(json(n) == j); } SECTION("uint16_t") { auto n = j.get<uint16_t>(); CHECK(json(n) == j); } SECTION("uint32_t") { auto n = j.get<uint32_t>(); CHECK(json(n) == j); } SECTION("uint64_t") { auto n = j.get<uint64_t>(); CHECK(json(n) == j); } SECTION("uint8_fast_t") { auto n = j.get<uint_fast8_t>(); CHECK(json(n) == j); } SECTION("uint16_fast_t") { auto n = j.get<uint_fast16_t>(); CHECK(json(n) == j); } SECTION("uint32_fast_t") { auto n = j.get<uint_fast32_t>(); CHECK(json(n) == j); } SECTION("uint64_fast_t") { auto n = j.get<uint_fast64_t>(); CHECK(json(n) == j); } SECTION("uint8_least_t") { auto n = j.get<uint_least8_t>(); CHECK(json(n) == j); } SECTION("uint16_least_t") { auto n = j.get<uint_least16_t>(); CHECK(json(n) == j); } SECTION("uint32_least_t") { auto n = j.get<uint_least32_t>(); CHECK(json(n) == j); } SECTION("uint64_least_t") { auto n = j.get<uint_least64_t>(); CHECK(json(n) == j); } SECTION("exception in case of a non-number type") { CHECK_THROWS_WITH_AS( json(json::value_t::null).get<json::number_integer_t>(), "[json.exception.type_error.302] type must be number, but is null", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::object).get<json::number_integer_t>(), "[json.exception.type_error.302] type must be number, but is object", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::array).get<json::number_integer_t>(), "[json.exception.type_error.302] type must be number, but is array", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::string).get<json::number_integer_t>(), "[json.exception.type_error.302] type must be number, but is string", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::boolean).get<json::number_integer_t>(), "[json.exception.type_error.302] type must be number, but is " "boolean", json::type_error&); CHECK_NOTHROW( json(json::value_t::number_float).get<json::number_integer_t>()); CHECK_NOTHROW( json(json::value_t::number_float).get<json::number_unsigned_t>()); } } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get an integer number (implicit)") { json::number_integer_t const n_reference{42}; json j(n_reference); json::number_unsigned_t const n_unsigned_reference{42u}; json j_unsigned(n_unsigned_reference); SECTION("number_integer_t") { auto n = j.get<json::number_integer_t>(); CHECK(json(n) == j); } SECTION("number_unsigned_t") { auto n = j_unsigned.get<json::number_unsigned_t>(); CHECK(json(n) == j_unsigned); } SECTION("short") { short const n = j; CHECK(json(n) == j); } SECTION("unsigned short") { unsigned short const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("int") { int const n = j; CHECK(json(n) == j); } SECTION("unsigned int") { unsigned int const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("long") { long const n = j; CHECK(json(n) == j); } SECTION("unsigned long") { unsigned long const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("long long") { long long const n = j; CHECK(json(n) == j); } SECTION("unsigned long long") { unsigned long long const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("int8_t") { int8_t const n = j; CHECK(json(n) == j); } SECTION("int16_t") { int16_t const n = j; CHECK(json(n) == j); } SECTION("int32_t") { int32_t const n = j; CHECK(json(n) == j); } SECTION("int64_t") { int64_t const n = j; CHECK(json(n) == j); } SECTION("int8_fast_t") { int_fast8_t const n = j; CHECK(json(n) == j); } SECTION("int16_fast_t") { int_fast16_t const n = j; CHECK(json(n) == j); } SECTION("int32_fast_t") { int_fast32_t const n = j; CHECK(json(n) == j); } SECTION("int64_fast_t") { int_fast64_t const n = j; CHECK(json(n) == j); } SECTION("int8_least_t") { int_least8_t const n = j; CHECK(json(n) == j); } SECTION("int16_least_t") { int_least16_t const n = j; CHECK(json(n) == j); } SECTION("int32_least_t") { int_least32_t const n = j; CHECK(json(n) == j); } SECTION("int64_least_t") { int_least64_t const n = j; CHECK(json(n) == j); } SECTION("uint8_t") { uint8_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint16_t") { uint16_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint32_t") { uint32_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint64_t") { uint64_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint8_fast_t") { uint_fast8_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint16_fast_t") { uint_fast16_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint32_fast_t") { uint_fast32_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint64_fast_t") { uint_fast64_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint8_least_t") { uint_least8_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint16_least_t") { uint_least16_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint32_least_t") { uint_least32_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } SECTION("uint64_least_t") { uint_least64_t const n = j_unsigned; CHECK(json(n) == j_unsigned); } } #endif SECTION("get a floating-point number (explicit)") { json::number_float_t const n_reference{42.23}; json const j(n_reference); SECTION("number_float_t") { auto n = j.get<json::number_float_t>(); CHECK(json(n).m_data.m_value.number_float == Approx(j.m_data.m_value.number_float)); } SECTION("float") { auto n = j.get<float>(); CHECK(json(n).m_data.m_value.number_float == Approx(j.m_data.m_value.number_float)); } SECTION("double") { auto n = j.get<double>(); CHECK(json(n).m_data.m_value.number_float == Approx(j.m_data.m_value.number_float)); } SECTION("exception in case of a non-string type") { CHECK_THROWS_WITH_AS( json(json::value_t::null).get<json::number_float_t>(), "[json.exception.type_error.302] type must be number, but is null", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::object).get<json::number_float_t>(), "[json.exception.type_error.302] type must be number, but is object", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::array).get<json::number_float_t>(), "[json.exception.type_error.302] type must be number, but is array", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::string).get<json::number_float_t>(), "[json.exception.type_error.302] type must be number, but is string", json::type_error&); CHECK_THROWS_WITH_AS( json(json::value_t::boolean).get<json::number_float_t>(), "[json.exception.type_error.302] type must be number, but is " "boolean", json::type_error&); CHECK_NOTHROW( json(json::value_t::number_integer).get<json::number_float_t>()); CHECK_NOTHROW( json(json::value_t::number_unsigned).get<json::number_float_t>()); } } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get a floating-point number (implicit)") { json::number_float_t const n_reference{42.23}; json const j(n_reference); SECTION("number_float_t") { json::number_float_t const n = j; CHECK(json(n).m_data.m_value.number_float == Approx(j.m_data.m_value.number_float)); } SECTION("float") { float const n = j; CHECK(json(n).m_data.m_value.number_float == Approx(j.m_data.m_value.number_float)); } SECTION("double") { double const n = j; CHECK(json(n).m_data.m_value.number_float == Approx(j.m_data.m_value.number_float)); } } #endif SECTION("get a binary value (explicit)") { json::binary_t const n_reference{{1, 2, 3}}; json j(n_reference); SECTION("binary_t") { json::binary_t const b = j.get<json::binary_t>(); CHECK(*json(b).m_data.m_value.binary == *j.m_data.m_value.binary); } SECTION("get_binary()") { SECTION("non-const") { auto& b = j.get_binary(); CHECK(*json(b).m_data.m_value.binary == *j.m_data.m_value.binary); } SECTION("non-const") { const json j_const = j; const auto& b = j_const.get_binary(); CHECK(*json(b).m_data.m_value.binary == *j.m_data.m_value.binary); } } SECTION("exception in case of a non-string type") { json j_null(json::value_t::null); json j_object(json::value_t::object); json j_array(json::value_t::array); json j_string(json::value_t::string); json j_boolean(json::value_t::boolean); const json j_null_const(json::value_t::null); const json j_object_const(json::value_t::object); const json j_array_const(json::value_t::array); const json j_string_const(json::value_t::string); const json j_boolean_const(json::value_t::boolean); CHECK_THROWS_WITH_AS(j_null.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is null", json::type_error&); CHECK_THROWS_WITH_AS(j_object.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is object", json::type_error&); CHECK_THROWS_WITH_AS(j_array.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is array", json::type_error&); CHECK_THROWS_WITH_AS(j_string.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is string", json::type_error&); CHECK_THROWS_WITH_AS(j_boolean.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is boolean", json::type_error&); CHECK_THROWS_WITH_AS(j_null_const.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is null", json::type_error&); CHECK_THROWS_WITH_AS(j_object_const.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is object", json::type_error&); CHECK_THROWS_WITH_AS(j_array_const.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is array", json::type_error&); CHECK_THROWS_WITH_AS(j_string_const.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is string", json::type_error&); CHECK_THROWS_WITH_AS(j_boolean_const.get<json::binary_t>(), "[json.exception.type_error.302] type must be binary, but is boolean", json::type_error&); CHECK_THROWS_WITH_AS(j_null.get_binary(), "[json.exception.type_error.302] type must be binary, but is null", json::type_error&); CHECK_THROWS_WITH_AS(j_object.get_binary(), "[json.exception.type_error.302] type must be binary, but is object", json::type_error&); CHECK_THROWS_WITH_AS(j_array.get_binary(), "[json.exception.type_error.302] type must be binary, but is array", json::type_error&); CHECK_THROWS_WITH_AS(j_string.get_binary(), "[json.exception.type_error.302] type must be binary, but is string", json::type_error&); CHECK_THROWS_WITH_AS(j_boolean.get_binary(), "[json.exception.type_error.302] type must be binary, but is boolean", json::type_error&); CHECK_THROWS_WITH_AS(j_null_const.get_binary(), "[json.exception.type_error.302] type must be binary, but is null", json::type_error&); CHECK_THROWS_WITH_AS(j_object_const.get_binary(), "[json.exception.type_error.302] type must be binary, but is object", json::type_error&); CHECK_THROWS_WITH_AS(j_array_const.get_binary(), "[json.exception.type_error.302] type must be binary, but is array", json::type_error&); CHECK_THROWS_WITH_AS(j_string_const.get_binary(), "[json.exception.type_error.302] type must be binary, but is string", json::type_error&); CHECK_THROWS_WITH_AS(j_boolean_const.get_binary(), "[json.exception.type_error.302] type must be binary, but is boolean", json::type_error&); } } #if JSON_USE_IMPLICIT_CONVERSIONS SECTION("get a binary value (implicit)") { json::binary_t const n_reference{{1, 2, 3}}; json const j(n_reference); SECTION("binary_t") { json::binary_t const b = j; CHECK(*json(b).m_data.m_value.binary == *j.m_data.m_value.binary); } } #endif SECTION("get an enum") { enum c_enum { value_1, value_2 }; enum class cpp_enum { value_1, value_2 }; CHECK(json(value_1).get<c_enum>() == value_1); CHECK(json(cpp_enum::value_1).get<cpp_enum>() == cpp_enum::value_1); } SECTION("more involved conversions") { SECTION("object-like STL containers") { json const j1 = {{"one", 1}, {"two", 2}, {"three", 3}}; json const j2 = {{"one", 1u}, {"two", 2u}, {"three", 3u}}; json const j3 = {{"one", 1.1}, {"two", 2.2}, {"three", 3.3}}; json const j4 = {{"one", true}, {"two", false}, {"three", true}}; json const j5 = {{"one", "eins"}, {"two", "zwei"}, {"three", "drei"}}; SECTION("std::map") { j1.get<std::map<std::string, int>>(); j2.get<std::map<std::string, unsigned int>>(); j3.get<std::map<std::string, double>>(); j4.get<std::map<std::string, bool>>(); j5.get<std::map<std::string, std::string>>(); } SECTION("std::unordered_map") { j1.get<std::unordered_map<std::string, int>>(); j2.get<std::unordered_map<std::string, unsigned int>>(); j3.get<std::unordered_map<std::string, double>>(); j4.get<std::unordered_map<std::string, bool>>(); j5.get<std::unordered_map<std::string, std::string>>(); // CHECK(m5["one"] == "eins"); } SECTION("std::multimap") { j1.get<std::multimap<std::string, int>>(); j2.get<std::multimap<std::string, unsigned int>>(); j3.get<std::multimap<std::string, double>>(); j4.get<std::multimap<std::string, bool>>(); j5.get<std::multimap<std::string, std::string>>(); // CHECK(m5["one"] == "eins"); } SECTION("std::unordered_multimap") { j1.get<std::unordered_multimap<std::string, int>>(); j2.get<std::unordered_multimap<std::string, unsigned int>>(); j3.get<std::unordered_multimap<std::string, double>>(); j4.get<std::unordered_multimap<std::string, bool>>(); j5.get<std::unordered_multimap<std::string, std::string>>(); // CHECK(m5["one"] == "eins"); } SECTION("exception in case of a non-object type") { CHECK_THROWS_WITH_AS( (json().get<std::map<std::string, int>>()), "[json.exception.type_error.302] type must be object, but is null", json::type_error&); } } SECTION("array-like STL containers") { json const j1 = {1, 2, 3, 4}; json const j2 = {1u, 2u, 3u, 4u}; json const j3 = {1.2, 2.3, 3.4, 4.5}; json const j4 = {true, false, true}; json const j5 = {"one", "two", "three"}; SECTION("std::list") { j1.get<std::list<int>>(); j2.get<std::list<unsigned int>>(); j3.get<std::list<double>>(); j4.get<std::list<bool>>(); j5.get<std::list<std::string>>(); } SECTION("std::forward_list") { j1.get<std::forward_list<int>>(); j2.get<std::forward_list<unsigned int>>(); j3.get<std::forward_list<double>>(); j4.get<std::forward_list<bool>>(); j5.get<std::forward_list<std::string>>(); } SECTION("std::array") { j1.get<std::array<int, 4>>(); j2.get<std::array<unsigned int, 3>>(); j3.get<std::array<double, 4>>(); j4.get<std::array<bool, 3>>(); j5.get<std::array<std::string, 3>>(); SECTION("std::array is larger than JSON") { std::array<int, 6> arr6 = {{1, 2, 3, 4, 5, 6}}; CHECK_THROWS_WITH_AS(j1.get_to(arr6), "[json.exception.out_of_range.401] " "array index 4 is out of range", json::out_of_range&); } SECTION("std::array is smaller than JSON") { std::array<int, 2> arr2 = {{8, 9}}; j1.get_to(arr2); CHECK(arr2[0] == 1); CHECK(arr2[1] == 2); } } SECTION("std::valarray") { j1.get<std::valarray<int>>(); j2.get<std::valarray<unsigned int>>(); j3.get<std::valarray<double>>(); j4.get<std::valarray<bool>>(); j5.get<std::valarray<std::string>>(); } SECTION("std::vector") { j1.get<std::vector<int>>(); j2.get<std::vector<unsigned int>>(); j3.get<std::vector<double>>(); j4.get<std::vector<bool>>(); j5.get<std::vector<std::string>>(); } SECTION("std::deque") { j1.get<std::deque<int>>(); j2.get<std::deque<unsigned int>>(); j2.get<std::deque<double>>(); j4.get<std::deque<bool>>(); j5.get<std::deque<std::string>>(); } SECTION("std::set") { j1.get<std::set<int>>(); j2.get<std::set<unsigned int>>(); j3.get<std::set<double>>(); j4.get<std::set<bool>>(); j5.get<std::set<std::string>>(); } SECTION("std::unordered_set") { j1.get<std::unordered_set<int>>(); j2.get<std::unordered_set<unsigned int>>(); j3.get<std::unordered_set<double>>(); j4.get<std::unordered_set<bool>>(); j5.get<std::unordered_set<std::string>>(); } SECTION("std::map (array of pairs)") { std::map<int, int> m{{0, 1}, {1, 2}, {2, 3}}; json const j6 = m; auto m2 = j6.get<std::map<int, int>>(); CHECK(m == m2); json const j7 = {0, 1, 2, 3}; json const j8 = 2; CHECK_THROWS_WITH_AS((j7.get<std::map<int, int>>()), "[json.exception.type_error.302] type must be array, " "but is number", json::type_error&); CHECK_THROWS_WITH_AS((j8.get<std::map<int, int>>()), "[json.exception.type_error.302] type must be array, " "but is number", json::type_error&); SECTION("superfluous entries") { json const j9 = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}}; m2 = j9.get<std::map<int, int>>(); CHECK(m == m2); } } SECTION("std::unordered_map (array of pairs)") { std::unordered_map<int, int> m{{0, 1}, {1, 2}, {2, 3}}; json const j6 = m; auto m2 = j6.get<std::unordered_map<int, int>>(); CHECK(m == m2); json const j7 = {0, 1, 2, 3}; json const j8 = 2; CHECK_THROWS_WITH_AS((j7.get<std::unordered_map<int, int>>()), "[json.exception.type_error.302] type must be array, " "but is number", json::type_error&); CHECK_THROWS_WITH_AS((j8.get<std::unordered_map<int, int>>()), "[json.exception.type_error.302] type must be array, " "but is number", json::type_error&); SECTION("superfluous entries") { json const j9{{0, 1, 2}, {1, 2, 3}, {2, 3, 4}}; m2 = j9.get<std::unordered_map<int, int>>(); CHECK(m == m2); } } SECTION("exception in case of a non-object type") { // 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 CHECK_THROWS_WITH_AS( (json().get<std::list<int>>()), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); CHECK_THROWS_WITH_AS( (json().get<std::vector<int>>()), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); CHECK_THROWS_WITH_AS( (json().get<std::vector<json>>()), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); CHECK_THROWS_WITH_AS( (json().get<std::list<json>>()), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); CHECK_THROWS_WITH_AS( (json().get<std::valarray<int>>()), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); CHECK_THROWS_WITH_AS( (json().get<std::map<int, int>>()), "[json.exception.type_error.302] type must be array, but is null", json::type_error&); } } } } enum class cards {kreuz, pik, herz, karo}; // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive NLOHMANN_JSON_SERIALIZE_ENUM(cards, { {cards::kreuz, "kreuz"}, {cards::pik, "pik"}, {cards::pik, "puk"}, // second entry for cards::puk; will not be used {cards::herz, "herz"}, {cards::karo, "karo"} }) enum TaskState { TS_STOPPED, TS_RUNNING, TS_COMPLETED, TS_INVALID = -1, }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive NLOHMANN_JSON_SERIALIZE_ENUM(TaskState, { {TS_INVALID, nullptr}, {TS_STOPPED, "stopped"}, {TS_RUNNING, "running"}, {TS_COMPLETED, "completed"}, }) TEST_CASE("JSON to enum mapping") { SECTION("enum class") { // enum -> json CHECK(json(cards::kreuz) == "kreuz"); CHECK(json(cards::pik) == "pik"); CHECK(json(cards::herz) == "herz"); CHECK(json(cards::karo) == "karo"); // json -> enum CHECK(cards::kreuz == json("kreuz")); CHECK(cards::pik == json("pik")); CHECK(cards::herz == json("herz")); CHECK(cards::karo == json("karo")); // invalid json -> first enum CHECK(cards::kreuz == json("what?").get<cards>()); } SECTION("traditional enum") { // enum -> json CHECK(json(TS_STOPPED) == "stopped"); CHECK(json(TS_RUNNING) == "running"); CHECK(json(TS_COMPLETED) == "completed"); CHECK(json(TS_INVALID) == json()); // json -> enum CHECK(TS_STOPPED == json("stopped")); CHECK(TS_RUNNING == json("running")); CHECK(TS_COMPLETED == json("completed")); CHECK(TS_INVALID == json()); // invalid json -> first enum CHECK(TS_INVALID == json("what?").get<TaskState>()); } } DOCTEST_CLANG_SUPPRESS_WARNING_POP
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-cbor.cpp
.cpp
130,050
2,706
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #include <nlohmann/json.hpp> using nlohmann::json; #include <fstream> #include <sstream> #include <iomanip> #include <iostream> #include <limits> #include <set> #include "make_test_data_available.hpp" #include "test_utils.hpp" namespace { class SaxCountdown { public: explicit SaxCountdown(const int count) : events_left(count) {} bool null() { return events_left-- > 0; } bool boolean(bool /*unused*/) { return events_left-- > 0; } bool number_integer(json::number_integer_t /*unused*/) { return events_left-- > 0; } bool number_unsigned(json::number_unsigned_t /*unused*/) { return events_left-- > 0; } bool number_float(json::number_float_t /*unused*/, const std::string& /*unused*/) { return events_left-- > 0; } bool string(std::string& /*unused*/) { return events_left-- > 0; } bool binary(std::vector<std::uint8_t>& /*unused*/) { return events_left-- > 0; } bool start_object(std::size_t /*unused*/) { return events_left-- > 0; } bool key(std::string& /*unused*/) { return events_left-- > 0; } bool end_object() { return events_left-- > 0; } bool start_array(std::size_t /*unused*/) { return events_left-- > 0; } bool end_array() { return events_left-- > 0; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const json::exception& /*unused*/) // NOLINT(readability-convert-member-functions-to-static) { return false; } private: int events_left = 0; }; } // namespace TEST_CASE("CBOR") { SECTION("individual values") { SECTION("discarded") { // discarded values are not serialized json const j = json::value_t::discarded; const auto result = json::to_cbor(j); CHECK(result.empty()); } SECTION("NaN") { // NaN value json const j = std::numeric_limits<json::number_float_t>::quiet_NaN(); const std::vector<uint8_t> expected = {0xf9, 0x7e, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); } SECTION("Infinity") { // Infinity value json const j = std::numeric_limits<json::number_float_t>::infinity(); const std::vector<uint8_t> expected = {0xf9, 0x7c, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); } SECTION("null") { const json j = nullptr; const std::vector<uint8_t> expected = {0xf6}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("boolean") { SECTION("true") { const json j = true; const std::vector<uint8_t> expected = {0xf5}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("false") { const json j = false; const std::vector<uint8_t> expected = {0xf4}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("number") { SECTION("signed") { SECTION("-9223372036854775808..-4294967297") { const std::vector<int64_t> numbers { (std::numeric_limits<int64_t>::min)(), -1000000000000000000, -100000000000000000, -10000000000000000, -1000000000000000, -100000000000000, -10000000000000, -1000000000000, -100000000000, -10000000000, -4294967297, }; for (const auto i : numbers) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_integer()); // create expected byte vector const auto positive = static_cast<uint64_t>(-1 - i); const std::vector<uint8_t> expected { static_cast<uint8_t>(0x3b), static_cast<uint8_t>((positive >> 56) & 0xff), static_cast<uint8_t>((positive >> 48) & 0xff), static_cast<uint8_t>((positive >> 40) & 0xff), static_cast<uint8_t>((positive >> 32) & 0xff), static_cast<uint8_t>((positive >> 24) & 0xff), static_cast<uint8_t>((positive >> 16) & 0xff), static_cast<uint8_t>((positive >> 8) & 0xff), static_cast<uint8_t>(positive & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 9); // check individual bytes CHECK(result[0] == 0x3b); const uint64_t restored = (static_cast<uint64_t>(result[1]) << 070) + (static_cast<uint64_t>(result[2]) << 060) + (static_cast<uint64_t>(result[3]) << 050) + (static_cast<uint64_t>(result[4]) << 040) + (static_cast<uint64_t>(result[5]) << 030) + (static_cast<uint64_t>(result[6]) << 020) + (static_cast<uint64_t>(result[7]) << 010) + static_cast<uint64_t>(result[8]); CHECK(restored == positive); CHECK(-1 - static_cast<int64_t>(restored) == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("-4294967296..-65537") { const std::vector<int64_t> numbers { -65537, -100000, -1000000, -10000000, -100000000, -1000000000, -4294967296, }; for (const auto i : numbers) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_integer()); // create expected byte vector auto positive = static_cast<uint32_t>(static_cast<uint64_t>(-1 - i) & 0x00000000ffffffff); const std::vector<uint8_t> expected { static_cast<uint8_t>(0x3a), static_cast<uint8_t>((positive >> 24) & 0xff), static_cast<uint8_t>((positive >> 16) & 0xff), static_cast<uint8_t>((positive >> 8) & 0xff), static_cast<uint8_t>(positive & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 5); // check individual bytes CHECK(result[0] == 0x3a); const uint32_t restored = (static_cast<uint32_t>(result[1]) << 030) + (static_cast<uint32_t>(result[2]) << 020) + (static_cast<uint32_t>(result[3]) << 010) + static_cast<uint32_t>(result[4]); CHECK(restored == positive); CHECK(-1LL - restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("-65536..-257") { for (int32_t i = -65536; i <= -257; ++i) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_integer()); // create expected byte vector const auto positive = static_cast<uint16_t>(-1 - i); const std::vector<uint8_t> expected { static_cast<uint8_t>(0x39), static_cast<uint8_t>((positive >> 8) & 0xff), static_cast<uint8_t>(positive & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 3); // check individual bytes CHECK(result[0] == 0x39); const auto restored = static_cast<uint16_t>(static_cast<uint8_t>(result[1]) * 256 + static_cast<uint8_t>(result[2])); CHECK(restored == positive); CHECK(-1 - restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("-9263 (int 16)") { const json j = -9263; std::vector<uint8_t> expected = {0x39, 0x24, 0x2e}; const auto result = json::to_cbor(j); CHECK(result == expected); const auto restored = static_cast<int16_t>(-1 - ((result[1] << 8) + result[2])); CHECK(restored == -9263); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("-256..-24") { for (auto i = -256; i < -24; ++i) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { 0x38, static_cast<uint8_t>(-1 - i), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 2); // check individual bytes CHECK(result[0] == 0x38); CHECK(static_cast<int16_t>(-1 - result[1]) == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("-24..-1") { for (auto i = -24; i <= -1; ++i) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { static_cast<uint8_t>(0x20 - 1 - static_cast<uint8_t>(i)), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 1); // check individual bytes CHECK(static_cast<int8_t>(0x20 - 1 - result[0]) == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("0..23") { for (size_t i = 0; i <= 23; ++i) { CAPTURE(i) // create JSON value with integer number json j = -1; j.get_ref<json::number_integer_t&>() = static_cast<json::number_integer_t>(i); // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { static_cast<uint8_t>(i), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 1); // check individual bytes CHECK(result[0] == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("24..255") { for (size_t i = 24; i <= 255; ++i) { CAPTURE(i) // create JSON value with integer number json j = -1; j.get_ref<json::number_integer_t&>() = static_cast<json::number_integer_t>(i); // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { static_cast<uint8_t>(0x18), static_cast<uint8_t>(i), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 2); // check individual bytes CHECK(result[0] == 0x18); CHECK(result[1] == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("256..65535") { for (size_t i = 256; i <= 65535; ++i) { CAPTURE(i) // create JSON value with integer number json j = -1; j.get_ref<json::number_integer_t&>() = static_cast<json::number_integer_t>(i); // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { static_cast<uint8_t>(0x19), static_cast<uint8_t>((i >> 8) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 3); // check individual bytes CHECK(result[0] == 0x19); const auto restored = static_cast<uint16_t>(static_cast<uint8_t>(result[1]) * 256 + static_cast<uint8_t>(result[2])); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("65536..4294967295") { for (const uint32_t i : { 65536u, 77777u, 1048576u }) { CAPTURE(i) // create JSON value with integer number json j = -1; j.get_ref<json::number_integer_t&>() = static_cast<json::number_integer_t>(i); // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { 0x1a, static_cast<uint8_t>((i >> 24) & 0xff), static_cast<uint8_t>((i >> 16) & 0xff), static_cast<uint8_t>((i >> 8) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 5); // check individual bytes CHECK(result[0] == 0x1a); const uint32_t restored = (static_cast<uint32_t>(result[1]) << 030) + (static_cast<uint32_t>(result[2]) << 020) + (static_cast<uint32_t>(result[3]) << 010) + static_cast<uint32_t>(result[4]); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("4294967296..4611686018427387903") { for (const uint64_t i : { 4294967296ul, 4611686018427387903ul }) { CAPTURE(i) // create JSON value with integer number json j = -1; j.get_ref<json::number_integer_t&>() = static_cast<json::number_integer_t>(i); // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { 0x1b, static_cast<uint8_t>((i >> 070) & 0xff), static_cast<uint8_t>((i >> 060) & 0xff), static_cast<uint8_t>((i >> 050) & 0xff), static_cast<uint8_t>((i >> 040) & 0xff), static_cast<uint8_t>((i >> 030) & 0xff), static_cast<uint8_t>((i >> 020) & 0xff), static_cast<uint8_t>((i >> 010) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 9); // check individual bytes CHECK(result[0] == 0x1b); const uint64_t restored = (static_cast<uint64_t>(result[1]) << 070) + (static_cast<uint64_t>(result[2]) << 060) + (static_cast<uint64_t>(result[3]) << 050) + (static_cast<uint64_t>(result[4]) << 040) + (static_cast<uint64_t>(result[5]) << 030) + (static_cast<uint64_t>(result[6]) << 020) + (static_cast<uint64_t>(result[7]) << 010) + static_cast<uint64_t>(result[8]); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("-32768..-129 (int 16)") { for (int16_t i = -32768; i <= static_cast<std::int16_t>(-129); ++i) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_integer()); // create expected byte vector const std::vector<uint8_t> expected { 0xd1, static_cast<uint8_t>((i >> 8) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_msgpack(j); CHECK(result == expected); CHECK(result.size() == 3); // check individual bytes CHECK(result[0] == 0xd1); const auto restored = static_cast<int16_t>((result[1] << 8) + result[2]); CHECK(restored == i); // roundtrip CHECK(json::from_msgpack(result) == j); } } } SECTION("unsigned") { SECTION("0..23 (Integer)") { for (size_t i = 0; i <= 23; ++i) { CAPTURE(i) // create JSON value with unsigned integer number const json j = i; // check type CHECK(j.is_number_unsigned()); // create expected byte vector const std::vector<uint8_t> expected { static_cast<uint8_t>(i), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 1); // check individual bytes CHECK(result[0] == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("24..255 (one-byte uint8_t)") { for (size_t i = 24; i <= 255; ++i) { CAPTURE(i) // create JSON value with unsigned integer number const json j = i; // check type CHECK(j.is_number_unsigned()); // create expected byte vector const std::vector<uint8_t> expected { 0x18, static_cast<uint8_t>(i), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 2); // check individual bytes CHECK(result[0] == 0x18); const auto restored = static_cast<uint8_t>(result[1]); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("256..65535 (two-byte uint16_t)") { for (size_t i = 256; i <= 65535; ++i) { CAPTURE(i) // create JSON value with unsigned integer number const json j = i; // check type CHECK(j.is_number_unsigned()); // create expected byte vector const std::vector<uint8_t> expected { 0x19, static_cast<uint8_t>((i >> 8) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 3); // check individual bytes CHECK(result[0] == 0x19); const auto restored = static_cast<uint16_t>(static_cast<uint8_t>(result[1]) * 256 + static_cast<uint8_t>(result[2])); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("65536..4294967295 (four-byte uint32_t)") { for (const uint32_t i : { 65536u, 77777u, 1048576u }) { CAPTURE(i) // create JSON value with unsigned integer number const json j = i; // check type CHECK(j.is_number_unsigned()); // create expected byte vector const std::vector<uint8_t> expected { 0x1a, static_cast<uint8_t>((i >> 24) & 0xff), static_cast<uint8_t>((i >> 16) & 0xff), static_cast<uint8_t>((i >> 8) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 5); // check individual bytes CHECK(result[0] == 0x1a); const uint32_t restored = (static_cast<uint32_t>(result[1]) << 030) + (static_cast<uint32_t>(result[2]) << 020) + (static_cast<uint32_t>(result[3]) << 010) + static_cast<uint32_t>(result[4]); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("4294967296..4611686018427387903 (eight-byte uint64_t)") { for (const uint64_t i : { 4294967296ul, 4611686018427387903ul }) { CAPTURE(i) // create JSON value with integer number const json j = i; // check type CHECK(j.is_number_unsigned()); // create expected byte vector const std::vector<uint8_t> expected { 0x1b, static_cast<uint8_t>((i >> 070) & 0xff), static_cast<uint8_t>((i >> 060) & 0xff), static_cast<uint8_t>((i >> 050) & 0xff), static_cast<uint8_t>((i >> 040) & 0xff), static_cast<uint8_t>((i >> 030) & 0xff), static_cast<uint8_t>((i >> 020) & 0xff), static_cast<uint8_t>((i >> 010) & 0xff), static_cast<uint8_t>(i & 0xff), }; // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == 9); // check individual bytes CHECK(result[0] == 0x1b); const uint64_t restored = (static_cast<uint64_t>(result[1]) << 070) + (static_cast<uint64_t>(result[2]) << 060) + (static_cast<uint64_t>(result[3]) << 050) + (static_cast<uint64_t>(result[4]) << 040) + (static_cast<uint64_t>(result[5]) << 030) + (static_cast<uint64_t>(result[6]) << 020) + (static_cast<uint64_t>(result[7]) << 010) + static_cast<uint64_t>(result[8]); CHECK(restored == i); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } } SECTION("double-precision float") { SECTION("3.1415925") { double v = 3.1415925; const json j = v; std::vector<uint8_t> expected = { 0xfb, 0x40, 0x09, 0x21, 0xfb, 0x3f, 0xa6, 0xde, 0xfc }; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("single-precision float") { SECTION("0.5") { double v = 0.5; const json j = v; // its double-precision float binary value is // {0xfb, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // but to save memory, we can store it as single-precision float. const std::vector<uint8_t> expected = {0xfa, 0x3f, 0x00, 0x00, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("0.0") { double v = 0.0; const json j = v; // its double-precision binary value is: // {0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} const std::vector<uint8_t> expected = {0xfa, 0x00, 0x00, 0x00, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("-0.0") { double v = -0.0; const json j = v; // its double-precision binary value is: // {0xfb, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} const std::vector<uint8_t> expected = {0xfa, 0x80, 0x00, 0x00, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("100.0") { double v = 100.0; const json j = v; // its double-precision binary value is: // {0xfb, 0x40, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} const std::vector<uint8_t> expected = {0xfa, 0x42, 0xc8, 0x00, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("200.0") { double v = 200.0; const json j = v; // its double-precision binary value is: // {0xfb, 0x40, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} const std::vector<uint8_t> expected = {0xfa, 0x43, 0x48, 0x00, 0x00}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("3.40282e+38(max float)") { float v = (std::numeric_limits<float>::max)(); const json j = v; const std::vector<uint8_t> expected = { 0xfa, 0x7f, 0x7f, 0xff, 0xff }; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("-3.40282e+38(lowest float)") { auto v = static_cast<double>(std::numeric_limits<float>::lowest()); const json j = v; const std::vector<uint8_t> expected = { 0xfa, 0xff, 0x7f, 0xff, 0xff }; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("1 + 3.40282e+38(more than max float)") { double v = static_cast<double>((std::numeric_limits<float>::max)()) + 0.1e+34; const json j = v; const std::vector<uint8_t> expected = { 0xfb, 0x47, 0xf0, 0x00, 0x03, 0x04, 0xdc, 0x64, 0x49 }; // double const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } SECTION("-1 - 3.40282e+38(less than lowest float)") { double v = static_cast<double>(std::numeric_limits<float>::lowest()) - 1.0; const json j = v; const std::vector<uint8_t> expected = { 0xfa, 0xff, 0x7f, 0xff, 0xff }; // the same with lowest float const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result) == v); } } SECTION("half-precision float (edge cases)") { SECTION("errors") { SECTION("no byte follows") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xf9})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({0xf9}), true, false).is_discarded()); } SECTION("only one byte follows") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xf9, 0x7c})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({0xf9, 0x7c}), true, false).is_discarded()); } } SECTION("exp = 0b00000") { SECTION("0 (0 00000 0000000000)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x00, 0x00})); json::number_float_t d{j}; CHECK(d == 0.0); } SECTION("-0 (1 00000 0000000000)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x80, 0x00})); json::number_float_t d{j}; CHECK(d == -0.0); } SECTION("2**-24 (0 00000 0000000001)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x00, 0x01})); json::number_float_t d{j}; CHECK(d == std::pow(2.0, -24.0)); } } SECTION("exp = 0b11111") { SECTION("infinity (0 11111 0000000000)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x7c, 0x00})); json::number_float_t d{j}; CHECK(d == std::numeric_limits<json::number_float_t>::infinity()); CHECK(j.dump() == "null"); } SECTION("-infinity (1 11111 0000000000)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0xfc, 0x00})); json::number_float_t d{j}; CHECK(d == -std::numeric_limits<json::number_float_t>::infinity()); CHECK(j.dump() == "null"); } } SECTION("other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format") { SECTION("1 (0 01111 0000000000)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x3c, 0x00})); json::number_float_t d{j}; CHECK(d == 1); } SECTION("-2 (1 10000 0000000000)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0xc0, 0x00})); json::number_float_t d{j}; CHECK(d == -2); } SECTION("65504 (0 11110 1111111111)") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x7b, 0xff})); json::number_float_t d{j}; CHECK(d == 65504); } } SECTION("infinity") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x7c, 0x00})); json::number_float_t const d{j}; CHECK(!std::isfinite(d)); CHECK(j.dump() == "null"); } SECTION("NaN") { json const j = json::from_cbor(std::vector<uint8_t>({0xf9, 0x7e, 0x00})); json::number_float_t const d{j}; CHECK(std::isnan(d)); CHECK(j.dump() == "null"); } } } SECTION("string") { SECTION("N = 0..23") { for (size_t N = 0; N <= 0x17; ++N) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::string(N, 'x'); const json j = s; // create expected byte vector std::vector<uint8_t> expected; expected.push_back(static_cast<uint8_t>(0x60 + N)); for (size_t i = 0; i < N; ++i) { expected.push_back('x'); } // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 1); // check that no null byte is appended if (N > 0) { CHECK(result.back() != '\x00'); } // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("N = 24..255") { for (size_t N = 24; N <= 255; ++N) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::string(N, 'x'); const json j = s; // create expected byte vector std::vector<uint8_t> expected; expected.push_back(0x78); expected.push_back(static_cast<uint8_t>(N)); for (size_t i = 0; i < N; ++i) { expected.push_back('x'); } // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 2); // check that no null byte is appended CHECK(result.back() != '\x00'); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("N = 256..65535") { for (const size_t N : { 256u, 999u, 1025u, 3333u, 2048u, 65535u }) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::string(N, 'x'); const json j = s; // create expected byte vector (hack: create string first) std::vector<uint8_t> expected(N, 'x'); // reverse order of commands, because we insert at begin() expected.insert(expected.begin(), static_cast<uint8_t>(N & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 8) & 0xff)); expected.insert(expected.begin(), 0x79); // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 3); // check that no null byte is appended CHECK(result.back() != '\x00'); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("N = 65536..4294967295") { for (const size_t N : { 65536u, 77777u, 1048576u }) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::string(N, 'x'); const json j = s; // create expected byte vector (hack: create string first) std::vector<uint8_t> expected(N, 'x'); // reverse order of commands, because we insert at begin() expected.insert(expected.begin(), static_cast<uint8_t>(N & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 8) & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 16) & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 24) & 0xff)); expected.insert(expected.begin(), 0x7a); // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 5); // check that no null byte is appended CHECK(result.back() != '\x00'); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } } SECTION("array") { SECTION("empty") { const json j = json::array(); std::vector<uint8_t> expected = {0x80}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("[null]") { const json j = {nullptr}; const std::vector<uint8_t> expected = {0x81, 0xf6}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("[1,2,3,4,5]") { const json j = json::parse("[1,2,3,4,5]"); const std::vector<uint8_t> expected = {0x85, 0x01, 0x02, 0x03, 0x04, 0x05}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("[[[[]]]]") { const json j = json::parse("[[[[]]]]"); const std::vector<uint8_t> expected = {0x81, 0x81, 0x81, 0x80}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("array with uint16_t elements") { const json j(257, nullptr); std::vector<uint8_t> expected(j.size() + 3, 0xf6); // all null expected[0] = 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); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("array with uint32_t elements") { const json j(65793, nullptr); std::vector<uint8_t> expected(j.size() + 5, 0xf6); // all null expected[0] = 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); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("object") { SECTION("empty") { const json j = json::object(); const std::vector<uint8_t> expected = {0xa0}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("{\"\":null}") { const json j = {{"", nullptr}}; const std::vector<uint8_t> expected = {0xa1, 0x60, 0xf6}; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("{\"a\": {\"b\": {\"c\": {}}}}") { const json j = json::parse(R"({"a": {"b": {"c": {}}}})"); const std::vector<uint8_t> expected = { 0xa1, 0x61, 0x61, 0xa1, 0x61, 0x62, 0xa1, 0x61, 0x63, 0xa0 }; const auto result = json::to_cbor(j); CHECK(result == expected); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("object with uint8_t elements") { 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. CHECK(result.size() == 1787); // 1 type, 1 size, 255*7 content CHECK(result[0] == 0xb8); // map 8 bit CHECK(result[1] == 0xff); // size byte (0xff) // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("object with uint16_t elements") { 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. CHECK(result.size() == 1795); // 1 type, 2 size, 256*7 content CHECK(result[0] == 0xb9); // map 16 bit CHECK(result[1] == 0x01); // byte 0 of size (0x0100) CHECK(result[2] == 0x00); // byte 1 of size (0x0100) // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } SECTION("object with uint32_t elements") { 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. CHECK(result.size() == 458757); // 1 type, 4 size, 65536*7 content CHECK(result[0] == 0xba); // map 32 bit CHECK(result[1] == 0x00); // byte 0 of size (0x00010000) CHECK(result[2] == 0x01); // byte 1 of size (0x00010000) CHECK(result[3] == 0x00); // byte 2 of size (0x00010000) CHECK(result[4] == 0x00); // byte 3 of size (0x00010000) // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("binary") { SECTION("N = 0..23") { for (size_t N = 0; N <= 0x17; ++N) { CAPTURE(N) // create JSON value with byte array containing of N * 'x' const auto s = std::vector<uint8_t>(N, 'x'); const json j = json::binary(s); // create expected byte vector std::vector<uint8_t> expected; expected.push_back(static_cast<uint8_t>(0x40 + N)); for (size_t i = 0; i < N; ++i) { expected.push_back(0x78); } // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 1); // check that no null byte is appended if (N > 0) { CHECK(result.back() != '\x00'); } // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("N = 24..255") { for (size_t N = 24; N <= 255; ++N) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::vector<uint8_t>(N, 'x'); const json j = json::binary(s); // create expected byte vector std::vector<uint8_t> expected; expected.push_back(0x58); expected.push_back(static_cast<uint8_t>(N)); for (size_t i = 0; i < N; ++i) { expected.push_back('x'); } // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 2); // check that no null byte is appended CHECK(result.back() != '\x00'); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("N = 256..65535") { for (const size_t N : { 256u, 999u, 1025u, 3333u, 2048u, 65535u }) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::vector<uint8_t>(N, 'x'); const json j = json::binary(s); // create expected byte vector (hack: create string first) std::vector<uint8_t> expected(N, 'x'); // reverse order of commands, because we insert at begin() expected.insert(expected.begin(), static_cast<uint8_t>(N & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 8) & 0xff)); expected.insert(expected.begin(), 0x59); // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 3); // check that no null byte is appended CHECK(result.back() != '\x00'); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("N = 65536..4294967295") { for (const size_t N : { 65536u, 77777u, 1048576u }) { CAPTURE(N) // create JSON value with string containing of N * 'x' const auto s = std::vector<uint8_t>(N, 'x'); const json j = json::binary(s); // create expected byte vector (hack: create string first) std::vector<uint8_t> expected(N, 'x'); // reverse order of commands, because we insert at begin() expected.insert(expected.begin(), static_cast<uint8_t>(N & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 8) & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 16) & 0xff)); expected.insert(expected.begin(), static_cast<uint8_t>((N >> 24) & 0xff)); expected.insert(expected.begin(), 0x5a); // compare result + size const auto result = json::to_cbor(j); CHECK(result == expected); CHECK(result.size() == N + 5); // check that no null byte is appended CHECK(result.back() != '\x00'); // roundtrip CHECK(json::from_cbor(result) == j); CHECK(json::from_cbor(result, true, false) == j); } } SECTION("indefinite size") { std::vector<std::uint8_t> const input = {0x5F, 0x44, 0xaa, 0xbb, 0xcc, 0xdd, 0x43, 0xee, 0xff, 0x99, 0xFF}; auto j = json::from_cbor(input); CHECK(j.is_binary()); auto k = json::binary({0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x99}); CAPTURE(j.dump(0, ' ', false, json::error_handler_t::strict)) CHECK(j == k); } SECTION("binary in array") { // array with three empty byte strings std::vector<std::uint8_t> const input = {0x83, 0x40, 0x40, 0x40}; json _; CHECK_NOTHROW(_ = json::from_cbor(input)); } SECTION("binary in object") { // object mapping "foo" to empty byte string std::vector<std::uint8_t> const input = {0xA1, 0x63, 0x66, 0x6F, 0x6F, 0x40}; json _; CHECK_NOTHROW(_ = json::from_cbor(input)); } SECTION("SAX callback with binary") { // object mapping "foo" to byte string std::vector<std::uint8_t> const input = {0xA1, 0x63, 0x66, 0x6F, 0x6F, 0x41, 0x00}; // callback to set binary_seen to true if a binary value was seen bool binary_seen = false; auto callback = [&binary_seen](int /*depth*/, json::parse_event_t /*event*/, json & parsed) noexcept { if (parsed.is_binary()) { binary_seen = true; } return true; }; json j; auto cbp = nlohmann::detail::json_sax_dom_callback_parser<json>(j, callback, true); CHECK(json::sax_parse(input, &cbp, json::input_format_t::cbor)); CHECK(j.at("foo").is_binary()); CHECK(binary_seen); } } } SECTION("additional deserialization") { SECTION("0x5b (byte array)") { std::vector<uint8_t> const given = {0x5b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x61 }; const json j = json::from_cbor(given); CHECK(j == json::binary(std::vector<uint8_t> {'a'})); } SECTION("0x7b (string)") { std::vector<uint8_t> const given = {0x7b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x61 }; const json j = json::from_cbor(given); CHECK(j == "a"); } SECTION("0x9b (array)") { std::vector<uint8_t> const given = {0x9b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf4 }; const json j = json::from_cbor(given); CHECK(j == json::parse("[false]")); } SECTION("0xbb (map)") { std::vector<uint8_t> const given = {0xbb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x60, 0xf4 }; const json j = json::from_cbor(given); CHECK(j == json::parse("{\"\": false}")); } } SECTION("errors") { SECTION("empty byte vector") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>()), "[json.exception.parse_error.110] parse error at byte 1: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>(), true, false).is_discarded()); } SECTION("too short byte vector") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x18})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x19})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x19, 0x00})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1a})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1a, 0x00})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1a, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 4: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1a, 0x00, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 4: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 6: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 7: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 8: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})), "[json.exception.parse_error.110] parse error at byte 9: syntax error while parsing CBOR number: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x62})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR string: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x62, 0x60})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR string: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x7F})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR string: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x7F, 0x60})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR string: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x82, 0x01})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x9F, 0x01})), "[json.exception.parse_error.110] parse error at byte 3: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xBF, 0x61, 0x61, 0xF5})), "[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xA1, 0x61, 0X61})), "[json.exception.parse_error.110] parse error at byte 4: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xBF, 0x61, 0X61})), "[json.exception.parse_error.110] parse error at byte 4: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR binary: unexpected end of input", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F, 0x00})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR binary: expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x00", json::parse_error&); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x41})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR binary: unexpected end of input", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({0x18}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x19}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x19, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1a}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1a, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1a, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1a, 0x00, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x62}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x62, 0x60}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x7F}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x7F, 0x60}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x82, 0x01}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x9F, 0x01}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0xBF, 0x61, 0x61, 0xF5}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0xA1, 0x61, 0x61}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0xBF, 0x61, 0x61}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x5F}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x5F, 0x00}), true, false).is_discarded()); CHECK(json::from_cbor(std::vector<uint8_t>({0x41}), true, false).is_discarded()); } SECTION("unsupported bytes") { SECTION("concrete examples") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x1c})), "[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({0x1c}), true, false).is_discarded()); CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xf8})), "[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xF8", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({0xf8}), true, false).is_discarded()); } SECTION("all unsupported bytes") { for (const auto byte : { // ? 0x1c, 0x1d, 0x1e, 0x1f, // ? 0x3c, 0x3d, 0x3e, 0x3f, // ? 0x5c, 0x5d, 0x5e, // ? 0x7c, 0x7d, 0x7e, // ? 0x9c, 0x9d, 0x9e, // ? 0xbc, 0xbd, 0xbe, // date/time 0xc0, 0xc1, // bignum 0xc2, 0xc3, // fraction 0xc4, // bigfloat 0xc5, // tagged item 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, // expected conversion 0xd5, 0xd6, 0xd7, // more tagged items 0xd8, 0xd9, 0xda, 0xdb, // ? 0xdc, 0xdd, 0xde, 0xdf, // (simple value) 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, // undefined 0xf7, // simple value 0xf8 }) { json _; CHECK_THROWS_AS(_ = json::from_cbor(std::vector<uint8_t>({static_cast<uint8_t>(byte)})), json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({static_cast<uint8_t>(byte)}), true, false).is_discarded()); } } } SECTION("invalid string in map") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xa1, 0xff, 0x01})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF", json::parse_error&); CHECK(json::from_cbor(std::vector<uint8_t>({0xa1, 0xff, 0x01}), true, false).is_discarded()); } SECTION("strict mode") { std::vector<uint8_t> const vec = {0xf6, 0xf6}; SECTION("non-strict mode") { const auto result = json::from_cbor(vec, false); CHECK(result == json()); CHECK(!json::from_cbor(vec, false, false).is_discarded()); } SECTION("strict mode") { json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(vec), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR value: expected end of input; last byte: 0xF6", json::parse_error&); CHECK(json::from_cbor(vec, true, false).is_discarded()); } } } SECTION("SAX aborts") { SECTION("start_array(len)") { std::vector<uint8_t> const v = {0x83, 0x01, 0x02, 0x03}; SaxCountdown scp(0); CHECK(!json::sax_parse(v, &scp, json::input_format_t::cbor)); } SECTION("start_object(len)") { std::vector<uint8_t> const v = {0xA1, 0x63, 0x66, 0x6F, 0x6F, 0xF4}; SaxCountdown scp(0); CHECK(!json::sax_parse(v, &scp, json::input_format_t::cbor)); } SECTION("key()") { std::vector<uint8_t> const v = {0xA1, 0x63, 0x66, 0x6F, 0x6F, 0xF4}; SaxCountdown scp(1); CHECK(!json::sax_parse(v, &scp, json::input_format_t::cbor)); } } } // use this testcase outside [hide] to run it with Valgrind TEST_CASE("single CBOR roundtrip") { SECTION("sample.json") { std::string const filename = TEST_DATA_DIRECTORY "/json_testsuite/sample.json"; // parse JSON file std::ifstream f_json(filename); const json j1 = json::parse(f_json); // parse CBOR file auto packed = utils::read_binary_file(filename + ".cbor"); json j2; CHECK_NOTHROW(j2 = json::from_cbor(packed)); // compare parsed JSON values CHECK(j1 == j2); SECTION("roundtrips") { SECTION("std::ostringstream") { std::basic_ostringstream<std::uint8_t> ss; json::to_cbor(j1, ss); json j3 = json::from_cbor(ss.str()); CHECK(j1 == j3); } SECTION("std::string") { std::string s; json::to_cbor(j1, s); json j3 = json::from_cbor(s); CHECK(j1 == j3); } } // check with different start index packed.insert(packed.begin(), 5, 0xff); CHECK(j1 == json::from_cbor(packed.begin() + 5, packed.end())); } } #if !defined(JSON_NOEXCEPTION) TEST_CASE("CBOR regressions") { SECTION("fuzz test results") { /* 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. */ for (const std::string filename : { TEST_DATA_DIRECTORY "/cbor_regression/test01", TEST_DATA_DIRECTORY "/cbor_regression/test02", TEST_DATA_DIRECTORY "/cbor_regression/test03", TEST_DATA_DIRECTORY "/cbor_regression/test04", TEST_DATA_DIRECTORY "/cbor_regression/test05", TEST_DATA_DIRECTORY "/cbor_regression/test06", TEST_DATA_DIRECTORY "/cbor_regression/test07", TEST_DATA_DIRECTORY "/cbor_regression/test08", TEST_DATA_DIRECTORY "/cbor_regression/test09", TEST_DATA_DIRECTORY "/cbor_regression/test10", TEST_DATA_DIRECTORY "/cbor_regression/test11", TEST_DATA_DIRECTORY "/cbor_regression/test12", TEST_DATA_DIRECTORY "/cbor_regression/test13", TEST_DATA_DIRECTORY "/cbor_regression/test14", TEST_DATA_DIRECTORY "/cbor_regression/test15", TEST_DATA_DIRECTORY "/cbor_regression/test16", TEST_DATA_DIRECTORY "/cbor_regression/test17", TEST_DATA_DIRECTORY "/cbor_regression/test18", TEST_DATA_DIRECTORY "/cbor_regression/test19", TEST_DATA_DIRECTORY "/cbor_regression/test20", TEST_DATA_DIRECTORY "/cbor_regression/test21" }) { CAPTURE(filename) try { // parse CBOR file auto vec1 = utils::read_binary_file(filename); json j1 = json::from_cbor(vec1); try { // step 2: round trip std::vector<uint8_t> const vec2 = json::to_cbor(j1); // parse serialization json j2 = json::from_cbor(vec2); // deserializations must match CHECK(j1 == j2); } catch (const json::parse_error&) { // parsing a CBOR serialization must not fail CHECK(false); } } catch (const json::parse_error&) { // parse errors are ok, because input may be random bytes } } } } #endif TEST_CASE("CBOR roundtrips" * doctest::skip()) { SECTION("input from flynn") { // most of these are excluded due to differences in key order (not a real problem) std::set<std::string> exclude_packed; exclude_packed.insert(TEST_DATA_DIRECTORY "/json.org/1.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/json.org/2.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/json.org/3.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/json.org/4.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/json.org/5.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/json_testsuite/sample.json"); // kills AppVeyor exclude_packed.insert(TEST_DATA_DIRECTORY "/json_tests/pass1.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/regression/working_file.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_duplicated_key.json"); exclude_packed.insert(TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_long_strings.json"); for (const std::string filename : { TEST_DATA_DIRECTORY "/json_nlohmann_tests/all_unicode.json", TEST_DATA_DIRECTORY "/json.org/1.json", TEST_DATA_DIRECTORY "/json.org/2.json", TEST_DATA_DIRECTORY "/json.org/3.json", TEST_DATA_DIRECTORY "/json.org/4.json", TEST_DATA_DIRECTORY "/json.org/5.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip01.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip02.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip03.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip04.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip05.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip06.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip07.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip08.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip09.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip10.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip11.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip12.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip13.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip14.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip15.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip16.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip17.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip18.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip19.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip20.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip21.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip22.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip23.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip24.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip25.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip26.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip27.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip28.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip29.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip30.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip31.json", TEST_DATA_DIRECTORY "/json_roundtrip/roundtrip32.json", TEST_DATA_DIRECTORY "/json_testsuite/sample.json", // kills AppVeyor TEST_DATA_DIRECTORY "/json_tests/pass1.json", TEST_DATA_DIRECTORY "/json_tests/pass2.json", TEST_DATA_DIRECTORY "/json_tests/pass3.json", TEST_DATA_DIRECTORY "/regression/floats.json", TEST_DATA_DIRECTORY "/regression/signed_ints.json", TEST_DATA_DIRECTORY "/regression/unsigned_ints.json", TEST_DATA_DIRECTORY "/regression/working_file.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_arraysWithSpaces.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_empty-string.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_empty.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_ending_with_newline.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_false.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_heterogeneous.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_null.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_with_1_and_newline.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_with_leading_space.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_with_several_null.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_array_with_trailing_space.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_0e+1.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_0e1.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_after_space.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_double_close_to_zero.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_double_huge_neg_exp.json", //TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_huge_exp.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_int_with_exp.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_minus_zero.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_negative_int.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_negative_one.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_negative_zero.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_capital_e.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_capital_e_neg_exp.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_capital_e_pos_exp.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_exponent.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_fraction_exponent.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_neg_exp.json", //TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_neg_overflow.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_pos_exponent.json", //TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_pos_overflow.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_real_underflow.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_simple_int.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_simple_real.json", //TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_too_big_neg_int.json", //TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_too_big_pos_int.json", //TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_number_very_big_negative_int.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_basic.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_duplicated_key.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_duplicated_key_and_value.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_empty.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_empty_key.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_escaped_null_in_key.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_extreme_numbers.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_long_strings.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_simple.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_string_unicode.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_object_with_newlines.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_1_2_3_bytes_UTF-8_sequences.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_UTF-16_Surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_accepted_surrogate_pair.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_accepted_surrogate_pairs.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_allowed_escapes.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_backslash_and_u_escaped_zero.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_backslash_doublequotes.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_comments.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_double_escape_a.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_double_escape_n.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_escaped_control_character.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_escaped_noncharacter.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_in_array.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_in_array_with_leading_space.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_last_surrogates_1_and_2.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_newline_uescaped.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+10FFFF.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+1FFFF.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_nonCharacterInUTF-8_U+FFFF.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_null_escape.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_one-byte-utf-8.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_pi.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_simple_ascii.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_space.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_three-byte-utf-8.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_two-byte-utf-8.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_u+2028_line_sep.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_u+2029_par_sep.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_uEscape.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unescaped_char_delete.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unicode.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unicodeEscapedBackslash.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unicode_2.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unicode_U+2064_invisible_plus.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_unicode_escaped_double_quote.json", // TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_utf16.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_utf8.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_string_with_del_character.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_lonely_false.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_lonely_int.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_lonely_negative_real.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_lonely_null.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_lonely_string.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_lonely_true.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_string_empty.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_trailing_newline.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_true_in_array.json", TEST_DATA_DIRECTORY "/nst_json_testsuite/test_parsing/y_structure_whitespace_array.json" }) { CAPTURE(filename) { INFO_WITH_TEMP(filename + ": std::vector<uint8_t>"); // parse JSON file std::ifstream f_json(filename); json j1 = json::parse(f_json); // parse CBOR file const auto packed = utils::read_binary_file(filename + ".cbor"); json j2; CHECK_NOTHROW(j2 = json::from_cbor(packed)); // compare parsed JSON values CHECK(j1 == j2); } { INFO_WITH_TEMP(filename + ": std::ifstream"); // 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); json j2; CHECK_NOTHROW(j2 = json::from_cbor(f_cbor)); // compare parsed JSON values CHECK(j1 == j2); } { INFO_WITH_TEMP(filename + ": uint8_t* and size"); // parse JSON file std::ifstream f_json(filename); json j1 = json::parse(f_json); // parse CBOR file const auto packed = utils::read_binary_file(filename + ".cbor"); json j2; CHECK_NOTHROW(j2 = json::from_cbor({packed.data(), packed.size()})); // compare parsed JSON values CHECK(j1 == j2); } { INFO_WITH_TEMP(filename + ": output to output adapters"); // parse JSON file std::ifstream f_json(filename); json const j1 = json::parse(f_json); // parse CBOR file const auto packed = utils::read_binary_file(filename + ".cbor"); if (exclude_packed.count(filename) == 0u) { { INFO_WITH_TEMP(filename + ": output adapters: std::vector<uint8_t>"); std::vector<uint8_t> vec; json::to_cbor(j1, vec); CHECK(vec == packed); } } } } } } #if !defined(JSON_NOEXCEPTION) TEST_CASE("all CBOR first bytes") { // these bytes will fail immediately with exception parse_error.112 std::set<uint8_t> unsupported = { //// types not supported by this library // 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<uint8_t>(i); try { auto res = json::from_cbor(std::vector<uint8_t>(1, byte)); } catch (const json::parse_error& e) { // check that parse_error.112 is only thrown if the // first byte is in the unsupported set INFO_WITH_TEMP(e.what()); if (unsupported.find(byte) != unsupported.end()) { CHECK(e.id == 112); } else { CHECK(e.id != 112); } } } } #endif TEST_CASE("examples from RFC 7049 Appendix A") { SECTION("numbers") { CHECK(json::to_cbor(json::parse("0")) == std::vector<uint8_t>({0x00})); CHECK(json::parse("0") == json::from_cbor(std::vector<uint8_t>({0x00}))); CHECK(json::to_cbor(json::parse("1")) == std::vector<uint8_t>({0x01})); CHECK(json::parse("1") == json::from_cbor(std::vector<uint8_t>({0x01}))); CHECK(json::to_cbor(json::parse("10")) == std::vector<uint8_t>({0x0a})); CHECK(json::parse("10") == json::from_cbor(std::vector<uint8_t>({0x0a}))); CHECK(json::to_cbor(json::parse("23")) == std::vector<uint8_t>({0x17})); CHECK(json::parse("23") == json::from_cbor(std::vector<uint8_t>({0x17}))); CHECK(json::to_cbor(json::parse("24")) == std::vector<uint8_t>({0x18, 0x18})); CHECK(json::parse("24") == json::from_cbor(std::vector<uint8_t>({0x18, 0x18}))); CHECK(json::to_cbor(json::parse("25")) == std::vector<uint8_t>({0x18, 0x19})); CHECK(json::parse("25") == json::from_cbor(std::vector<uint8_t>({0x18, 0x19}))); CHECK(json::to_cbor(json::parse("100")) == std::vector<uint8_t>({0x18, 0x64})); CHECK(json::parse("100") == json::from_cbor(std::vector<uint8_t>({0x18, 0x64}))); CHECK(json::to_cbor(json::parse("1000")) == std::vector<uint8_t>({0x19, 0x03, 0xe8})); CHECK(json::parse("1000") == json::from_cbor(std::vector<uint8_t>({0x19, 0x03, 0xe8}))); CHECK(json::to_cbor(json::parse("1000000")) == std::vector<uint8_t>({0x1a, 0x00, 0x0f, 0x42, 0x40})); CHECK(json::parse("1000000") == json::from_cbor(std::vector<uint8_t>({0x1a, 0x00, 0x0f, 0x42, 0x40}))); CHECK(json::to_cbor(json::parse("1000000000000")) == std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0xe8, 0xd4, 0xa5, 0x10, 0x00})); CHECK(json::parse("1000000000000") == json::from_cbor(std::vector<uint8_t>({0x1b, 0x00, 0x00, 0x00, 0xe8, 0xd4, 0xa5, 0x10, 0x00}))); CHECK(json::to_cbor(json::parse("18446744073709551615")) == std::vector<uint8_t>({0x1b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})); CHECK(json::parse("18446744073709551615") == json::from_cbor(std::vector<uint8_t>({0x1b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}))); // positive bignum is not supported //CHECK(json::to_cbor(json::parse("18446744073709551616")) == std::vector<uint8_t>({0xc2, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})); //CHECK(json::parse("18446744073709551616") == json::from_cbor(std::vector<uint8_t>({0xc2, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}))); //CHECK(json::to_cbor(json::parse("-18446744073709551616")) == std::vector<uint8_t>({0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})); //CHECK(json::parse("-18446744073709551616") == json::from_cbor(std::vector<uint8_t>({0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}))); // negative bignum is not supported //CHECK(json::to_cbor(json::parse("-18446744073709551617")) == std::vector<uint8_t>({0xc3, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})); //CHECK(json::parse("-18446744073709551617") == json::from_cbor(std::vector<uint8_t>({0xc3, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}))); CHECK(json::to_cbor(json::parse("-1")) == std::vector<uint8_t>({0x20})); CHECK(json::parse("-1") == json::from_cbor(std::vector<uint8_t>({0x20}))); CHECK(json::to_cbor(json::parse("-10")) == std::vector<uint8_t>({0x29})); CHECK(json::parse("-10") == json::from_cbor(std::vector<uint8_t>({0x29}))); CHECK(json::to_cbor(json::parse("-100")) == std::vector<uint8_t>({0x38, 0x63})); CHECK(json::parse("-100") == json::from_cbor(std::vector<uint8_t>({0x38, 0x63}))); CHECK(json::to_cbor(json::parse("-1000")) == std::vector<uint8_t>({0x39, 0x03, 0xe7})); CHECK(json::parse("-1000") == json::from_cbor(std::vector<uint8_t>({0x39, 0x03, 0xe7}))); // half-precision float //CHECK(json::to_cbor(json::parse("0.0")) == std::vector<uint8_t>({0xf9, 0x00, 0x00})); CHECK(json::parse("0.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0x00, 0x00}))); // half-precision float //CHECK(json::to_cbor(json::parse("-0.0")) == std::vector<uint8_t>({0xf9, 0x80, 0x00})); CHECK(json::parse("-0.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0x80, 0x00}))); // half-precision float //CHECK(json::to_cbor(json::parse("1.0")) == std::vector<uint8_t>({0xf9, 0x3c, 0x00})); CHECK(json::parse("1.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0x3c, 0x00}))); CHECK(json::to_cbor(json::parse("1.1")) == std::vector<uint8_t>({0xfb, 0x3f, 0xf1, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a})); CHECK(json::parse("1.1") == json::from_cbor(std::vector<uint8_t>({0xfb, 0x3f, 0xf1, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a}))); // half-precision float //CHECK(json::to_cbor(json::parse("1.5")) == std::vector<uint8_t>({0xf9, 0x3e, 0x00})); CHECK(json::parse("1.5") == json::from_cbor(std::vector<uint8_t>({0xf9, 0x3e, 0x00}))); // half-precision float //CHECK(json::to_cbor(json::parse("65504.0")) == std::vector<uint8_t>({0xf9, 0x7b, 0xff})); CHECK(json::parse("65504.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0x7b, 0xff}))); //CHECK(json::to_cbor(json::parse("100000.0")) == std::vector<uint8_t>({0xfa, 0x47, 0xc3, 0x50, 0x00})); CHECK(json::parse("100000.0") == json::from_cbor(std::vector<uint8_t>({0xfa, 0x47, 0xc3, 0x50, 0x00}))); //CHECK(json::to_cbor(json::parse("3.4028234663852886e+38")) == std::vector<uint8_t>({0xfa, 0x7f, 0x7f, 0xff, 0xff})); CHECK(json::parse("3.4028234663852886e+38") == json::from_cbor(std::vector<uint8_t>({0xfa, 0x7f, 0x7f, 0xff, 0xff}))); CHECK(json::to_cbor(json::parse("1.0e+300")) == std::vector<uint8_t>({0xfb, 0x7e, 0x37, 0xe4, 0x3c, 0x88, 0x00, 0x75, 0x9c})); CHECK(json::parse("1.0e+300") == json::from_cbor(std::vector<uint8_t>({0xfb, 0x7e, 0x37, 0xe4, 0x3c, 0x88, 0x00, 0x75, 0x9c}))); // half-precision float //CHECK(json::to_cbor(json::parse("5.960464477539063e-8")) == std::vector<uint8_t>({0xf9, 0x00, 0x01})); CHECK(json::parse("-4.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0xc4, 0x00}))); // half-precision float //CHECK(json::to_cbor(json::parse("0.00006103515625")) == std::vector<uint8_t>({0xf9, 0x04, 0x00})); CHECK(json::parse("-4.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0xc4, 0x00}))); // half-precision float //CHECK(json::to_cbor(json::parse("-4.0")) == std::vector<uint8_t>({0xf9, 0xc4, 0x00})); CHECK(json::parse("-4.0") == json::from_cbor(std::vector<uint8_t>({0xf9, 0xc4, 0x00}))); CHECK(json::to_cbor(json::parse("-4.1")) == std::vector<uint8_t>({0xfb, 0xc0, 0x10, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66})); CHECK(json::parse("-4.1") == json::from_cbor(std::vector<uint8_t>({0xfb, 0xc0, 0x10, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}))); } SECTION("simple values") { CHECK(json::to_cbor(json::parse("false")) == std::vector<uint8_t>({0xf4})); CHECK(json::parse("false") == json::from_cbor(std::vector<uint8_t>({0xf4}))); CHECK(json::to_cbor(json::parse("true")) == std::vector<uint8_t>({0xf5})); CHECK(json::parse("true") == json::from_cbor(std::vector<uint8_t>({0xf5}))); CHECK(json::to_cbor(json::parse("true")) == std::vector<uint8_t>({0xf5})); CHECK(json::parse("true") == json::from_cbor(std::vector<uint8_t>({0xf5}))); } SECTION("strings") { CHECK(json::to_cbor(json::parse("\"\"")) == std::vector<uint8_t>({0x60})); CHECK(json::parse("\"\"") == json::from_cbor(std::vector<uint8_t>({0x60}))); CHECK(json::to_cbor(json::parse("\"a\"")) == std::vector<uint8_t>({0x61, 0x61})); CHECK(json::parse("\"a\"") == json::from_cbor(std::vector<uint8_t>({0x61, 0x61}))); CHECK(json::to_cbor(json::parse("\"IETF\"")) == std::vector<uint8_t>({0x64, 0x49, 0x45, 0x54, 0x46})); CHECK(json::parse("\"IETF\"") == json::from_cbor(std::vector<uint8_t>({0x64, 0x49, 0x45, 0x54, 0x46}))); CHECK(json::to_cbor(json::parse("\"\\u00fc\"")) == std::vector<uint8_t>({0x62, 0xc3, 0xbc})); CHECK(json::parse("\"\\u00fc\"") == json::from_cbor(std::vector<uint8_t>({0x62, 0xc3, 0xbc}))); CHECK(json::to_cbor(json::parse("\"\\u6c34\"")) == std::vector<uint8_t>({0x63, 0xe6, 0xb0, 0xb4})); CHECK(json::parse("\"\\u6c34\"") == json::from_cbor(std::vector<uint8_t>({0x63, 0xe6, 0xb0, 0xb4}))); CHECK(json::to_cbor(json::parse("\"\\ud800\\udd51\"")) == std::vector<uint8_t>({0x64, 0xf0, 0x90, 0x85, 0x91})); CHECK(json::parse("\"\\ud800\\udd51\"") == json::from_cbor(std::vector<uint8_t>({0x64, 0xf0, 0x90, 0x85, 0x91}))); // indefinite length strings CHECK(json::parse("\"streaming\"") == json::from_cbor(std::vector<uint8_t>({0x7f, 0x65, 0x73, 0x74, 0x72, 0x65, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0x67, 0xff}))); } SECTION("byte arrays") { const auto packed = utils::read_binary_file(TEST_DATA_DIRECTORY "/binary_data/cbor_binary.cbor"); json j; CHECK_NOTHROW(j = json::from_cbor(packed)); const auto expected = utils::read_binary_file(TEST_DATA_DIRECTORY "/binary_data/cbor_binary.out"); CHECK(j == json::binary(expected)); // 0xd8 CHECK(json::to_cbor(json::binary(std::vector<uint8_t> {}, 0x42)) == std::vector<uint8_t> {0xd8, 0x42, 0x40}); CHECK(!json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 0x42)), true, true, json::cbor_tag_handler_t::ignore).get_binary().has_subtype()); CHECK(json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 0x42)), true, true, json::cbor_tag_handler_t::store).get_binary().subtype() == 0x42); // 0xd9 CHECK(json::to_cbor(json::binary(std::vector<uint8_t> {}, 1000)) == std::vector<uint8_t> {0xd9, 0x03, 0xe8, 0x40}); CHECK(!json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 1000)), true, true, json::cbor_tag_handler_t::ignore).get_binary().has_subtype()); CHECK(json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 1000)), true, true, json::cbor_tag_handler_t::store).get_binary().subtype() == 1000); // 0xda CHECK(json::to_cbor(json::binary(std::vector<uint8_t> {}, 394216)) == std::vector<uint8_t> {0xda, 0x00, 0x06, 0x03, 0xe8, 0x40}); CHECK(!json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 394216)), true, true, json::cbor_tag_handler_t::ignore).get_binary().has_subtype()); CHECK(json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 394216)), true, true, json::cbor_tag_handler_t::store).get_binary().subtype() == 394216); // 0xdb CHECK(json::to_cbor(json::binary(std::vector<uint8_t> {}, 8589934590)) == std::vector<uint8_t> {0xdb, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xfe, 0x40}); CHECK(!json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 8589934590)), true, true, json::cbor_tag_handler_t::ignore).get_binary().has_subtype()); CHECK(json::from_cbor(json::to_cbor(json::binary(std::vector<uint8_t> {}, 8589934590)), true, true, json::cbor_tag_handler_t::store).get_binary().subtype() == 8589934590); } SECTION("arrays") { CHECK(json::to_cbor(json::parse("[]")) == std::vector<uint8_t>({0x80})); CHECK(json::parse("[]") == json::from_cbor(std::vector<uint8_t>({0x80}))); CHECK(json::to_cbor(json::parse("[1, 2, 3]")) == std::vector<uint8_t>({0x83, 0x01, 0x02, 0x03})); CHECK(json::parse("[1, 2, 3]") == json::from_cbor(std::vector<uint8_t>({0x83, 0x01, 0x02, 0x03}))); CHECK(json::to_cbor(json::parse("[1, [2, 3], [4, 5]]")) == std::vector<uint8_t>({0x83, 0x01, 0x82, 0x02, 0x03, 0x82, 0x04, 0x05})); CHECK(json::parse("[1, [2, 3], [4, 5]]") == json::from_cbor(std::vector<uint8_t>({0x83, 0x01, 0x82, 0x02, 0x03, 0x82, 0x04, 0x05}))); CHECK(json::to_cbor(json::parse("[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]")) == std::vector<uint8_t>({0x98, 0x19, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x18, 0x19})); CHECK(json::parse("[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]") == json::from_cbor(std::vector<uint8_t>({0x98, 0x19, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x18, 0x19}))); // indefinite length arrays CHECK(json::parse("[]") == json::from_cbor(std::vector<uint8_t>({0x9f, 0xff}))); CHECK(json::parse("[1, [2, 3], [4, 5]] ") == json::from_cbor(std::vector<uint8_t>({0x9f, 0x01, 0x82, 0x02, 0x03, 0x9f, 0x04, 0x05, 0xff, 0xff}))); CHECK(json::parse("[1, [2, 3], [4, 5]]") == json::from_cbor(std::vector<uint8_t>({0x9f, 0x01, 0x82, 0x02, 0x03, 0x82, 0x04, 0x05, 0xff}))); CHECK(json::parse("[1, [2, 3], [4, 5]]") == json::from_cbor(std::vector<uint8_t>({0x83, 0x01, 0x82, 0x02, 0x03, 0x9f, 0x04, 0x05, 0xff}))); CHECK(json::parse("[1, [2, 3], [4, 5]]") == json::from_cbor(std::vector<uint8_t>({0x83, 0x01, 0x9f, 0x02, 0x03, 0xff, 0x82, 0x04, 0x05}))); CHECK(json::parse("[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]") == json::from_cbor(std::vector<uint8_t>({0x9f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x18, 0x19, 0xff}))); } SECTION("objects") { CHECK(json::to_cbor(json::parse("{}")) == std::vector<uint8_t>({0xa0})); CHECK(json::parse("{}") == json::from_cbor(std::vector<uint8_t>({0xa0}))); CHECK(json::to_cbor(json::parse("{\"a\": 1, \"b\": [2, 3]}")) == std::vector<uint8_t>({0xa2, 0x61, 0x61, 0x01, 0x61, 0x62, 0x82, 0x02, 0x03})); CHECK(json::parse("{\"a\": 1, \"b\": [2, 3]}") == json::from_cbor(std::vector<uint8_t>({0xa2, 0x61, 0x61, 0x01, 0x61, 0x62, 0x82, 0x02, 0x03}))); CHECK(json::to_cbor(json::parse("[\"a\", {\"b\": \"c\"}]")) == std::vector<uint8_t>({0x82, 0x61, 0x61, 0xa1, 0x61, 0x62, 0x61, 0x63})); CHECK(json::parse("[\"a\", {\"b\": \"c\"}]") == json::from_cbor(std::vector<uint8_t>({0x82, 0x61, 0x61, 0xa1, 0x61, 0x62, 0x61, 0x63}))); CHECK(json::to_cbor(json::parse("{\"a\": \"A\", \"b\": \"B\", \"c\": \"C\", \"d\": \"D\", \"e\": \"E\"}")) == std::vector<uint8_t>({0xa5, 0x61, 0x61, 0x61, 0x41, 0x61, 0x62, 0x61, 0x42, 0x61, 0x63, 0x61, 0x43, 0x61, 0x64, 0x61, 0x44, 0x61, 0x65, 0x61, 0x45})); CHECK(json::parse("{\"a\": \"A\", \"b\": \"B\", \"c\": \"C\", \"d\": \"D\", \"e\": \"E\"}") == json::from_cbor(std::vector<uint8_t>({0xa5, 0x61, 0x61, 0x61, 0x41, 0x61, 0x62, 0x61, 0x42, 0x61, 0x63, 0x61, 0x43, 0x61, 0x64, 0x61, 0x44, 0x61, 0x65, 0x61, 0x45}))); // indefinite length objects CHECK(json::parse("{\"a\": 1, \"b\": [2, 3]}") == json::from_cbor(std::vector<uint8_t>({0xbf, 0x61, 0x61, 0x01, 0x61, 0x62, 0x9f, 0x02, 0x03, 0xff, 0xff}))); CHECK(json::parse("[\"a\", {\"b\": \"c\"}]") == json::from_cbor(std::vector<uint8_t>({0x82, 0x61, 0x61, 0xbf, 0x61, 0x62, 0x61, 0x63, 0xff}))); CHECK(json::parse("{\"Fun\": true, \"Amt\": -2}") == json::from_cbor(std::vector<uint8_t>({0xbf, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0xff}))); } } TEST_CASE("Tagged values") { const json j = "s"; auto v = json::to_cbor(j); SECTION("0xC6..0xD4") { for (const auto b : std::vector<std::uint8_t> { 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4 }) { CAPTURE(b); // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), b); // check that parsing fails in error mode json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); // check that parsing succeeds and gets original value in ignore mode auto j_tagged = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore); CHECK(j_tagged == j); auto j_tagged_stored = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::store); CHECK(j_tagged_stored == j); } } SECTION("0xD8 - 1 byte follows") { SECTION("success") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x42); // 1 byte v_tagged.insert(v_tagged.begin(), 0xD8); // tag // check that parsing fails in error mode json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); // check that parsing succeeds and gets original value in ignore mode auto j_tagged = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore); CHECK(j_tagged == j); } SECTION("missing byte after tag") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0xD8); // tag // check that parsing fails in all modes json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore), json::parse_error); } } SECTION("0xD9 - 2 byte follow") { SECTION("success") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x42); // 1 byte v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0xD9); // tag // check that parsing fails in error mode json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); // check that parsing succeeds and gets original value in ignore mode auto j_tagged = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore); CHECK(j_tagged == j); } SECTION("missing byte after tag") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0xD9); // tag // check that parsing fails in all modes json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore), json::parse_error); } } SECTION("0xDA - 4 bytes follow") { SECTION("success") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x42); // 1 byte v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0x22); // 1 byte v_tagged.insert(v_tagged.begin(), 0x11); // 1 byte v_tagged.insert(v_tagged.begin(), 0xDA); // tag // check that parsing fails in error mode json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); // check that parsing succeeds and gets original value in ignore mode auto j_tagged = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore); CHECK(j_tagged == j); } SECTION("missing bytes after tag") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0x22); // 1 byte v_tagged.insert(v_tagged.begin(), 0x11); // 1 byte v_tagged.insert(v_tagged.begin(), 0xDA); // tag // check that parsing fails in all modes json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore), json::parse_error); } } SECTION("0xDB - 8 bytes follow") { SECTION("success") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x42); // 1 byte v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0x22); // 1 byte v_tagged.insert(v_tagged.begin(), 0x11); // 1 byte v_tagged.insert(v_tagged.begin(), 0x42); // 1 byte v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0x22); // 1 byte v_tagged.insert(v_tagged.begin(), 0x11); // 1 byte v_tagged.insert(v_tagged.begin(), 0xDB); // tag // check that parsing fails in error mode json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); // check that parsing succeeds and gets original value in ignore mode auto j_tagged = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore); CHECK(j_tagged == j); } SECTION("missing byte after tag") { // add tag to value auto v_tagged = v; v_tagged.insert(v_tagged.begin(), 0x42); // 1 byte v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0x22); // 1 byte v_tagged.insert(v_tagged.begin(), 0x11); // 1 byte v_tagged.insert(v_tagged.begin(), 0x23); // 1 byte v_tagged.insert(v_tagged.begin(), 0x22); // 1 byte v_tagged.insert(v_tagged.begin(), 0x11); // 1 byte v_tagged.insert(v_tagged.begin(), 0xDB); // tag // check that parsing fails in all modes json _; CHECK_THROWS_AS(_ = json::from_cbor(v_tagged), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::error), json::parse_error); CHECK_THROWS_AS(_ = json::from_cbor(v_tagged, true, true, json::cbor_tag_handler_t::ignore), json::parse_error); } } SECTION("tagged binary") { // create a binary value of subtype 42 json j_binary; j_binary["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to CBOR const auto vec = json::to_cbor(j_binary); CHECK(vec == std::vector<std::uint8_t> {0xA1, 0x66, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79, 0xD8, 0x2A, 0x44, 0xCA, 0xFE, 0xBA, 0xBE}); // parse error when parsing tagged value json _; CHECK_THROWS_WITH_AS(_ = json::from_cbor(vec), "[json.exception.parse_error.112] parse error at byte 9: syntax error while parsing CBOR value: invalid byte: 0xD8", json::parse_error); // binary without subtype when tags are ignored json jb = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore); CHECK(jb.is_object()); CHECK(jb["binary"].is_binary()); CHECK(!jb["binary"].get_binary().has_subtype()); } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-element_access2.cpp
.cpp
96,001
1,795
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // Copyright (c) 2013-2022 Niels Lohmann <http://nlohmann.me>. // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #include <nlohmann/json.hpp> #ifdef JSON_TEST_NO_GLOBAL_UDLS using namespace nlohmann::literals; // NOLINT(google-build-using-namespace) #endif // build test with C++14 // JSON_HAS_CPP_14 TEST_CASE_TEMPLATE("element access 2", Json, nlohmann::json, nlohmann::ordered_json) { SECTION("object") { 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 = j; SECTION("access specified element with bounds checking") { SECTION("access within bounds") { CHECK(j.at("integer") == Json(1)); CHECK(j.at("unsigned") == Json(1u)); CHECK(j.at("boolean") == Json(true)); CHECK(j.at("null") == Json(nullptr)); CHECK(j.at("string") == Json("hello world")); CHECK(j.at("floating") == Json(42.23)); CHECK(j.at("object") == Json::object()); CHECK(j.at("array") == Json({1, 2, 3})); CHECK(j_const.at("integer") == Json(1)); CHECK(j_const.at("unsigned") == Json(1u)); CHECK(j_const.at("boolean") == Json(true)); CHECK(j_const.at("null") == Json(nullptr)); CHECK(j_const.at("string") == Json("hello world")); CHECK(j_const.at("floating") == Json(42.23)); CHECK(j_const.at("object") == Json::object()); CHECK(j_const.at("array") == Json({1, 2, 3})); #ifdef JSON_HAS_CPP_17 CHECK(j.at(std::string_view("integer")) == Json(1)); CHECK(j.at(std::string_view("unsigned")) == Json(1u)); CHECK(j.at(std::string_view("boolean")) == Json(true)); CHECK(j.at(std::string_view("null")) == Json(nullptr)); CHECK(j.at(std::string_view("string")) == Json("hello world")); CHECK(j.at(std::string_view("floating")) == Json(42.23)); CHECK(j.at(std::string_view("object")) == Json::object()); CHECK(j.at(std::string_view("array")) == Json({1, 2, 3})); CHECK(j_const.at(std::string_view("integer")) == Json(1)); CHECK(j_const.at(std::string_view("unsigned")) == Json(1u)); CHECK(j_const.at(std::string_view("boolean")) == Json(true)); CHECK(j_const.at(std::string_view("null")) == Json(nullptr)); CHECK(j_const.at(std::string_view("string")) == Json("hello world")); CHECK(j_const.at(std::string_view("floating")) == Json(42.23)); CHECK(j_const.at(std::string_view("object")) == Json::object()); CHECK(j_const.at(std::string_view("array")) == Json({1, 2, 3})); #endif } SECTION("access outside bounds") { CHECK_THROWS_WITH_AS(j.at("foo"), "[json.exception.out_of_range.403] key 'foo' not found", typename Json::out_of_range&); CHECK_THROWS_WITH_AS(j_const.at("foo"), "[json.exception.out_of_range.403] key 'foo' not found", typename Json::out_of_range&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j.at(std::string_view("foo")), "[json.exception.out_of_range.403] key 'foo' not found", typename Json::out_of_range&); CHECK_THROWS_WITH_AS(j_const.at(std::string_view("foo")), "[json.exception.out_of_range.403] key 'foo' not found", typename Json::out_of_range&); #endif } SECTION("access on non-object type") { SECTION("null") { Json j_nonobject(Json::value_t::null); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with null", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view(std::string_view("foo"))), "[json.exception.type_error.304] cannot use at() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view(std::string_view("foo"))), "[json.exception.type_error.304] cannot use at() with null", typename Json::type_error&); #endif } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with boolean", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with boolean", typename Json::type_error&); #endif } SECTION("string") { Json j_nonobject(Json::value_t::string); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with string", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with string", typename Json::type_error&); #endif } SECTION("array") { Json j_nonobject(Json::value_t::array); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with array", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with array", typename Json::type_error&); #endif } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); #endif } SECTION("number (unsigned)") { Json j_nonobject(Json::value_t::number_unsigned); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); #endif } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); const Json j_nonobject_const(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject.at("foo"), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at("foo"), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.at(std::string_view("foo")), "[json.exception.type_error.304] cannot use at() with number", typename Json::type_error&); #endif } } } SECTION("access specified element with default value") { SECTION("given a key") { SECTION("access existing value") { CHECK(j.value("integer", 2) == 1); CHECK(j.value("integer", 1.0) == Approx(1)); CHECK(j.value("unsigned", 2) == 1u); CHECK(j.value("unsigned", 1.0) == Approx(1u)); CHECK(j.value("null", Json(1)) == Json()); CHECK(j.value("boolean", false) == true); CHECK(j.value("string", "bar") == "hello world"); CHECK(j.value("string", std::string("bar")) == "hello world"); CHECK(j.value("floating", 12.34) == Approx(42.23)); CHECK(j.value("floating", 12) == 42); CHECK(j.value("object", Json({{"foo", "bar"}})) == Json::object()); CHECK(j.value("array", Json({10, 100})) == Json({1, 2, 3})); CHECK(j_const.value("integer", 2) == 1); CHECK(j_const.value("integer", 1.0) == Approx(1)); CHECK(j_const.value("unsigned", 2) == 1u); CHECK(j_const.value("unsigned", 1.0) == Approx(1u)); CHECK(j_const.value("boolean", false) == true); CHECK(j_const.value("string", "bar") == "hello world"); CHECK(j_const.value("string", std::string("bar")) == "hello world"); CHECK(j_const.value("floating", 12.34) == Approx(42.23)); CHECK(j_const.value("floating", 12) == 42); CHECK(j_const.value("object", Json({{"foo", "bar"}})) == Json::object()); CHECK(j_const.value("array", Json({10, 100})) == Json({1, 2, 3})); #ifdef JSON_HAS_CPP_17 CHECK(j.value(std::string_view("integer"), 2) == 1); CHECK(j.value(std::string_view("integer"), 1.0) == Approx(1)); CHECK(j.value(std::string_view("unsigned"), 2) == 1u); CHECK(j.value(std::string_view("unsigned"), 1.0) == Approx(1u)); CHECK(j.value(std::string_view("null"), Json(1)) == Json()); CHECK(j.value(std::string_view("boolean"), false) == true); CHECK(j.value(std::string_view("string"), "bar") == "hello world"); CHECK(j.value(std::string_view("string"), std::string("bar")) == "hello world"); CHECK(j.value(std::string_view("floating"), 12.34) == Approx(42.23)); CHECK(j.value(std::string_view("floating"), 12) == 42); CHECK(j.value(std::string_view("object"), Json({{"foo", "bar"}})) == Json::object()); CHECK(j.value(std::string_view("array"), Json({10, 100})) == Json({1, 2, 3})); CHECK(j_const.value(std::string_view("integer"), 2) == 1); CHECK(j_const.value(std::string_view("integer"), 1.0) == Approx(1)); CHECK(j_const.value(std::string_view("unsigned"), 2) == 1u); CHECK(j_const.value(std::string_view("unsigned"), 1.0) == Approx(1u)); CHECK(j_const.value(std::string_view("boolean"), false) == true); CHECK(j_const.value(std::string_view("string"), "bar") == "hello world"); CHECK(j_const.value(std::string_view("string"), std::string("bar")) == "hello world"); CHECK(j_const.value(std::string_view("floating"), 12.34) == Approx(42.23)); CHECK(j_const.value(std::string_view("floating"), 12) == 42); CHECK(j_const.value(std::string_view("object"), Json({{"foo", "bar"}})) == Json::object()); CHECK(j_const.value(std::string_view("array"), Json({10, 100})) == Json({1, 2, 3})); #endif } SECTION("access non-existing value") { CHECK(j.value("_", 2) == 2); CHECK(j.value("_", 2u) == 2u); CHECK(j.value("_", false) == false); CHECK(j.value("_", "bar") == "bar"); CHECK(j.value("_", 12.34) == Approx(12.34)); CHECK(j.value("_", Json({{"foo", "bar"}})) == Json({{"foo", "bar"}})); CHECK(j.value("_", Json({10, 100})) == Json({10, 100})); CHECK(j_const.value("_", 2) == 2); CHECK(j_const.value("_", 2u) == 2u); CHECK(j_const.value("_", false) == false); CHECK(j_const.value("_", "bar") == "bar"); CHECK(j_const.value("_", 12.34) == Approx(12.34)); CHECK(j_const.value("_", Json({{"foo", "bar"}})) == Json({{"foo", "bar"}})); CHECK(j_const.value("_", Json({10, 100})) == Json({10, 100})); #ifdef JSON_HAS_CPP_17 CHECK(j.value(std::string_view("_"), 2) == 2); CHECK(j.value(std::string_view("_"), 2u) == 2u); CHECK(j.value(std::string_view("_"), false) == false); CHECK(j.value(std::string_view("_"), "bar") == "bar"); CHECK(j.value(std::string_view("_"), 12.34) == Approx(12.34)); CHECK(j.value(std::string_view("_"), Json({{"foo", "bar"}})) == Json({{"foo", "bar"}})); CHECK(j.value(std::string_view("_"), Json({10, 100})) == Json({10, 100})); CHECK(j_const.value(std::string_view("_"), 2) == 2); CHECK(j_const.value(std::string_view("_"), 2u) == 2u); CHECK(j_const.value(std::string_view("_"), false) == false); CHECK(j_const.value(std::string_view("_"), "bar") == "bar"); CHECK(j_const.value(std::string_view("_"), 12.34) == Approx(12.34)); CHECK(j_const.value(std::string_view("_"), Json({{"foo", "bar"}})) == Json({{"foo", "bar"}})); CHECK(j_const.value(std::string_view("_"), Json({10, 100})) == Json({10, 100})); #endif } SECTION("access on non-object type") { SECTION("null") { Json j_nonobject(Json::value_t::null); const Json j_nonobject_const(Json::value_t::null); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); #endif } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); const Json j_nonobject_const(Json::value_t::boolean); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with boolean", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with boolean", typename Json::type_error&); #endif } SECTION("string") { Json j_nonobject(Json::value_t::string); const Json j_nonobject_const(Json::value_t::string); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with string", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with string", typename Json::type_error&); #endif } SECTION("array") { Json j_nonobject(Json::value_t::array); const Json j_nonobject_const(Json::value_t::array); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with array", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with array", typename Json::type_error&); #endif } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); const Json j_nonobject_const(Json::value_t::number_integer); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); #endif } SECTION("number (unsigned)") { Json j_nonobject(Json::value_t::number_unsigned); const Json j_nonobject_const(Json::value_t::number_unsigned); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); #endif } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); const Json j_nonobject_const(Json::value_t::number_float); CHECK_THROWS_WITH_AS(j_nonobject.value("foo", 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("foo", 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value(std::string_view("foo"), 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); #endif } } } SECTION("given a JSON pointer") { SECTION("access existing value") { CHECK(j.value("/integer"_json_pointer, 2) == 1); CHECK(j.value("/integer"_json_pointer, 1.0) == Approx(1)); CHECK(j.value("/unsigned"_json_pointer, 2) == 1u); CHECK(j.value("/unsigned"_json_pointer, 1.0) == Approx(1u)); CHECK(j.value("/null"_json_pointer, Json(1)) == Json()); CHECK(j.value("/boolean"_json_pointer, false) == true); CHECK(j.value("/string"_json_pointer, "bar") == "hello world"); CHECK(j.value("/string"_json_pointer, std::string("bar")) == "hello world"); CHECK(j.value("/floating"_json_pointer, 12.34) == Approx(42.23)); CHECK(j.value("/floating"_json_pointer, 12) == 42); CHECK(j.value("/object"_json_pointer, Json({{"foo", "bar"}})) == Json::object()); CHECK(j.value("/array"_json_pointer, Json({10, 100})) == Json({1, 2, 3})); CHECK(j_const.value("/integer"_json_pointer, 2) == 1); CHECK(j_const.value("/integer"_json_pointer, 1.0) == Approx(1)); CHECK(j_const.value("/unsigned"_json_pointer, 2) == 1u); CHECK(j_const.value("/unsigned"_json_pointer, 1.0) == Approx(1u)); CHECK(j_const.value("/boolean"_json_pointer, false) == true); CHECK(j_const.value("/string"_json_pointer, "bar") == "hello world"); CHECK(j_const.value("/string"_json_pointer, std::string("bar")) == "hello world"); CHECK(j_const.value("/floating"_json_pointer, 12.34) == Approx(42.23)); CHECK(j_const.value("/floating"_json_pointer, 12) == 42); CHECK(j_const.value("/object"_json_pointer, Json({{"foo", "bar"}})) == Json::object()); CHECK(j_const.value("/array"_json_pointer, Json({10, 100})) == Json({1, 2, 3})); } SECTION("access on non-object type") { SECTION("null") { Json j_nonobject(Json::value_t::null); const Json j_nonobject_const(Json::value_t::null); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); const Json j_nonobject_const(Json::value_t::boolean); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with boolean", typename Json::type_error&); } SECTION("string") { Json j_nonobject(Json::value_t::string); const Json j_nonobject_const(Json::value_t::string); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with string", typename Json::type_error&); } SECTION("array") { Json j_nonobject(Json::value_t::array); const Json j_nonobject_const(Json::value_t::array); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with array", typename Json::type_error&); } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); const Json j_nonobject_const(Json::value_t::number_integer); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); } SECTION("number (unsigned)") { Json j_nonobject(Json::value_t::number_unsigned); const Json j_nonobject_const(Json::value_t::number_unsigned); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); const Json j_nonobject_const(Json::value_t::number_float); CHECK_THROWS_WITH_AS(j_nonobject.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject_const.value("/foo"_json_pointer, 1), "[json.exception.type_error.306] cannot use value() with number", typename Json::type_error&); } } } } SECTION("non-const operator[]") { { Json j_null; CHECK(j_null.is_null()); j_null["key"] = 1; CHECK(j_null.is_object()); CHECK(j_null.size() == 1); j_null["key"] = 2; CHECK(j_null.size() == 1); } #ifdef JSON_HAS_CPP_17 { std::string_view const key = "key"; Json j_null; CHECK(j_null.is_null()); j_null[key] = 1; CHECK(j_null.is_object()); CHECK(j_null.size() == 1); j_null[key] = 2; CHECK(j_null.size() == 1); } #endif } SECTION("front and back") { if (std::is_same<Json, nlohmann::ordered_json>::value) { // "integer" is the first key CHECK(j.front() == Json(1)); CHECK(j_const.front() == Json(1)); // "array" is last key CHECK(j.back() == Json({1, 2, 3})); CHECK(j_const.back() == Json({1, 2, 3})); } else { // "array" is the smallest key CHECK(j.front() == Json({1, 2, 3})); CHECK(j_const.front() == Json({1, 2, 3})); // "unsigned" is the largest key CHECK(j.back() == Json(1u)); CHECK(j_const.back() == Json(1u)); } } SECTION("access specified element") { SECTION("access within bounds") { CHECK(j["integer"] == Json(1)); CHECK(j[typename Json::object_t::key_type("integer")] == j["integer"]); CHECK(j["unsigned"] == Json(1u)); CHECK(j[typename Json::object_t::key_type("unsigned")] == j["unsigned"]); CHECK(j["boolean"] == Json(true)); CHECK(j[typename Json::object_t::key_type("boolean")] == j["boolean"]); CHECK(j["null"] == Json(nullptr)); CHECK(j[typename Json::object_t::key_type("null")] == j["null"]); CHECK(j["string"] == Json("hello world")); CHECK(j[typename Json::object_t::key_type("string")] == j["string"]); CHECK(j["floating"] == Json(42.23)); CHECK(j[typename Json::object_t::key_type("floating")] == j["floating"]); CHECK(j["object"] == Json::object()); CHECK(j[typename Json::object_t::key_type("object")] == j["object"]); CHECK(j["array"] == Json({1, 2, 3})); CHECK(j[typename Json::object_t::key_type("array")] == j["array"]); CHECK(j_const["integer"] == Json(1)); CHECK(j_const[typename Json::object_t::key_type("integer")] == j["integer"]); CHECK(j_const["boolean"] == Json(true)); CHECK(j_const[typename Json::object_t::key_type("boolean")] == j["boolean"]); CHECK(j_const["null"] == Json(nullptr)); CHECK(j_const[typename Json::object_t::key_type("null")] == j["null"]); CHECK(j_const["string"] == Json("hello world")); CHECK(j_const[typename Json::object_t::key_type("string")] == j["string"]); CHECK(j_const["floating"] == Json(42.23)); CHECK(j_const[typename Json::object_t::key_type("floating")] == j["floating"]); CHECK(j_const["object"] == Json::object()); CHECK(j_const[typename Json::object_t::key_type("object")] == j["object"]); CHECK(j_const["array"] == Json({1, 2, 3})); CHECK(j_const[typename Json::object_t::key_type("array")] == j["array"]); } #ifdef JSON_HAS_CPP_17 SECTION("access within bounds (string_view)") { CHECK(j["integer"] == Json(1)); CHECK(j[std::string_view("integer")] == j["integer"]); CHECK(j["unsigned"] == Json(1u)); CHECK(j[std::string_view("unsigned")] == j["unsigned"]); CHECK(j["boolean"] == Json(true)); CHECK(j[std::string_view("boolean")] == j["boolean"]); CHECK(j["null"] == Json(nullptr)); CHECK(j[std::string_view("null")] == j["null"]); CHECK(j["string"] == Json("hello world")); CHECK(j[std::string_view("string")] == j["string"]); CHECK(j["floating"] == Json(42.23)); CHECK(j[std::string_view("floating")] == j["floating"]); CHECK(j["object"] == Json::object()); CHECK(j[std::string_view("object")] == j["object"]); CHECK(j["array"] == Json({1, 2, 3})); CHECK(j[std::string_view("array")] == j["array"]); CHECK(j_const["integer"] == Json(1)); CHECK(j_const[std::string_view("integer")] == j["integer"]); CHECK(j_const["boolean"] == Json(true)); CHECK(j_const[std::string_view("boolean")] == j["boolean"]); CHECK(j_const["null"] == Json(nullptr)); CHECK(j_const[std::string_view("null")] == j["null"]); CHECK(j_const["string"] == Json("hello world")); CHECK(j_const[std::string_view("string")] == j["string"]); CHECK(j_const["floating"] == Json(42.23)); CHECK(j_const[std::string_view("floating")] == j["floating"]); CHECK(j_const["object"] == Json::object()); CHECK(j_const[std::string_view("object")] == j["object"]); CHECK(j_const["array"] == Json({1, 2, 3})); CHECK(j_const[std::string_view("array")] == j["array"]); } #endif SECTION("access on non-object type") { SECTION("null") { Json j_nonobject(Json::value_t::null); Json j_nonobject2(Json::value_t::null); const Json j_const_nonobject(j_nonobject); CHECK_NOTHROW(j_nonobject["foo"]); CHECK_NOTHROW(j_nonobject2[typename Json::object_t::key_type("foo")]); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with null", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_NOTHROW(j_nonobject2[std::string_view("foo")]); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with null", typename Json::type_error&); #endif } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); const Json j_const_nonobject(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with boolean", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with boolean", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with boolean", typename Json::type_error&); #endif } SECTION("string") { Json j_nonobject(Json::value_t::string); const Json j_const_nonobject(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with string", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with string", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with string", typename Json::type_error&); #endif } SECTION("array") { Json j_nonobject(Json::value_t::array); const Json j_const_nonobject(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with array", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with array", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with array", typename Json::type_error&); #endif } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); const Json j_const_nonobject(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); #endif } SECTION("number (unsigned)") { Json j_nonobject(Json::value_t::number_unsigned); const Json j_const_nonobject(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); #endif } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); const Json j_const_nonobject(j_nonobject); CHECK_THROWS_WITH_AS(j_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject["foo"], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[typename Json::object_t::key_type("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); CHECK_THROWS_WITH_AS(j_const_nonobject[std::string_view("foo")], "[json.exception.type_error.305] cannot use operator[] with a string argument with number", typename Json::type_error&); #endif } } } SECTION("remove specified element") { SECTION("remove element by key") { CHECK(j.find("integer") != j.end()); CHECK(j.erase("integer") == 1); CHECK(j.find("integer") == j.end()); CHECK(j.erase("integer") == 0); CHECK(j.find("unsigned") != j.end()); CHECK(j.erase("unsigned") == 1); CHECK(j.find("unsigned") == j.end()); CHECK(j.erase("unsigned") == 0); CHECK(j.find("boolean") != j.end()); CHECK(j.erase("boolean") == 1); CHECK(j.find("boolean") == j.end()); CHECK(j.erase("boolean") == 0); CHECK(j.find("null") != j.end()); CHECK(j.erase("null") == 1); CHECK(j.find("null") == j.end()); CHECK(j.erase("null") == 0); CHECK(j.find("string") != j.end()); CHECK(j.erase("string") == 1); CHECK(j.find("string") == j.end()); CHECK(j.erase("string") == 0); CHECK(j.find("floating") != j.end()); CHECK(j.erase("floating") == 1); CHECK(j.find("floating") == j.end()); CHECK(j.erase("floating") == 0); CHECK(j.find("object") != j.end()); CHECK(j.erase("object") == 1); CHECK(j.find("object") == j.end()); CHECK(j.erase("object") == 0); CHECK(j.find("array") != j.end()); CHECK(j.erase("array") == 1); CHECK(j.find("array") == j.end()); CHECK(j.erase("array") == 0); } #ifdef JSON_HAS_CPP_17 SECTION("remove element by key (string_view)") { CHECK(j.find(std::string_view("integer")) != j.end()); CHECK(j.erase(std::string_view("integer")) == 1); CHECK(j.find(std::string_view("integer")) == j.end()); CHECK(j.erase(std::string_view("integer")) == 0); CHECK(j.find(std::string_view("unsigned")) != j.end()); CHECK(j.erase(std::string_view("unsigned")) == 1); CHECK(j.find(std::string_view("unsigned")) == j.end()); CHECK(j.erase(std::string_view("unsigned")) == 0); CHECK(j.find(std::string_view("boolean")) != j.end()); CHECK(j.erase(std::string_view("boolean")) == 1); CHECK(j.find(std::string_view("boolean")) == j.end()); CHECK(j.erase(std::string_view("boolean")) == 0); CHECK(j.find(std::string_view("null")) != j.end()); CHECK(j.erase(std::string_view("null")) == 1); CHECK(j.find(std::string_view("null")) == j.end()); CHECK(j.erase(std::string_view("null")) == 0); CHECK(j.find(std::string_view("string")) != j.end()); CHECK(j.erase(std::string_view("string")) == 1); CHECK(j.find(std::string_view("string")) == j.end()); CHECK(j.erase(std::string_view("string")) == 0); CHECK(j.find(std::string_view("floating")) != j.end()); CHECK(j.erase(std::string_view("floating")) == 1); CHECK(j.find(std::string_view("floating")) == j.end()); CHECK(j.erase(std::string_view("floating")) == 0); CHECK(j.find(std::string_view("object")) != j.end()); CHECK(j.erase(std::string_view("object")) == 1); CHECK(j.find(std::string_view("object")) == j.end()); CHECK(j.erase(std::string_view("object")) == 0); CHECK(j.find(std::string_view("array")) != j.end()); CHECK(j.erase(std::string_view("array")) == 1); CHECK(j.find(std::string_view("array")) == j.end()); CHECK(j.erase(std::string_view("array")) == 0); } #endif SECTION("remove element by iterator") { SECTION("erase(begin())") { { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::iterator const it2 = jobject.erase(jobject.begin()); CHECK(jobject == Json({{"b", 1}, {"c", 17u}})); CHECK(*it2 == Json(1)); } { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::const_iterator const it2 = jobject.erase(jobject.cbegin()); CHECK(jobject == Json({{"b", 1}, {"c", 17u}})); CHECK(*it2 == Json(1)); } } SECTION("erase(begin(), end())") { { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::iterator it2 = jobject.erase(jobject.begin(), jobject.end()); CHECK(jobject == Json::object()); CHECK(it2 == jobject.end()); } { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::const_iterator it2 = jobject.erase(jobject.cbegin(), jobject.cend()); CHECK(jobject == Json::object()); CHECK(it2 == jobject.cend()); } } SECTION("erase(begin(), begin())") { { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::iterator const it2 = jobject.erase(jobject.begin(), jobject.begin()); CHECK(jobject == Json({{"a", "a"}, {"b", 1}, {"c", 17u}})); CHECK(*it2 == Json("a")); } { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::const_iterator const it2 = jobject.erase(jobject.cbegin(), jobject.cbegin()); CHECK(jobject == Json({{"a", "a"}, {"b", 1}, {"c", 17u}})); CHECK(*it2 == Json("a")); } } SECTION("erase at offset") { { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::iterator const it = jobject.find("b"); typename Json::iterator const it2 = jobject.erase(it); CHECK(jobject == Json({{"a", "a"}, {"c", 17u}})); CHECK(*it2 == Json(17)); } { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}}; typename Json::const_iterator const it = jobject.find("b"); typename Json::const_iterator const it2 = jobject.erase(it); CHECK(jobject == Json({{"a", "a"}, {"c", 17u}})); CHECK(*it2 == Json(17)); } } SECTION("erase subrange") { { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; typename Json::iterator const it2 = jobject.erase(jobject.find("b"), jobject.find("e")); CHECK(jobject == Json({{"a", "a"}, {"e", true}})); CHECK(*it2 == Json(true)); } { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; typename Json::const_iterator const it2 = jobject.erase(jobject.find("b"), jobject.find("e")); CHECK(jobject == Json({{"a", "a"}, {"e", true}})); CHECK(*it2 == Json(true)); } } SECTION("different objects") { { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; Json jobject2 = {{"a", "a"}, {"b", 1}, {"c", 17u}}; CHECK_THROWS_WITH_AS(jobject.erase(jobject2.begin()), "[json.exception.invalid_iterator.202] iterator does not fit current value", typename Json::invalid_iterator&); CHECK_THROWS_WITH_AS(jobject.erase(jobject.begin(), jobject2.end()), "[json.exception.invalid_iterator.203] iterators do not fit current value", typename Json::invalid_iterator&); CHECK_THROWS_WITH_AS(jobject.erase(jobject2.begin(), jobject.end()), "[json.exception.invalid_iterator.203] iterators do not fit current value", typename Json::invalid_iterator&); CHECK_THROWS_WITH_AS(jobject.erase(jobject2.begin(), jobject2.end()), "[json.exception.invalid_iterator.203] iterators do not fit current value", typename Json::invalid_iterator&); } { Json jobject = {{"a", "a"}, {"b", 1}, {"c", 17u}, {"d", false}, {"e", true}}; Json jobject2 = {{"a", "a"}, {"b", 1}, {"c", 17u}}; CHECK_THROWS_WITH_AS(jobject.erase(jobject2.cbegin()), "[json.exception.invalid_iterator.202] iterator does not fit current value", typename Json::invalid_iterator&); CHECK_THROWS_WITH_AS(jobject.erase(jobject.cbegin(), jobject2.cend()), "[json.exception.invalid_iterator.203] iterators do not fit current value", typename Json::invalid_iterator&); CHECK_THROWS_WITH_AS(jobject.erase(jobject2.cbegin(), jobject.cend()), "[json.exception.invalid_iterator.203] iterators do not fit current value", typename Json::invalid_iterator&); CHECK_THROWS_WITH_AS(jobject.erase(jobject2.cbegin(), jobject2.cend()), "[json.exception.invalid_iterator.203] iterators do not fit current value", typename Json::invalid_iterator&); } } } SECTION("remove element by key in non-object type") { SECTION("null") { Json j_nonobject(Json::value_t::null); CHECK_THROWS_WITH_AS(j_nonobject.erase("foo"), "[json.exception.type_error.307] cannot use erase() with null", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.erase(std::string_view("foo")), "[json.exception.type_error.307] cannot use erase() with null", typename Json::type_error&); #endif } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); CHECK_THROWS_WITH_AS(j_nonobject.erase("foo"), "[json.exception.type_error.307] cannot use erase() with boolean", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.erase(std::string_view("foo")), "[json.exception.type_error.307] cannot use erase() with boolean", typename Json::type_error&); #endif } SECTION("string") { Json j_nonobject(Json::value_t::string); CHECK_THROWS_WITH_AS(j_nonobject.erase("foo"), "[json.exception.type_error.307] cannot use erase() with string", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.erase(std::string_view("foo")), "[json.exception.type_error.307] cannot use erase() with string", typename Json::type_error&); #endif } SECTION("array") { Json j_nonobject(Json::value_t::array); CHECK_THROWS_WITH_AS(j_nonobject.erase("foo"), "[json.exception.type_error.307] cannot use erase() with array", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.erase(std::string_view("foo")), "[json.exception.type_error.307] cannot use erase() with array", typename Json::type_error&); #endif } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); CHECK_THROWS_WITH_AS(j_nonobject.erase("foo"), "[json.exception.type_error.307] cannot use erase() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.erase(std::string_view("foo")), "[json.exception.type_error.307] cannot use erase() with number", typename Json::type_error&); #endif } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); CHECK_THROWS_WITH_AS(j_nonobject.erase("foo"), "[json.exception.type_error.307] cannot use erase() with number", typename Json::type_error&); #ifdef JSON_HAS_CPP_17 CHECK_THROWS_WITH_AS(j_nonobject.erase(std::string_view("foo")), "[json.exception.type_error.307] cannot use erase() with number", typename Json::type_error&); #endif } } } SECTION("find an element in an object") { SECTION("existing element") { for (const auto* key : {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" }) { CHECK(j.find(key) != j.end()); CHECK(*j.find(key) == j.at(key)); CHECK(j_const.find(key) != j_const.end()); CHECK(*j_const.find(key) == j_const.at(key)); } #ifdef JSON_HAS_CPP_17 for (const std::string_view key : {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" }) { CHECK(j.find(key) != j.end()); CHECK(*j.find(key) == j.at(key)); CHECK(j_const.find(key) != j_const.end()); CHECK(*j_const.find(key) == j_const.at(key)); } #endif } SECTION("nonexisting element") { CHECK(j.find("foo") == j.end()); CHECK(j_const.find("foo") == j_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j.find(std::string_view("foo")) == j.end()); CHECK(j_const.find(std::string_view("foo")) == j_const.end()); #endif } SECTION("all types") { SECTION("null") { Json j_nonarray(Json::value_t::null); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("string") { Json j_nonarray(Json::value_t::string); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("object") { Json j_nonarray(Json::value_t::object); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("array") { Json j_nonarray(Json::value_t::array); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("boolean") { Json j_nonarray(Json::value_t::boolean); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("number (integer)") { Json j_nonarray(Json::value_t::number_integer); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("number (unsigned)") { Json j_nonarray(Json::value_t::number_unsigned); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } SECTION("number (floating-point)") { Json j_nonarray(Json::value_t::number_float); const Json j_nonarray_const(j_nonarray); CHECK(j_nonarray.find("foo") == j_nonarray.end()); CHECK(j_nonarray_const.find("foo") == j_nonarray_const.end()); #ifdef JSON_HAS_CPP_17 CHECK(j_nonarray.find(std::string_view("foo")) == j_nonarray.end()); CHECK(j_nonarray_const.find(std::string_view("foo")) == j_nonarray_const.end()); #endif } } } SECTION("count keys in an object") { SECTION("existing element") { for (const auto* key : {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" }) { CHECK(j.count(key) == 1); CHECK(j_const.count(key) == 1); } #ifdef JSON_HAS_CPP_17 for (const std::string_view key : {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" }) { CHECK(j.count(key) == 1); CHECK(j_const.count(key) == 1); } #endif } SECTION("nonexisting element") { CHECK(j.count("foo") == 0); CHECK(j_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("all types") { SECTION("null") { Json j_nonobject(Json::value_t::null); const Json j_nonobject_const(Json::value_t::null); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("string") { Json j_nonobject(Json::value_t::string); const Json j_nonobject_const(Json::value_t::string); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("object") { Json j_nonobject(Json::value_t::object); const Json j_nonobject_const(Json::value_t::object); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("array") { Json j_nonobject(Json::value_t::array); const Json j_nonobject_const(Json::value_t::array); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); const Json j_nonobject_const(Json::value_t::boolean); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); const Json j_nonobject_const(Json::value_t::number_integer); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("number (unsigned)") { Json j_nonobject(Json::value_t::number_unsigned); const Json j_nonobject_const(Json::value_t::number_unsigned); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); const Json j_nonobject_const(Json::value_t::number_float); CHECK(j_nonobject.count("foo") == 0); CHECK(j_nonobject_const.count("foo") == 0); #ifdef JSON_HAS_CPP_17 CHECK(j.count(std::string_view("foo")) == 0); CHECK(j_const.count(std::string_view("foo")) == 0); #endif } } } SECTION("check existence of key in an object") { SECTION("existing element") { for (const auto* key : {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" }) { CHECK(j.contains(key) == true); CHECK(j_const.contains(key) == true); } #ifdef JSON_HAS_CPP_17 for (const std::string_view key : {"integer", "unsigned", "floating", "null", "string", "boolean", "object", "array" }) { CHECK(j.contains(key) == true); CHECK(j_const.contains(key) == true); } #endif } SECTION("nonexisting element") { CHECK(j.contains("foo") == false); CHECK(j_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j.contains(std::string_view("foo")) == false); CHECK(j_const.contains(std::string_view("foo")) == false); #endif } SECTION("all types") { SECTION("null") { Json j_nonobject(Json::value_t::null); const Json j_nonobject_const(Json::value_t::null); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("string") { Json j_nonobject(Json::value_t::string); const Json j_nonobject_const(Json::value_t::string); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("object") { Json j_nonobject(Json::value_t::object); const Json j_nonobject_const(Json::value_t::object); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("array") { Json j_nonobject(Json::value_t::array); const Json j_nonobject_const(Json::value_t::array); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("boolean") { Json j_nonobject(Json::value_t::boolean); const Json j_nonobject_const(Json::value_t::boolean); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("number (integer)") { Json j_nonobject(Json::value_t::number_integer); const Json j_nonobject_const(Json::value_t::number_integer); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("number (unsigned)") { Json j_nonobject(Json::value_t::number_unsigned); const Json j_nonobject_const(Json::value_t::number_unsigned); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } SECTION("number (floating-point)") { Json j_nonobject(Json::value_t::number_float); const Json j_nonobject_const(Json::value_t::number_float); CHECK(j_nonobject.contains("foo") == false); CHECK(j_nonobject_const.contains("foo") == false); #ifdef JSON_HAS_CPP_17 CHECK(j_nonobject.contains(std::string_view("foo")) == false); CHECK(j_nonobject_const.contains(std::string_view("foo")) == false); #endif } } } } } #if !defined(JSON_NOEXCEPTION) TEST_CASE_TEMPLATE("element access 2 (throwing tests)", Json, nlohmann::json, nlohmann::ordered_json) { SECTION("object") { 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 = {{"integer", 1}, {"unsigned", 1u}, {"floating", 42.23}, {"null", nullptr}, {"string", "hello world"}, {"boolean", true}, {"object", Json::object()}, {"array", {1, 2, 3}}}; SECTION("access specified element with default value") { SECTION("given a JSON pointer") { SECTION("access non-existing value") { CHECK(j.value("/not/existing"_json_pointer, 2) == 2); CHECK(j.value("/not/existing"_json_pointer, 2u) == 2u); CHECK(j.value("/not/existing"_json_pointer, false) == false); CHECK(j.value("/not/existing"_json_pointer, "bar") == "bar"); CHECK(j.value("/not/existing"_json_pointer, 12.34) == Approx(12.34)); CHECK(j.value("/not/existing"_json_pointer, Json({{"foo", "bar"}})) == Json({{"foo", "bar"}})); CHECK(j.value("/not/existing"_json_pointer, Json({10, 100})) == Json({10, 100})); CHECK(j_const.value("/not/existing"_json_pointer, 2) == 2); CHECK(j_const.value("/not/existing"_json_pointer, 2u) == 2u); CHECK(j_const.value("/not/existing"_json_pointer, false) == false); CHECK(j_const.value("/not/existing"_json_pointer, "bar") == "bar"); CHECK(j_const.value("/not/existing"_json_pointer, 12.34) == Approx(12.34)); CHECK(j_const.value("/not/existing"_json_pointer, Json({{"foo", "bar"}})) == Json({{"foo", "bar"}})); CHECK(j_const.value("/not/existing"_json_pointer, Json({10, 100})) == Json({10, 100})); } } } } } #endif // TODO(falbrechtskirchinger) merge with the other test case; clean up TEST_CASE_TEMPLATE("element access 2 (additional value() tests)", Json, nlohmann::json, nlohmann::ordered_json) { using string_t = typename Json::string_t; using number_integer_t = typename Json::number_integer_t; // test assumes string_t and object_t::key_type are the same REQUIRE(std::is_same<string_t, typename Json::object_t::key_type>::value); Json j { {"foo", "bar"}, {"baz", 42} }; const char* cpstr = "default"; const char castr[] = "default"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) string_t const str = "default"; number_integer_t integer = 69; std::size_t size = 69; SECTION("deduced ValueType") { SECTION("literal key") { CHECK(j.value("foo", "default") == "bar"); CHECK(j.value("foo", cpstr) == "bar"); CHECK(j.value("foo", castr) == "bar"); CHECK(j.value("foo", str) == "bar"); // this test is in fact different than the one below, // because of 0 considering const char * overloads // where as any other number does not CHECK(j.value("baz", 0) == 42); CHECK(j.value("baz", 47) == 42); CHECK(j.value("baz", integer) == 42); CHECK(j.value("baz", size) == 42); CHECK(j.value("bar", "default") == "default"); CHECK(j.value("bar", 0) == 0); CHECK(j.value("bar", 47) == 47); CHECK(j.value("bar", integer) == integer); CHECK(j.value("bar", size) == size); CHECK_THROWS_WITH_AS(Json().value("foo", "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().value("foo", str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("const char * key") { const char* key = "foo"; const char* key2 = "baz"; const char* key_notfound = "bar"; CHECK(j.value(key, "default") == "bar"); CHECK(j.value(key, cpstr) == "bar"); CHECK(j.value(key, castr) == "bar"); CHECK(j.value(key, str) == "bar"); CHECK(j.value(key2, 0) == 42); CHECK(j.value(key2, 47) == 42); CHECK(j.value(key2, integer) == 42); CHECK(j.value(key2, size) == 42); CHECK(j.value(key_notfound, "default") == "default"); CHECK(j.value(key_notfound, 0) == 0); CHECK(j.value(key_notfound, 47) == 47); CHECK(j.value(key_notfound, integer) == integer); CHECK(j.value(key_notfound, size) == size); CHECK_THROWS_WITH_AS(Json().value(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().value(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("const char(&)[] key") { const char key[] = "foo"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) const char key2[] = "baz"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) const char key_notfound[] = "bar"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) CHECK(j.value(key, "default") == "bar"); CHECK(j.value(key, cpstr) == "bar"); CHECK(j.value(key, castr) == "bar"); CHECK(j.value(key, str) == "bar"); CHECK(j.value(key2, 0) == 42); CHECK(j.value(key2, 47) == 42); CHECK(j.value(key2, integer) == 42); CHECK(j.value(key2, size) == 42); CHECK(j.value(key_notfound, "default") == "default"); CHECK(j.value(key_notfound, 0) == 0); CHECK(j.value(key_notfound, 47) == 47); CHECK(j.value(key_notfound, integer) == integer); CHECK(j.value(key_notfound, size) == size); CHECK_THROWS_WITH_AS(Json().value(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().value(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("string_t/object_t::key_type key") { string_t const key = "foo"; string_t const key2 = "baz"; string_t const key_notfound = "bar"; CHECK(j.value(key, "default") == "bar"); CHECK(j.value(key, cpstr) == "bar"); CHECK(j.value(key, castr) == "bar"); CHECK(j.value(key, str) == "bar"); CHECK(j.value(key2, 0) == 42); CHECK(j.value(key2, 47) == 42); CHECK(j.value(key2, integer) == 42); CHECK(j.value(key2, size) == 42); CHECK(j.value(key_notfound, "default") == "default"); CHECK(j.value(key_notfound, 0) == 0); CHECK(j.value(key_notfound, 47) == 47); CHECK(j.value(key_notfound, integer) == integer); CHECK(j.value(key_notfound, size) == size); CHECK_THROWS_WITH_AS(Json().value(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().value(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } #ifdef JSON_HAS_CPP_17 SECTION("std::string_view key") { std::string_view const key = "foo"; std::string_view const key2 = "baz"; std::string_view const key_notfound = "bar"; CHECK(j.value(key, "default") == "bar"); CHECK(j.value(key, cpstr) == "bar"); CHECK(j.value(key, castr) == "bar"); CHECK(j.value(key, str) == "bar"); CHECK(j.value(key2, 0) == 42); CHECK(j.value(key2, 47) == 42); CHECK(j.value(key2, integer) == 42); CHECK(j.value(key2, size) == 42); CHECK(j.value(key_notfound, "default") == "default"); CHECK(j.value(key_notfound, 0) == 0); CHECK(j.value(key_notfound, 47) == 47); CHECK(j.value(key_notfound, integer) == integer); CHECK(j.value(key_notfound, size) == size); CHECK_THROWS_WITH_AS(Json().value(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().value(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } #endif } SECTION("explicit ValueType") { SECTION("literal key") { CHECK(j.template value<string_t>("foo", "default") == "bar"); CHECK(j.template value<string_t>("foo", cpstr) == "bar"); CHECK(j.template value<string_t>("foo", castr) == "bar"); CHECK(j.template value<string_t>("foo", str) == "bar"); CHECK(j.template value<number_integer_t>("baz", 0) == 42); CHECK(j.template value<number_integer_t>("baz", 47) == 42); CHECK(j.template value<number_integer_t>("baz", integer) == 42); CHECK(j.template value<std::size_t>("baz", 0) == 42); CHECK(j.template value<std::size_t>("baz", 47) == 42); CHECK(j.template value<std::size_t>("baz", size) == 42); CHECK(j.template value<string_t>("bar", "default") == "default"); CHECK(j.template value<number_integer_t>("bar", 0) == 0); CHECK(j.template value<number_integer_t>("bar", 47) == 47); CHECK(j.template value<number_integer_t>("bar", integer) == integer); CHECK(j.template value<std::size_t>("bar", 0) == 0); CHECK(j.template value<std::size_t>("bar", 47) == 47); CHECK(j.template value<std::size_t>("bar", size) == size); CHECK_THROWS_WITH_AS(Json().template value<string_t>("foo", "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().template value<string_t>("foo", str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("const char * key") { const char* key = "foo"; const char* key2 = "baz"; const char* key_notfound = "bar"; CHECK(j.template value<string_t>(key, "default") == "bar"); CHECK(j.template value<string_t>(key, cpstr) == "bar"); CHECK(j.template value<string_t>(key, castr) == "bar"); CHECK(j.template value<string_t>(key, str) == "bar"); CHECK(j.template value<number_integer_t>(key2, 0) == 42); CHECK(j.template value<number_integer_t>(key2, 47) == 42); CHECK(j.template value<number_integer_t>(key2, integer) == 42); CHECK(j.template value<std::size_t>(key2, 0) == 42); CHECK(j.template value<std::size_t>(key2, 47) == 42); CHECK(j.template value<std::size_t>(key2, size) == 42); CHECK(j.template value<string_t>(key_notfound, "default") == "default"); CHECK(j.template value<number_integer_t>(key_notfound, 0) == 0); CHECK(j.template value<number_integer_t>(key_notfound, 47) == 47); CHECK(j.template value<number_integer_t>(key_notfound, integer) == integer); CHECK(j.template value<std::size_t>(key_notfound, 0) == 0); CHECK(j.template value<std::size_t>(key_notfound, 47) == 47); CHECK(j.template value<std::size_t>(key_notfound, size) == size); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("const char(&)[] key") { const char key[] = "foo"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) const char key2[] = "baz"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) const char key_notfound[] = "bar"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) CHECK(j.template value<string_t>(key, "default") == "bar"); CHECK(j.template value<string_t>(key, cpstr) == "bar"); CHECK(j.template value<string_t>(key, castr) == "bar"); CHECK(j.template value<string_t>(key, str) == "bar"); CHECK(j.template value<number_integer_t>(key2, 0) == 42); CHECK(j.template value<number_integer_t>(key2, 47) == 42); CHECK(j.template value<number_integer_t>(key2, integer) == 42); CHECK(j.template value<std::size_t>(key2, 0) == 42); CHECK(j.template value<std::size_t>(key2, 47) == 42); CHECK(j.template value<std::size_t>(key2, size) == 42); CHECK(j.template value<string_t>(key_notfound, "default") == "default"); CHECK(j.template value<number_integer_t>(key_notfound, 0) == 0); CHECK(j.template value<number_integer_t>(key_notfound, 47) == 47); CHECK(j.template value<number_integer_t>(key_notfound, integer) == integer); CHECK(j.template value<std::size_t>(key_notfound, 0) == 0); CHECK(j.template value<std::size_t>(key_notfound, 47) == 47); CHECK(j.template value<std::size_t>(key_notfound, size) == size); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } SECTION("string_t/object_t::key_type key") { string_t const key = "foo"; string_t const key2 = "baz"; string_t const key_notfound = "bar"; CHECK(j.template value<string_t>(key, "default") == "bar"); CHECK(j.template value<string_t>(key, cpstr) == "bar"); CHECK(j.template value<string_t>(key, castr) == "bar"); CHECK(j.template value<string_t>(key, str) == "bar"); CHECK(j.template value<number_integer_t>(key2, 0) == 42); CHECK(j.template value<number_integer_t>(key2, 47) == 42); CHECK(j.template value<std::size_t>(key2, 0) == 42); CHECK(j.template value<std::size_t>(key2, 47) == 42); CHECK(j.template value<string_t>(key_notfound, "default") == "default"); CHECK(j.template value<number_integer_t>(key_notfound, 0) == 0); CHECK(j.template value<number_integer_t>(key_notfound, 47) == 47); CHECK(j.template value<std::size_t>(key_notfound, 0) == 0); CHECK(j.template value<std::size_t>(key_notfound, 47) == 47); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } #ifdef JSON_HAS_CPP_17 SECTION("std::string_view key") { std::string_view const key = "foo"; std::string_view const key2 = "baz"; std::string_view const key_notfound = "bar"; CHECK(j.template value<string_t>(key, "default") == "bar"); CHECK(j.template value<string_t>(key, cpstr) == "bar"); CHECK(j.template value<string_t>(key, castr) == "bar"); CHECK(j.template value<string_t>(key, str) == "bar"); CHECK(j.template value<number_integer_t>(key2, 0) == 42); CHECK(j.template value<number_integer_t>(key2, 47) == 42); CHECK(j.template value<number_integer_t>(key2, integer) == 42); CHECK(j.template value<std::size_t>(key2, 0) == 42); CHECK(j.template value<std::size_t>(key2, 47) == 42); CHECK(j.template value<std::size_t>(key2, size) == 42); CHECK(j.template value<string_t>(key_notfound, "default") == "default"); CHECK(j.template value<number_integer_t>(key_notfound, 0) == 0); CHECK(j.template value<number_integer_t>(key_notfound, 47) == 47); CHECK(j.template value<number_integer_t>(key_notfound, integer) == integer); CHECK(j.template value<std::size_t>(key_notfound, 0) == 0); CHECK(j.template value<std::size_t>(key_notfound, 47) == 47); CHECK(j.template value<std::size_t>(key_notfound, size) == size); CHECK(j.template value<std::string_view>(key, "default") == "bar"); CHECK(j.template value<std::string_view>(key, cpstr) == "bar"); CHECK(j.template value<std::string_view>(key, castr) == "bar"); CHECK(j.template value<std::string_view>(key, str) == "bar"); CHECK(j.template value<std::string_view>(key_notfound, "default") == "default"); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, "default"), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); CHECK_THROWS_WITH_AS(Json().template value<string_t>(key, str), "[json.exception.type_error.306] cannot use value() with null", typename Json::type_error&); } #endif } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-element_access1.cpp
.cpp
40,061
882
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // Copyright (c) 2013-2022 Niels Lohmann <http://nlohmann.me>. // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #include <nlohmann/json.hpp> using nlohmann::json; TEST_CASE("element access 1") { SECTION("array") { json j = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; const json j_const = j; SECTION("access specified element with bounds checking") { SECTION("access within bounds") { CHECK(j.at(0) == json(1)); CHECK(j.at(1) == json(1u)); CHECK(j.at(2) == json(true)); CHECK(j.at(3) == json(nullptr)); CHECK(j.at(4) == json("string")); CHECK(j.at(5) == json(42.23)); CHECK(j.at(6) == json::object()); CHECK(j.at(7) == json({1, 2, 3})); CHECK(j_const.at(0) == json(1)); CHECK(j_const.at(1) == json(1u)); CHECK(j_const.at(2) == json(true)); CHECK(j_const.at(3) == json(nullptr)); CHECK(j_const.at(4) == json("string")); CHECK(j_const.at(5) == json(42.23)); CHECK(j_const.at(6) == json::object()); CHECK(j_const.at(7) == json({1, 2, 3})); } SECTION("access outside bounds") { CHECK_THROWS_WITH_AS(j.at(8), "[json.exception.out_of_range.401] array index 8 is out of range", json::out_of_range&); CHECK_THROWS_WITH_AS(j_const.at(8), "[json.exception.out_of_range.401] array index 8 is out of range", json::out_of_range&); } SECTION("access on non-array type") { SECTION("null") { json j_nonarray(json::value_t::null); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with null", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with null", json::type_error&); } SECTION("boolean") { json j_nonarray(json::value_t::boolean); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with boolean", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with boolean", json::type_error&); } SECTION("string") { json j_nonarray(json::value_t::string); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with string", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with string", json::type_error&); } SECTION("object") { json j_nonarray(json::value_t::object); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with object", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with object", json::type_error&); } SECTION("number (integer)") { json j_nonarray(json::value_t::number_integer); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with number", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with number", json::type_error&); } SECTION("number (unsigned)") { json j_nonarray(json::value_t::number_unsigned); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with number", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with number", json::type_error&); } SECTION("number (floating-point)") { json j_nonarray(json::value_t::number_float); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray.at(0), "[json.exception.type_error.304] cannot use at() with number", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const.at(0), "[json.exception.type_error.304] cannot use at() with number", json::type_error&); } } } SECTION("front and back") { CHECK(j.front() == json(1)); CHECK(j_const.front() == json(1)); CHECK(j.back() == json({1, 2, 3})); CHECK(j_const.back() == json({1, 2, 3})); } SECTION("access specified element") { SECTION("access within bounds") { CHECK(j[0] == json(1)); CHECK(j[1] == json(1u)); CHECK(j[2] == json(true)); CHECK(j[3] == json(nullptr)); CHECK(j[4] == json("string")); CHECK(j[5] == json(42.23)); CHECK(j[6] == json::object()); CHECK(j[7] == json({1, 2, 3})); CHECK(j_const[0] == json(1)); CHECK(j_const[1] == json(1u)); CHECK(j_const[2] == json(true)); CHECK(j_const[3] == json(nullptr)); CHECK(j_const[4] == json("string")); CHECK(j_const[5] == json(42.23)); CHECK(j_const[6] == json::object()); CHECK(j_const[7] == json({1, 2, 3})); } SECTION("access on non-array type") { SECTION("null") { SECTION("standard tests") { json j_nonarray(json::value_t::null); const json j_nonarray_const(j_nonarray); CHECK_NOTHROW(j_nonarray[0]); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with null", json::type_error&); } SECTION("implicit transformation to properly filled array") { json j_nonarray; j_nonarray[3] = 42; CHECK(j_nonarray == json({nullptr, nullptr, nullptr, 42})); } } SECTION("boolean") { json j_nonarray(json::value_t::boolean); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with boolean", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with boolean", json::type_error&); } SECTION("string") { json j_nonarray(json::value_t::string); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with string", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with string", json::type_error&); } SECTION("object") { json j_nonarray(json::value_t::object); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with object", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with object", json::type_error&); } SECTION("number (integer)") { json j_nonarray(json::value_t::number_integer); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with number", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with number", json::type_error&); } SECTION("number (unsigned)") { json j_nonarray(json::value_t::number_unsigned); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with number", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with number", json::type_error&); } SECTION("number (floating-point)") { json j_nonarray(json::value_t::number_float); const json j_nonarray_const(j_nonarray); CHECK_THROWS_WITH_AS(j_nonarray[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with number", json::type_error&); CHECK_THROWS_WITH_AS(j_nonarray_const[0], "[json.exception.type_error.305] cannot use operator[] with a numeric argument with number", json::type_error&); } } } SECTION("remove specified element") { SECTION("remove element by index") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(0); CHECK(jarray == json({1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(1); CHECK(jarray == json({1, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(2); CHECK(jarray == json({1, 1u, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(3); CHECK(jarray == json({1, 1u, true, "string", 42.23, json::object(), {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(4); CHECK(jarray == json({1, 1u, true, nullptr, 42.23, json::object(), {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(5); CHECK(jarray == json({1, 1u, true, nullptr, "string", json::object(), {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(6); CHECK(jarray == json({1, 1u, true, nullptr, "string", 42.23, {1, 2, 3}})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; jarray.erase(7); CHECK(jarray == json({1, 1u, true, nullptr, "string", 42.23, json::object()})); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; CHECK_THROWS_WITH_AS(jarray.erase(8), "[json.exception.out_of_range.401] array index 8 is out of range", json::out_of_range&); } } SECTION("remove element by iterator") { SECTION("erase(begin())") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::iterator const it2 = jarray.erase(jarray.begin()); CHECK(jarray == json({1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); CHECK(*it2 == json(1u)); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::const_iterator const it2 = jarray.erase(jarray.cbegin()); CHECK(jarray == json({1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); CHECK(*it2 == json(1u)); } } SECTION("erase(begin(), end())") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::iterator it2 = jarray.erase(jarray.begin(), jarray.end()); CHECK(jarray == json::array()); CHECK(it2 == jarray.end()); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::const_iterator it2 = jarray.erase(jarray.cbegin(), jarray.cend()); CHECK(jarray == json::array()); CHECK(it2 == jarray.cend()); } } SECTION("erase(begin(), begin())") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::iterator const it2 = jarray.erase(jarray.begin(), jarray.begin()); CHECK(jarray == json({1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); CHECK(*it2 == json(1)); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::const_iterator const it2 = jarray.erase(jarray.cbegin(), jarray.cbegin()); CHECK(jarray == json({1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}})); CHECK(*it2 == json(1)); } } SECTION("erase at offset") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::iterator const it = jarray.begin() + 4; json::iterator const it2 = jarray.erase(it); CHECK(jarray == json({1, 1u, true, nullptr, 42.23, json::object(), {1, 2, 3}})); CHECK(*it2 == json(42.23)); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::const_iterator const it = jarray.cbegin() + 4; json::const_iterator const it2 = jarray.erase(it); CHECK(jarray == json({1, 1u, true, nullptr, 42.23, json::object(), {1, 2, 3}})); CHECK(*it2 == json(42.23)); } } SECTION("erase subrange") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::iterator const it2 = jarray.erase(jarray.begin() + 3, jarray.begin() + 6); CHECK(jarray == json({1, 1u, true, json::object(), {1, 2, 3}})); CHECK(*it2 == json::object()); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json::const_iterator const it2 = jarray.erase(jarray.cbegin() + 3, jarray.cbegin() + 6); CHECK(jarray == json({1, 1u, true, json::object(), {1, 2, 3}})); CHECK(*it2 == json::object()); } } SECTION("different arrays") { { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json jarray2 = {"foo", "bar"}; CHECK_THROWS_WITH_AS(jarray.erase(jarray2.begin()), "[json.exception.invalid_iterator.202] iterator does not fit current value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(jarray.erase(jarray.begin(), jarray2.end()), "[json.exception.invalid_iterator.203] iterators do not fit current value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(jarray.erase(jarray2.begin(), jarray.end()), "[json.exception.invalid_iterator.203] iterators do not fit current value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(jarray.erase(jarray2.begin(), jarray2.end()), "[json.exception.invalid_iterator.203] iterators do not fit current value", json::invalid_iterator&); } { json jarray = {1, 1u, true, nullptr, "string", 42.23, json::object(), {1, 2, 3}}; json const jarray2 = {"foo", "bar"}; CHECK_THROWS_WITH_AS(jarray.erase(jarray2.cbegin()), "[json.exception.invalid_iterator.202] iterator does not fit current value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(jarray.erase(jarray.cbegin(), jarray2.cend()), "[json.exception.invalid_iterator.203] iterators do not fit current value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(jarray.erase(jarray2.cbegin(), jarray.cend()), "[json.exception.invalid_iterator.203] iterators do not fit current value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(jarray.erase(jarray2.cbegin(), jarray2.cend()), "[json.exception.invalid_iterator.203] iterators do not fit current value", json::invalid_iterator&); } } } SECTION("remove element by index in non-array type") { SECTION("null") { json j_nonobject(json::value_t::null); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with null", json::type_error&); } SECTION("boolean") { json j_nonobject(json::value_t::boolean); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with boolean", json::type_error&); } SECTION("string") { json j_nonobject(json::value_t::string); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with string", json::type_error&); } SECTION("object") { json j_nonobject(json::value_t::object); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with object", json::type_error&); } SECTION("number (integer)") { json j_nonobject(json::value_t::number_integer); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with number", json::type_error&); } SECTION("number (unsigned)") { json j_nonobject(json::value_t::number_unsigned); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with number", json::type_error&); } SECTION("number (floating-point)") { json j_nonobject(json::value_t::number_float); CHECK_THROWS_WITH_AS(j_nonobject.erase(0), "[json.exception.type_error.307] cannot use erase() with number", json::type_error&); } } } } SECTION("other values") { SECTION("front and back") { SECTION("null") { { json j; CHECK_THROWS_WITH_AS(j.front(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.back(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } { const json j{}; CHECK_THROWS_WITH_AS(j.front(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.back(), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } } SECTION("string") { { json j = "foo"; CHECK(j.front() == j); CHECK(j.back() == j); } { const json j = "bar"; CHECK(j.front() == j); CHECK(j.back() == j); } } SECTION("number (boolean)") { { json j = false; CHECK(j.front() == j); CHECK(j.back() == j); } { const json j = true; CHECK(j.front() == j); CHECK(j.back() == j); } } SECTION("number (integer)") { { json j = 17; CHECK(j.front() == j); CHECK(j.back() == j); } { const json j = 17; CHECK(j.front() == j); CHECK(j.back() == j); } } SECTION("number (unsigned)") { { json j = 17u; CHECK(j.front() == j); CHECK(j.back() == j); } { const json j = 17u; CHECK(j.front() == j); CHECK(j.back() == j); } } SECTION("number (floating point)") { { json j = 23.42; CHECK(j.front() == j); CHECK(j.back() == j); } { const json j = 23.42; CHECK(j.front() == j); CHECK(j.back() == j); } } } SECTION("erase with one valid iterator") { SECTION("null") { { json j; CHECK_THROWS_WITH_AS(j.erase(j.begin()), "[json.exception.type_error.307] cannot use erase() with null", json::type_error&); } { json j; CHECK_THROWS_WITH_AS(j.erase(j.begin()), "[json.exception.type_error.307] cannot use erase() with null", json::type_error&); } } SECTION("string") { { json j = "foo"; json::iterator it = j.erase(j.begin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = "bar"; json::const_iterator it = j.erase(j.cbegin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (boolean)") { { json j = false; json::iterator it = j.erase(j.begin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = true; json::const_iterator it = j.erase(j.cbegin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (integer)") { { json j = 17; json::iterator it = j.erase(j.begin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = 17; json::const_iterator it = j.erase(j.cbegin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (unsigned)") { { json j = 17u; json::iterator it = j.erase(j.begin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = 17u; json::const_iterator it = j.erase(j.cbegin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (floating point)") { { json j = 23.42; json::iterator it = j.erase(j.begin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = 23.42; json::const_iterator it = j.erase(j.cbegin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("binary") { { json j = json::binary({1, 2, 3}); json::iterator it = j.erase(j.begin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = json::binary({1, 2, 3}); json::const_iterator it = j.erase(j.cbegin()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } } SECTION("erase with one invalid iterator") { SECTION("string") { { json j = "foo"; CHECK_THROWS_WITH_AS(j.erase(j.end()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } { json j = "bar"; CHECK_THROWS_WITH_AS(j.erase(j.cend()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } } SECTION("number (boolean)") { { json j = false; CHECK_THROWS_WITH_AS(j.erase(j.end()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } { json j = true; CHECK_THROWS_WITH_AS(j.erase(j.cend()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } } SECTION("number (integer)") { { json j = 17; CHECK_THROWS_WITH_AS(j.erase(j.end()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } { json j = 17; CHECK_THROWS_WITH_AS(j.erase(j.cend()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } } SECTION("number (unsigned)") { { json j = 17u; CHECK_THROWS_WITH_AS(j.erase(j.end()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } { json j = 17u; CHECK_THROWS_WITH_AS(j.erase(j.cend()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } } SECTION("number (floating point)") { { json j = 23.42; CHECK_THROWS_WITH_AS(j.erase(j.end()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } { json j = 23.42; CHECK_THROWS_WITH_AS(j.erase(j.cend()), "[json.exception.invalid_iterator.205] iterator out of range", json::invalid_iterator&); } } } SECTION("erase with two valid iterators") { SECTION("null") { { json j; CHECK_THROWS_WITH_AS(j.erase(j.begin(), j.end()), "[json.exception.type_error.307] cannot use erase() with null", json::type_error&); } { json j; CHECK_THROWS_WITH_AS(j.erase(j.cbegin(), j.cend()), "[json.exception.type_error.307] cannot use erase() with null", json::type_error&); } } SECTION("string") { { json j = "foo"; json::iterator it = j.erase(j.begin(), j.end()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = "bar"; json::const_iterator it = j.erase(j.cbegin(), j.cend()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (boolean)") { { json j = false; json::iterator it = j.erase(j.begin(), j.end()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = true; json::const_iterator it = j.erase(j.cbegin(), j.cend()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (integer)") { { json j = 17; json::iterator it = j.erase(j.begin(), j.end()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = 17; json::const_iterator it = j.erase(j.cbegin(), j.cend()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (unsigned)") { { json j = 17u; json::iterator it = j.erase(j.begin(), j.end()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = 17u; json::const_iterator it = j.erase(j.cbegin(), j.cend()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("number (floating point)") { { json j = 23.42; json::iterator it = j.erase(j.begin(), j.end()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = 23.42; json::const_iterator it = j.erase(j.cbegin(), j.cend()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } SECTION("binary") { { json j = json::binary({1, 2, 3}); json::iterator it = j.erase(j.begin(), j.end()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } { json j = json::binary({1, 2, 3}); json::const_iterator it = j.erase(j.cbegin(), j.cend()); CHECK(j.type() == json::value_t::null); CHECK(it == j.end()); } } } SECTION("erase with two invalid iterators") { SECTION("string") { { json j = "foo"; CHECK_THROWS_WITH_AS(j.erase(j.end(), j.end()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.begin(), j.begin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } { json j = "bar"; CHECK_THROWS_WITH_AS(j.erase(j.cend(), j.cend()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.cbegin(), j.cbegin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } } SECTION("number (boolean)") { { json j = false; CHECK_THROWS_WITH_AS(j.erase(j.end(), j.end()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.begin(), j.begin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } { json j = true; CHECK_THROWS_WITH_AS(j.erase(j.cend(), j.cend()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.cbegin(), j.cbegin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } } SECTION("number (integer)") { { json j = 17; CHECK_THROWS_WITH_AS(j.erase(j.end(), j.end()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.begin(), j.begin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } { json j = 17; CHECK_THROWS_WITH_AS(j.erase(j.cend(), j.cend()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.cbegin(), j.cbegin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } } SECTION("number (unsigned)") { { json j = 17u; CHECK_THROWS_WITH_AS(j.erase(j.end(), j.end()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.begin(), j.begin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } { json j = 17u; CHECK_THROWS_WITH_AS(j.erase(j.cend(), j.cend()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.cbegin(), j.cbegin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } } SECTION("number (floating point)") { { json j = 23.42; CHECK_THROWS_WITH_AS(j.erase(j.end(), j.end()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.begin(), j.begin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } { json j = 23.42; CHECK_THROWS_WITH_AS(j.erase(j.cend(), j.cend()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); CHECK_THROWS_WITH_AS(j.erase(j.cbegin(), j.cbegin()), "[json.exception.invalid_iterator.204] iterators out of range", json::invalid_iterator&); } } } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-json_pointer.cpp
.cpp
30,734
789
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #define JSON_TESTS_PRIVATE #include <nlohmann/json.hpp> using nlohmann::json; #ifdef JSON_TEST_NO_GLOBAL_UDLS using namespace nlohmann::literals; // NOLINT(google-build-using-namespace) #endif #include <map> #include <sstream> TEST_CASE("JSON pointers") { SECTION("errors") { CHECK_THROWS_WITH_AS(json::json_pointer("foo"), "[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'", json::parse_error&); CHECK_THROWS_WITH_AS(json::json_pointer("/~~"), "[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'", json::parse_error&); CHECK_THROWS_WITH_AS(json::json_pointer("/~"), "[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'", json::parse_error&); json::json_pointer p; CHECK_THROWS_WITH_AS(p.top(), "[json.exception.out_of_range.405] JSON pointer has no parent", json::out_of_range&); CHECK_THROWS_WITH_AS(p.pop_back(), "[json.exception.out_of_range.405] JSON pointer has no parent", json::out_of_range&); SECTION("array index error") { json v = {1, 2, 3, 4}; json::json_pointer const ptr("/10e"); CHECK_THROWS_WITH_AS(v[ptr], "[json.exception.out_of_range.404] unresolved reference token '10e'", json::out_of_range&); } } SECTION("examples from RFC 6901") { SECTION("nonconst access") { 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 CHECK(j[json::json_pointer()] == j); CHECK(j[json::json_pointer("")] == j); CHECK(j.contains(json::json_pointer())); CHECK(j.contains(json::json_pointer(""))); // array access CHECK(j[json::json_pointer("/foo")] == j["foo"]); CHECK(j.contains(json::json_pointer("/foo"))); CHECK(j[json::json_pointer("/foo/0")] == j["foo"][0]); CHECK(j[json::json_pointer("/foo/1")] == j["foo"][1]); CHECK(j["/foo/1"_json_pointer] == j["foo"][1]); CHECK(j.contains(json::json_pointer("/foo/0"))); CHECK(j.contains(json::json_pointer("/foo/1"))); CHECK(!j.contains(json::json_pointer("/foo/3"))); CHECK(!j.contains(json::json_pointer("/foo/+"))); CHECK(!j.contains(json::json_pointer("/foo/1+2"))); CHECK(!j.contains(json::json_pointer("/foo/-"))); // checked array access CHECK(j.at(json::json_pointer("/foo/0")) == j["foo"][0]); CHECK(j.at(json::json_pointer("/foo/1")) == j["foo"][1]); // empty string access CHECK(j[json::json_pointer("/")] == j[""]); CHECK(j.contains(json::json_pointer(""))); CHECK(j.contains(json::json_pointer("/"))); // other cases CHECK(j[json::json_pointer("/ ")] == j[" "]); CHECK(j[json::json_pointer("/c%d")] == j["c%d"]); CHECK(j[json::json_pointer("/e^f")] == j["e^f"]); CHECK(j[json::json_pointer("/g|h")] == j["g|h"]); CHECK(j[json::json_pointer("/i\\j")] == j["i\\j"]); CHECK(j[json::json_pointer("/k\"l")] == j["k\"l"]); // contains CHECK(j.contains(json::json_pointer("/ "))); CHECK(j.contains(json::json_pointer("/c%d"))); CHECK(j.contains(json::json_pointer("/e^f"))); CHECK(j.contains(json::json_pointer("/g|h"))); CHECK(j.contains(json::json_pointer("/i\\j"))); CHECK(j.contains(json::json_pointer("/k\"l"))); // checked access CHECK(j.at(json::json_pointer("/ ")) == j[" "]); CHECK(j.at(json::json_pointer("/c%d")) == j["c%d"]); CHECK(j.at(json::json_pointer("/e^f")) == j["e^f"]); CHECK(j.at(json::json_pointer("/g|h")) == j["g|h"]); CHECK(j.at(json::json_pointer("/i\\j")) == j["i\\j"]); CHECK(j.at(json::json_pointer("/k\"l")) == j["k\"l"]); // escaped access CHECK(j[json::json_pointer("/a~1b")] == j["a/b"]); CHECK(j[json::json_pointer("/m~0n")] == j["m~n"]); CHECK(j.contains(json::json_pointer("/a~1b"))); CHECK(j.contains(json::json_pointer("/m~0n"))); // unescaped access // access to nonexisting values yield object creation CHECK(!j.contains(json::json_pointer("/a/b"))); CHECK_NOTHROW(j[json::json_pointer("/a/b")] = 42); CHECK(j.contains(json::json_pointer("/a/b"))); CHECK(j["a"]["b"] == json(42)); CHECK(!j.contains(json::json_pointer("/a/c/1"))); CHECK_NOTHROW(j[json::json_pointer("/a/c/1")] = 42); CHECK(j["a"]["c"] == json({nullptr, 42})); CHECK(j.contains(json::json_pointer("/a/c/1"))); CHECK(!j.contains(json::json_pointer("/a/d/-"))); CHECK_NOTHROW(j[json::json_pointer("/a/d/-")] = 42); CHECK(!j.contains(json::json_pointer("/a/d/-"))); CHECK(j["a"]["d"] == json::array({42})); // "/a/b" works for JSON {"a": {"b": 42}} CHECK(json({{"a", {{"b", 42}}}})[json::json_pointer("/a/b")] == json(42)); // unresolved access json j_primitive = 1; CHECK_THROWS_WITH_AS(j_primitive["/foo"_json_pointer], "[json.exception.out_of_range.404] unresolved reference token 'foo'", json::out_of_range&); CHECK_THROWS_WITH_AS(j_primitive.at("/foo"_json_pointer), "[json.exception.out_of_range.404] unresolved reference token 'foo'", json::out_of_range&); CHECK(!j_primitive.contains(json::json_pointer("/foo"))); } SECTION("const access") { 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 CHECK(j[json::json_pointer()] == j); CHECK(j[json::json_pointer("")] == j); // array access CHECK(j[json::json_pointer("/foo")] == j["foo"]); CHECK(j[json::json_pointer("/foo/0")] == j["foo"][0]); CHECK(j[json::json_pointer("/foo/1")] == j["foo"][1]); CHECK(j["/foo/1"_json_pointer] == j["foo"][1]); // checked array access CHECK(j.at(json::json_pointer("/foo/0")) == j["foo"][0]); CHECK(j.at(json::json_pointer("/foo/1")) == j["foo"][1]); // empty string access CHECK(j[json::json_pointer("/")] == j[""]); // other cases CHECK(j[json::json_pointer("/ ")] == j[" "]); CHECK(j[json::json_pointer("/c%d")] == j["c%d"]); CHECK(j[json::json_pointer("/e^f")] == j["e^f"]); CHECK(j[json::json_pointer("/g|h")] == j["g|h"]); CHECK(j[json::json_pointer("/i\\j")] == j["i\\j"]); CHECK(j[json::json_pointer("/k\"l")] == j["k\"l"]); // checked access CHECK(j.at(json::json_pointer("/ ")) == j[" "]); CHECK(j.at(json::json_pointer("/c%d")) == j["c%d"]); CHECK(j.at(json::json_pointer("/e^f")) == j["e^f"]); CHECK(j.at(json::json_pointer("/g|h")) == j["g|h"]); CHECK(j.at(json::json_pointer("/i\\j")) == j["i\\j"]); CHECK(j.at(json::json_pointer("/k\"l")) == j["k\"l"]); // escaped access CHECK(j[json::json_pointer("/a~1b")] == j["a/b"]); CHECK(j[json::json_pointer("/m~0n")] == j["m~n"]); // unescaped access CHECK_THROWS_WITH_AS(j.at(json::json_pointer("/a/b")), "[json.exception.out_of_range.403] key 'a' not found", json::out_of_range&); // unresolved access const json j_primitive = 1; CHECK_THROWS_WITH_AS(j_primitive["/foo"_json_pointer], "[json.exception.out_of_range.404] unresolved reference token 'foo'", json::out_of_range&); CHECK_THROWS_WITH_AS(j_primitive.at("/foo"_json_pointer), "[json.exception.out_of_range.404] unresolved reference token 'foo'", json::out_of_range&); } SECTION("user-defined string literal") { 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 CHECK(j[""_json_pointer] == j); CHECK(j.contains(""_json_pointer)); // array access CHECK(j["/foo"_json_pointer] == j["foo"]); CHECK(j["/foo/0"_json_pointer] == j["foo"][0]); CHECK(j["/foo/1"_json_pointer] == j["foo"][1]); CHECK(j.contains("/foo"_json_pointer)); CHECK(j.contains("/foo/0"_json_pointer)); CHECK(j.contains("/foo/1"_json_pointer)); CHECK(!j.contains("/foo/-"_json_pointer)); } } SECTION("array access") { SECTION("nonconst access") { json j = {1, 2, 3}; const json j_const = j; // check reading access CHECK(j["/0"_json_pointer] == j[0]); CHECK(j["/1"_json_pointer] == j[1]); CHECK(j["/2"_json_pointer] == j[2]); // assign to existing index j["/1"_json_pointer] = 13; CHECK(j[1] == json(13)); // assign to nonexisting index j["/3"_json_pointer] = 33; CHECK(j[3] == json(33)); // assign to nonexisting index (with gap) j["/5"_json_pointer] = 55; CHECK(j == json({1, 13, 3, 33, nullptr, 55})); // error with leading 0 CHECK_THROWS_WITH_AS(j["/01"_json_pointer], "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'", json::parse_error&); CHECK_THROWS_WITH_AS(j_const["/01"_json_pointer], "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'", json::parse_error&); CHECK_THROWS_WITH_AS(j.at("/01"_json_pointer), "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'", json::parse_error&); CHECK_THROWS_WITH_AS(j_const.at("/01"_json_pointer), "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'", json::parse_error&); CHECK(!j.contains("/01"_json_pointer)); CHECK(!j.contains("/01"_json_pointer)); CHECK(!j_const.contains("/01"_json_pointer)); CHECK(!j_const.contains("/01"_json_pointer)); // error with incorrect numbers CHECK_THROWS_WITH_AS(j["/one"_json_pointer] = 1, "[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j_const["/one"_json_pointer] == 1, "[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j.at("/one"_json_pointer) = 1, "[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j_const.at("/one"_json_pointer) == 1, "[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j["/+1"_json_pointer] = 1, "[json.exception.parse_error.109] parse error: array index '+1' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j_const["/+1"_json_pointer] == 1, "[json.exception.parse_error.109] parse error: array index '+1' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j["/1+1"_json_pointer] = 1, "[json.exception.out_of_range.404] unresolved reference token '1+1'", json::out_of_range&); CHECK_THROWS_WITH_AS(j_const["/1+1"_json_pointer] == 1, "[json.exception.out_of_range.404] unresolved reference token '1+1'", json::out_of_range&); { auto too_large_index = std::to_string((std::numeric_limits<unsigned long long>::max)()) + "1"; json::json_pointer const jp(std::string("/") + too_large_index); std::string const throw_msg = std::string("[json.exception.out_of_range.404] unresolved reference token '") + too_large_index + "'"; CHECK_THROWS_WITH_AS(j[jp] = 1, throw_msg.c_str(), json::out_of_range&); CHECK_THROWS_WITH_AS(j_const[jp] == 1, throw_msg.c_str(), json::out_of_range&); } // on some machines, the check below is not constant DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(4127) if (sizeof(typename json::size_type) < sizeof(unsigned long long)) { auto size_type_max_uul = static_cast<unsigned long long>((std::numeric_limits<json::size_type>::max)()); auto too_large_index = std::to_string(size_type_max_uul); json::json_pointer const jp(std::string("/") + too_large_index); std::string const throw_msg = std::string("[json.exception.out_of_range.410] array index ") + too_large_index + " exceeds size_type"; CHECK_THROWS_WITH_AS(j[jp] = 1, throw_msg.c_str(), json::out_of_range&); CHECK_THROWS_WITH_AS(j_const[jp] == 1, throw_msg.c_str(), json::out_of_range&); } DOCTEST_MSVC_SUPPRESS_WARNING_POP CHECK_THROWS_WITH_AS(j.at("/one"_json_pointer) = 1, "[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&); CHECK_THROWS_WITH_AS(j_const.at("/one"_json_pointer) == 1, "[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&); CHECK(!j.contains("/one"_json_pointer)); CHECK(!j.contains("/one"_json_pointer)); CHECK(!j_const.contains("/one"_json_pointer)); CHECK(!j_const.contains("/one"_json_pointer)); CHECK_THROWS_WITH_AS(json({{"/list/0", 1}, {"/list/1", 2}, {"/list/three", 3}}).unflatten(), "[json.exception.parse_error.109] parse error: array index 'three' is not a number", json::parse_error&); // assign to "-" j["/-"_json_pointer] = 99; CHECK(j == json({1, 13, 3, 33, nullptr, 55, 99})); // error when using "-" in const object CHECK_THROWS_WITH_AS(j_const["/-"_json_pointer], "[json.exception.out_of_range.402] array index '-' (3) is out of range", json::out_of_range&); CHECK(!j_const.contains("/-"_json_pointer)); // error when using "-" with at CHECK_THROWS_WITH_AS(j.at("/-"_json_pointer), "[json.exception.out_of_range.402] array index '-' (7) is out of range", json::out_of_range&); CHECK_THROWS_WITH_AS(j_const.at("/-"_json_pointer), "[json.exception.out_of_range.402] array index '-' (3) is out of range", json::out_of_range&); CHECK(!j_const.contains("/-"_json_pointer)); } SECTION("const access") { const json j = {1, 2, 3}; // check reading access CHECK(j["/0"_json_pointer] == j[0]); CHECK(j["/1"_json_pointer] == j[1]); CHECK(j["/2"_json_pointer] == j[2]); // assign to nonexisting index CHECK_THROWS_WITH_AS(j.at("/3"_json_pointer), "[json.exception.out_of_range.401] array index 3 is out of range", json::out_of_range&); CHECK(!j.contains("/3"_json_pointer)); // assign to nonexisting index (with gap) CHECK_THROWS_WITH_AS(j.at("/5"_json_pointer), "[json.exception.out_of_range.401] array index 5 is out of range", json::out_of_range&); CHECK(!j.contains("/5"_json_pointer)); // assign to "-" CHECK_THROWS_WITH_AS(j["/-"_json_pointer], "[json.exception.out_of_range.402] array index '-' (3) is out of range", json::out_of_range&); CHECK_THROWS_WITH_AS(j.at("/-"_json_pointer), "[json.exception.out_of_range.402] array index '-' (3) is out of range", json::out_of_range&); CHECK(!j.contains("/-"_json_pointer)); } } SECTION("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 CHECK(j.flatten() == j_flatten); // check if unflattened result is as expected CHECK(j_flatten.unflatten() == j); // error for nonobjects CHECK_THROWS_WITH_AS(json(1).unflatten(), "[json.exception.type_error.314] only objects can be unflattened", json::type_error&); // error for nonprimitve values #if JSON_DIAGNOSTICS CHECK_THROWS_WITH_AS(json({{"/1", {1, 2, 3}}}).unflatten(), "[json.exception.type_error.315] (/~11) values in object must be primitive", json::type_error&); #else CHECK_THROWS_WITH_AS(json({{"/1", {1, 2, 3}}}).unflatten(), "[json.exception.type_error.315] values in object must be primitive", json::type_error&); #endif // error for conflicting values json const j_error = {{"", 42}, {"/foo", 17}}; CHECK_THROWS_WITH_AS(j_error.unflatten(), "[json.exception.type_error.313] invalid value to unflatten", json::type_error&); // explicit roundtrip check CHECK(j.flatten().unflatten() == j); // roundtrip for primitive values json j_null; CHECK(j_null.flatten().unflatten() == j_null); json j_number = 42; CHECK(j_number.flatten().unflatten() == j_number); json j_boolean = false; CHECK(j_boolean.flatten().unflatten() == j_boolean); json j_string = "foo"; CHECK(j_string.flatten().unflatten() == j_string); // roundtrip for empty structured values (will be unflattened to null) json const j_array(json::value_t::array); CHECK(j_array.flatten().unflatten() == json()); json const j_object(json::value_t::object); CHECK(j_object.flatten().unflatten() == json()); } SECTION("string representation") { for (const auto* ptr_str : {"", "/foo", "/foo/0", "/", "/a~1b", "/c%d", "/e^f", "/g|h", "/i\\j", "/k\"l", "/ ", "/m~0n" }) { json::json_pointer const ptr(ptr_str); std::stringstream ss; ss << ptr; CHECK(ptr.to_string() == ptr_str); CHECK(std::string(ptr) == ptr_str); CHECK(ss.str() == ptr_str); } } SECTION("conversion") { SECTION("array") { json j; // all numbers -> array j["/12"_json_pointer] = 0; CHECK(j.is_array()); } SECTION("object") { json j; // contains a number, but is not a number -> object j["/a12"_json_pointer] = 0; CHECK(j.is_object()); } } SECTION("empty, push, pop and parent") { const json j = { {"", "Hello"}, {"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"} } } }; // empty json_pointer returns the root JSON-object auto ptr = ""_json_pointer; CHECK(ptr.empty()); CHECK(j[ptr] == j); // simple field access ptr.push_back("pi"); CHECK(!ptr.empty()); CHECK(j[ptr] == j["pi"]); ptr.pop_back(); CHECK(ptr.empty()); CHECK(j[ptr] == j); // object and children access const std::string answer("answer"); ptr.push_back(answer); ptr.push_back("everything"); CHECK(!ptr.empty()); CHECK(j[ptr] == j["answer"]["everything"]); // check access via const pointer const auto cptr = ptr; CHECK(cptr.back() == "everything"); ptr.pop_back(); ptr.pop_back(); CHECK(ptr.empty()); CHECK(j[ptr] == j); // push key which has to be encoded ptr.push_back("object"); ptr.push_back("/"); CHECK(j[ptr] == j["object"]["/"]); CHECK(ptr.to_string() == "/object/~1"); CHECK(j[ptr.parent_pointer()] == j["object"]); ptr = ptr.parent_pointer().parent_pointer(); CHECK(ptr.empty()); CHECK(j[ptr] == j); // parent-pointer of the empty json_pointer is empty ptr = ptr.parent_pointer(); CHECK(ptr.empty()); CHECK(j[ptr] == j); CHECK_THROWS_WITH(ptr.pop_back(), "[json.exception.out_of_range.405] JSON pointer has no parent"); } SECTION("operators") { const json j = { {"", "Hello"}, {"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"} } } }; // empty json_pointer returns the root JSON-object auto ptr = ""_json_pointer; CHECK(j[ptr] == j); // simple field access ptr = ptr / "pi"; CHECK(j[ptr] == j["pi"]); ptr.pop_back(); CHECK(j[ptr] == j); // object and children access const std::string answer("answer"); ptr /= answer; ptr = ptr / "everything"; CHECK(j[ptr] == j["answer"]["everything"]); ptr.pop_back(); ptr.pop_back(); CHECK(j[ptr] == j); CHECK(ptr / ""_json_pointer == ptr); CHECK(j["/answer"_json_pointer / "/everything"_json_pointer] == j["answer"]["everything"]); // list children access CHECK(j["/list"_json_pointer / 1] == j["list"][1]); // push key which has to be encoded ptr /= "object"; ptr = ptr / "/"; CHECK(j[ptr] == j["object"]["/"]); CHECK(ptr.to_string() == "/object/~1"); } SECTION("equality comparison") { const char* ptr_cpstring = "/foo/bar"; const char ptr_castring[] = "/foo/bar"; // NOLINT(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) std::string ptr_string{"/foo/bar"}; auto ptr1 = json::json_pointer(ptr_string); auto ptr2 = json::json_pointer(ptr_string); // build with C++20 to test rewritten candidates // JSON_HAS_CPP_20 CHECK(ptr1 == ptr2); CHECK(ptr1 == "/foo/bar"); CHECK(ptr1 == ptr_cpstring); CHECK(ptr1 == ptr_castring); CHECK(ptr1 == ptr_string); CHECK("/foo/bar" == ptr1); CHECK(ptr_cpstring == ptr1); CHECK(ptr_castring == ptr1); CHECK(ptr_string == ptr1); CHECK_FALSE(ptr1 != ptr2); CHECK_FALSE(ptr1 != "/foo/bar"); CHECK_FALSE(ptr1 != ptr_cpstring); CHECK_FALSE(ptr1 != ptr_castring); CHECK_FALSE(ptr1 != ptr_string); CHECK_FALSE("/foo/bar" != ptr1); CHECK_FALSE(ptr_cpstring != ptr1); CHECK_FALSE(ptr_castring != ptr1); CHECK_FALSE(ptr_string != ptr1); SECTION("exceptions") { CHECK_THROWS_WITH_AS(ptr1 == "foo", "[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'", json::parse_error&); CHECK_THROWS_WITH_AS("foo" == ptr1, "[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'", json::parse_error&); CHECK_THROWS_WITH_AS(ptr1 == "/~~", "[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'", json::parse_error&); CHECK_THROWS_WITH_AS("/~~" == ptr1, "[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'", json::parse_error&); } } SECTION("less-than comparison") { auto ptr1 = json::json_pointer("/foo/a"); auto ptr2 = json::json_pointer("/foo/b"); CHECK(ptr1 < ptr2); CHECK_FALSE(ptr2 < ptr1); // build with C++20 // JSON_HAS_CPP_20 #if JSON_HAS_THREE_WAY_COMPARISON CHECK((ptr1 <=> ptr2) == std::strong_ordering::less); // *NOPAD* CHECK(ptr2 > ptr1); #endif } SECTION("usable as map key") { auto ptr = json::json_pointer("/foo"); std::map<json::json_pointer, int> m; m[ptr] = 42; CHECK(m.find(ptr) != m.end()); } SECTION("backwards compatibility and mixing") { json j = R"( { "foo": ["bar", "baz"] } )"_json; using nlohmann::ordered_json; using json_ptr_str = nlohmann::json_pointer<std::string>; using json_ptr_j = nlohmann::json_pointer<json>; using json_ptr_oj = nlohmann::json_pointer<ordered_json>; CHECK(std::is_same<json_ptr_str::string_t, json::json_pointer::string_t>::value); CHECK(std::is_same<json_ptr_str::string_t, ordered_json::json_pointer::string_t>::value); CHECK(std::is_same<json_ptr_str::string_t, json_ptr_j::string_t>::value); CHECK(std::is_same<json_ptr_str::string_t, json_ptr_oj::string_t>::value); std::string const ptr_string{"/foo/0"}; json_ptr_str ptr{ptr_string}; json_ptr_j ptr_j{ptr_string}; json_ptr_oj ptr_oj{ptr_string}; CHECK(j.contains(ptr)); CHECK(j.contains(ptr_j)); CHECK(j.contains(ptr_oj)); CHECK(j.at(ptr) == j.at(ptr_j)); CHECK(j.at(ptr) == j.at(ptr_oj)); CHECK(j[ptr] == j[ptr_j]); CHECK(j[ptr] == j[ptr_oj]); CHECK(j.value(ptr, "x") == j.value(ptr_j, "x")); CHECK(j.value(ptr, "x") == j.value(ptr_oj, "x")); CHECK(ptr == ptr_j); CHECK(ptr == ptr_oj); CHECK_FALSE(ptr != ptr_j); CHECK_FALSE(ptr != ptr_oj); SECTION("equality comparison") { // build with C++20 to test rewritten candidates // JSON_HAS_CPP_20 CHECK(ptr == ptr_j); CHECK(ptr == ptr_oj); CHECK(ptr_j == ptr); CHECK(ptr_j == ptr_oj); CHECK(ptr_oj == ptr_j); CHECK(ptr_oj == ptr); CHECK_FALSE(ptr != ptr_j); CHECK_FALSE(ptr != ptr_oj); CHECK_FALSE(ptr_j != ptr); CHECK_FALSE(ptr_j != ptr_oj); CHECK_FALSE(ptr_oj != ptr_j); CHECK_FALSE(ptr_oj != ptr); } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-class_const_iterator.cpp
.cpp
14,545
394
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #define JSON_TESTS_PRIVATE #include <nlohmann/json.hpp> using nlohmann::json; TEST_CASE("const_iterator class") { SECTION("construction") { SECTION("constructor") { SECTION("null") { json const j(json::value_t::null); json::const_iterator const it(&j); } SECTION("object") { json const j(json::value_t::object); json::const_iterator const it(&j); } SECTION("array") { json const j(json::value_t::array); json::const_iterator const it(&j); } } SECTION("copy assignment") { json const j(json::value_t::null); json::const_iterator const it(&j); json::const_iterator it2(&j); it2 = it; } SECTION("copy constructor from non-const iterator") { SECTION("create from uninitialized iterator") { const json::iterator it {}; json::const_iterator const cit(it); } SECTION("create from initialized iterator") { json j; const json::iterator it = j.begin(); json::const_iterator const cit(it); } } } SECTION("initialization") { SECTION("set_begin") { SECTION("null") { json const j(json::value_t::null); json::const_iterator it(&j); it.set_begin(); CHECK((it == j.cbegin())); } SECTION("object") { json const j(json::value_t::object); json::const_iterator it(&j); it.set_begin(); CHECK((it == j.cbegin())); } SECTION("array") { json const j(json::value_t::array); json::const_iterator it(&j); it.set_begin(); CHECK((it == j.cbegin())); } } SECTION("set_end") { SECTION("null") { json const j(json::value_t::null); json::const_iterator it(&j); it.set_end(); CHECK((it == j.cend())); } SECTION("object") { json const j(json::value_t::object); json::const_iterator it(&j); it.set_end(); CHECK((it == j.cend())); } SECTION("array") { json const j(json::value_t::array); json::const_iterator it(&j); it.set_end(); CHECK((it == j.cend())); } } } SECTION("element access") { SECTION("operator*") { SECTION("null") { json const j(json::value_t::null); json::const_iterator const it = j.cbegin(); CHECK_THROWS_WITH_AS(*it, "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("number") { json const j(17); json::const_iterator it = j.cbegin(); CHECK(*it == json(17)); it = j.cend(); CHECK_THROWS_WITH_AS(*it, "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("object") { json const j({{"foo", "bar"}}); json::const_iterator const it = j.cbegin(); CHECK(*it == json("bar")); } SECTION("array") { json const j({1, 2, 3, 4}); json::const_iterator const it = j.cbegin(); CHECK(*it == json(1)); } } SECTION("operator->") { SECTION("null") { json const j(json::value_t::null); json::const_iterator const it = j.cbegin(); CHECK_THROWS_WITH_AS(std::string(it->type_name()), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("number") { json const j(17); json::const_iterator it = j.cbegin(); CHECK(std::string(it->type_name()) == "number"); it = j.cend(); CHECK_THROWS_WITH_AS(std::string(it->type_name()), "[json.exception.invalid_iterator.214] cannot get value", json::invalid_iterator&); } SECTION("object") { json const j({{"foo", "bar"}}); json::const_iterator const it = j.cbegin(); CHECK(std::string(it->type_name()) == "string"); } SECTION("array") { json const j({1, 2, 3, 4}); json::const_iterator const it = j.cbegin(); CHECK(std::string(it->type_name()) == "number"); } } } SECTION("increment/decrement") { SECTION("post-increment") { SECTION("null") { json const j(json::value_t::null); json::const_iterator it = j.cbegin(); CHECK((it.m_it.primitive_iterator.m_it == 1)); it++; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("number") { json const j(17); json::const_iterator it = j.cbegin(); CHECK((it.m_it.primitive_iterator.m_it == 0)); it++; CHECK((it.m_it.primitive_iterator.m_it == 1)); it++; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json const j({{"foo", "bar"}}); json::const_iterator it = j.cbegin(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); it++; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); } SECTION("array") { json const j({1, 2, 3, 4}); json::const_iterator it = j.cbegin(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it++; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); } } SECTION("pre-increment") { SECTION("null") { json const j(json::value_t::null); json::const_iterator it = j.cbegin(); CHECK((it.m_it.primitive_iterator.m_it == 1)); ++it; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("number") { json const j(17); json::const_iterator it = j.cbegin(); CHECK((it.m_it.primitive_iterator.m_it == 0)); ++it; CHECK((it.m_it.primitive_iterator.m_it == 1)); ++it; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json const j({{"foo", "bar"}}); json::const_iterator it = j.cbegin(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); ++it; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); } SECTION("array") { json const j({1, 2, 3, 4}); json::const_iterator it = j.cbegin(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); ++it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); } } SECTION("post-decrement") { SECTION("null") { json const j(json::value_t::null); json::const_iterator const it = j.cend(); CHECK((it.m_it.primitive_iterator.m_it == 1)); } SECTION("number") { json const j(17); json::const_iterator it = j.cend(); CHECK((it.m_it.primitive_iterator.m_it == 1)); it--; CHECK((it.m_it.primitive_iterator.m_it == 0)); it--; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json const j({{"foo", "bar"}}); json::const_iterator it = j.cend(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); it--; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); } SECTION("array") { json const j({1, 2, 3, 4}); json::const_iterator it = j.cend(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); it--; CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); } } SECTION("pre-decrement") { SECTION("null") { json const j(json::value_t::null); json::const_iterator const it = j.cend(); CHECK((it.m_it.primitive_iterator.m_it == 1)); } SECTION("number") { json const j(17); json::const_iterator it = j.cend(); CHECK((it.m_it.primitive_iterator.m_it == 1)); --it; CHECK((it.m_it.primitive_iterator.m_it == 0)); --it; CHECK((it.m_it.primitive_iterator.m_it != 0 && it.m_it.primitive_iterator.m_it != 1)); } SECTION("object") { json const j({{"foo", "bar"}}); json::const_iterator it = j.cend(); CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->end())); --it; CHECK((it.m_it.object_iterator == it.m_object->m_data.m_value.object->begin())); } SECTION("array") { json const j({1, 2, 3, 4}); json::const_iterator it = j.cend(); CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); --it; CHECK((it.m_it.array_iterator == it.m_object->m_data.m_value.array->begin())); CHECK((it.m_it.array_iterator != it.m_object->m_data.m_value.array->end())); } } } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-unicode5.cpp
.cpp
10,970
325
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" // for some reason including this after the json header leads to linker errors with VS 2017... #include <locale> #include <nlohmann/json.hpp> using nlohmann::json; #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include "make_test_data_available.hpp" // this test suite uses static variables with non-trivial destructors DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") namespace { extern size_t calls; size_t calls = 0; void check_utf8dump(bool success_expected, int byte1, int byte2, int byte3, int byte4); void check_utf8dump(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1) { static std::string json_string; json_string.clear(); CAPTURE(byte1) CAPTURE(byte2) CAPTURE(byte3) CAPTURE(byte4) json_string += std::string(1, static_cast<char>(byte1)); if (byte2 != -1) { json_string += std::string(1, static_cast<char>(byte2)); } if (byte3 != -1) { json_string += std::string(1, static_cast<char>(byte3)); } if (byte4 != -1) { json_string += std::string(1, static_cast<char>(byte4)); } CAPTURE(json_string) // store the string in a JSON value static json j; static json j2; j = json_string; j2 = "abc" + json_string + "xyz"; static std::string s_ignored; static std::string s_ignored2; static std::string s_ignored_ascii; static std::string s_ignored2_ascii; static std::string s_replaced; static std::string s_replaced2; static std::string s_replaced_ascii; static std::string s_replaced2_ascii; // dumping with ignore/replace must not throw in any case s_ignored = j.dump(-1, ' ', false, json::error_handler_t::ignore); s_ignored2 = j2.dump(-1, ' ', false, json::error_handler_t::ignore); s_ignored_ascii = j.dump(-1, ' ', true, json::error_handler_t::ignore); s_ignored2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::ignore); s_replaced = j.dump(-1, ' ', false, json::error_handler_t::replace); s_replaced2 = j2.dump(-1, ' ', false, json::error_handler_t::replace); s_replaced_ascii = j.dump(-1, ' ', true, json::error_handler_t::replace); s_replaced2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::replace); if (success_expected) { static std::string s_strict; // strict mode must not throw if success is expected s_strict = j.dump(); // all dumps should agree on the string CHECK(s_strict == s_ignored); CHECK(s_strict == s_replaced); } else { // strict mode must throw if success is not expected CHECK_THROWS_AS(j.dump(), json::type_error&); // ignore and replace must create different dumps CHECK(s_ignored != s_replaced); // check that replace string contains a replacement character CHECK(s_replaced.find("\xEF\xBF\xBD") != std::string::npos); } // check that prefix and suffix are preserved CHECK(s_ignored2.substr(1, 3) == "abc"); CHECK(s_ignored2.substr(s_ignored2.size() - 4, 3) == "xyz"); CHECK(s_ignored2_ascii.substr(1, 3) == "abc"); CHECK(s_ignored2_ascii.substr(s_ignored2_ascii.size() - 4, 3) == "xyz"); CHECK(s_replaced2.substr(1, 3) == "abc"); CHECK(s_replaced2.substr(s_replaced2.size() - 4, 3) == "xyz"); CHECK(s_replaced2_ascii.substr(1, 3) == "abc"); CHECK(s_replaced2_ascii.substr(s_replaced2_ascii.size() - 4, 3) == "xyz"); } void check_utf8string(bool success_expected, int byte1, int byte2, int byte3, int byte4); // create and check a JSON string with up to four UTF-8 bytes void check_utf8string(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1) { if (++calls % 100000 == 0) { std::cout << calls << " of 1246225 UTF-8 strings checked" << std::endl; // NOLINT(performance-avoid-endl) } static std::string json_string; json_string = "\""; CAPTURE(byte1) json_string += std::string(1, static_cast<char>(byte1)); if (byte2 != -1) { CAPTURE(byte2) json_string += std::string(1, static_cast<char>(byte2)); } if (byte3 != -1) { CAPTURE(byte3) json_string += std::string(1, static_cast<char>(byte3)); } if (byte4 != -1) { CAPTURE(byte4) json_string += std::string(1, static_cast<char>(byte4)); } json_string += "\""; CAPTURE(json_string) json _; if (success_expected) { CHECK_NOTHROW(_ = json::parse(json_string)); } else { CHECK_THROWS_AS(_ = json::parse(json_string), json::parse_error&); } } } // namespace TEST_CASE("Unicode (5/5)" * doctest::skip()) { SECTION("RFC 3629") { /* 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 */ SECTION("UTF8-4 (xF4 x80-8F UTF8-tail UTF8-tail)") { SECTION("well-formed") { 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) { check_utf8string(true, byte1, byte2, byte3, byte4); check_utf8dump(true, byte1, byte2, byte3, byte4); } } } } } SECTION("ill-formed: missing second byte") { for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) { check_utf8string(false, byte1); check_utf8dump(false, byte1); } } SECTION("ill-formed: missing third byte") { for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) { for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) { check_utf8string(false, byte1, byte2); check_utf8dump(false, byte1, byte2); } } } SECTION("ill-formed: missing fourth byte") { for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1) { for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2) { for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3) { check_utf8string(false, byte1, byte2, byte3); check_utf8dump(false, byte1, byte2, byte3); } } } } SECTION("ill-formed: wrong second byte") { 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) { check_utf8string(false, byte1, byte2, byte3, byte4); check_utf8dump(false, byte1, byte2, byte3, byte4); } } } } } SECTION("ill-formed: wrong third byte") { 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) { check_utf8string(false, byte1, byte2, byte3, byte4); check_utf8dump(false, byte1, byte2, byte3, byte4); } } } } } SECTION("ill-formed: wrong fourth byte") { 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; } check_utf8string(false, byte1, byte2, byte3, byte4); check_utf8dump(false, byte1, byte2, byte3, byte4); } } } } } } } } DOCTEST_CLANG_SUPPRESS_WARNING_POP
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/unit-binary_formats.cpp
.cpp
10,751
212
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "doctest_compatibility.h" #include <nlohmann/json.hpp> using nlohmann::json; #include <fstream> #include "make_test_data_available.hpp" TEST_CASE("Binary Formats" * doctest::skip()) { SECTION("canada.json") { const auto* filename = TEST_DATA_DIRECTORY "/nativejson-benchmark/canada.json"; const json j = json::parse(std::ifstream(filename)); const auto json_size = j.dump().size(); const auto bjdata_1_size = json::to_bjdata(j).size(); const auto bjdata_2_size = json::to_bjdata(j, true).size(); const auto bjdata_3_size = json::to_bjdata(j, true, true).size(); const auto bson_size = json::to_bson(j).size(); const auto cbor_size = json::to_cbor(j).size(); const auto msgpack_size = json::to_msgpack(j).size(); const auto ubjson_1_size = json::to_ubjson(j).size(); const auto ubjson_2_size = json::to_ubjson(j, true).size(); const auto ubjson_3_size = json::to_ubjson(j, true, true).size(); CHECK(json_size == 2090303); CHECK(bjdata_1_size == 1112030); CHECK(bjdata_2_size == 1224148); CHECK(bjdata_3_size == 1224148); CHECK(bson_size == 1794522); CHECK(cbor_size == 1055552); CHECK(msgpack_size == 1056145); CHECK(ubjson_1_size == 1112030); CHECK(ubjson_2_size == 1224148); CHECK(ubjson_3_size == 1169069); CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0)); CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(53.199)); CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(58.563)); CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(58.563)); CHECK((100.0 * double(bson_size) / double(json_size)) == Approx(85.849)); CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(50.497)); CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(50.526)); CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(53.199)); CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(58.563)); CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(55.928)); } SECTION("twitter.json") { const auto* filename = TEST_DATA_DIRECTORY "/nativejson-benchmark/twitter.json"; const json j = json::parse(std::ifstream(filename)); const auto json_size = j.dump().size(); const auto bjdata_1_size = json::to_bjdata(j).size(); const auto bjdata_2_size = json::to_bjdata(j, true).size(); const auto bjdata_3_size = json::to_bjdata(j, true, true).size(); const auto bson_size = json::to_bson(j).size(); const auto cbor_size = json::to_cbor(j).size(); const auto msgpack_size = json::to_msgpack(j).size(); const auto ubjson_1_size = json::to_ubjson(j).size(); const auto ubjson_2_size = json::to_ubjson(j, true).size(); const auto ubjson_3_size = json::to_ubjson(j, true, true).size(); CHECK(json_size == 466906); CHECK(bjdata_1_size == 425342); CHECK(bjdata_2_size == 429970); CHECK(bjdata_3_size == 429970); CHECK(bson_size == 444568); CHECK(cbor_size == 402814); CHECK(msgpack_size == 401510); CHECK(ubjson_1_size == 426160); CHECK(ubjson_2_size == 430788); CHECK(ubjson_3_size == 430798); CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0)); CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(91.097)); CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(92.089)); CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(92.089)); CHECK((100.0 * double(bson_size) / double(json_size)) == Approx(95.215)); CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(86.273)); CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(85.993)); CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(91.273)); CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(92.264)); CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(92.266)); } SECTION("citm_catalog.json") { const auto* filename = TEST_DATA_DIRECTORY "/nativejson-benchmark/citm_catalog.json"; const json j = json::parse(std::ifstream(filename)); const auto json_size = j.dump().size(); const auto bjdata_1_size = json::to_bjdata(j).size(); const auto bjdata_2_size = json::to_bjdata(j, true).size(); const auto bjdata_3_size = json::to_bjdata(j, true, true).size(); const auto bson_size = json::to_bson(j).size(); const auto cbor_size = json::to_cbor(j).size(); const auto msgpack_size = json::to_msgpack(j).size(); const auto ubjson_1_size = json::to_ubjson(j).size(); const auto ubjson_2_size = json::to_ubjson(j, true).size(); const auto ubjson_3_size = json::to_ubjson(j, true, true).size(); CHECK(json_size == 500299); CHECK(bjdata_1_size == 390781); CHECK(bjdata_2_size == 433557); CHECK(bjdata_3_size == 432964); CHECK(bson_size == 479430); CHECK(cbor_size == 342373); CHECK(msgpack_size == 342473); CHECK(ubjson_1_size == 391463); CHECK(ubjson_2_size == 434239); CHECK(ubjson_3_size == 425073); CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0)); CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(78.109)); CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(86.659)); CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(86.541)); CHECK((100.0 * double(bson_size) / double(json_size)) == Approx(95.828)); CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(68.433)); CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(68.453)); CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(78.245)); CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(86.795)); CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(84.963)); } SECTION("jeopardy.json") { const auto* filename = TEST_DATA_DIRECTORY "/jeopardy/jeopardy.json"; json j = json::parse(std::ifstream(filename)); const auto json_size = j.dump().size(); const auto bjdata_1_size = json::to_bjdata(j).size(); const auto bjdata_2_size = json::to_bjdata(j, true).size(); const auto bjdata_3_size = json::to_bjdata(j, true, true).size(); const auto bson_size = json::to_bson({{"", j}}).size(); // wrap array in object for BSON const auto cbor_size = json::to_cbor(j).size(); const auto msgpack_size = json::to_msgpack(j).size(); const auto ubjson_1_size = json::to_ubjson(j).size(); const auto ubjson_2_size = json::to_ubjson(j, true).size(); const auto ubjson_3_size = json::to_ubjson(j, true, true).size(); CHECK(json_size == 52508728); CHECK(bjdata_1_size == 50710965); CHECK(bjdata_2_size == 51144830); CHECK(bjdata_3_size == 51144830); CHECK(bson_size == 56008520); CHECK(cbor_size == 46187320); CHECK(msgpack_size == 46158575); CHECK(ubjson_1_size == 50710965); CHECK(ubjson_2_size == 51144830); CHECK(ubjson_3_size == 49861422); CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0)); CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(96.576)); CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(97.402)); CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(97.402)); CHECK((100.0 * double(bson_size) / double(json_size)) == Approx(106.665)); CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(87.961)); CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(87.906)); CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(96.576)); CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(97.402)); CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(94.958)); } SECTION("sample.json") { const auto* filename = TEST_DATA_DIRECTORY "/json_testsuite/sample.json"; const json j = json::parse(std::ifstream(filename)); const auto json_size = j.dump().size(); const auto bjdata_1_size = json::to_bjdata(j).size(); const auto bjdata_2_size = json::to_bjdata(j, true).size(); const auto bjdata_3_size = json::to_bjdata(j, true, true).size(); // BSON cannot process the file as it contains code point U+0000 const auto cbor_size = json::to_cbor(j).size(); const auto msgpack_size = json::to_msgpack(j).size(); const auto ubjson_1_size = json::to_ubjson(j).size(); const auto ubjson_2_size = json::to_ubjson(j, true).size(); const auto ubjson_3_size = json::to_ubjson(j, true, true).size(); CHECK(json_size == 168677); CHECK(bjdata_1_size == 148695); CHECK(bjdata_2_size == 150569); CHECK(bjdata_3_size == 150569); CHECK(cbor_size == 147095); CHECK(msgpack_size == 147017); CHECK(ubjson_1_size == 148695); CHECK(ubjson_2_size == 150569); CHECK(ubjson_3_size == 150883); CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0)); CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(88.153)); CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(89.264)); CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(89.264)); CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(87.205)); CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(87.158)); CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(88.153)); CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(89.264)); CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(89.450)); } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/src/fuzzer-parse_ubjson.cpp
.cpp
2,778
86
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT /* This file implements a parser test suitable for fuzz testing. Given a byte array data, it performs the following steps: - j1 = from_ubjson(data) - vec = to_ubjson(j1) - j2 = from_ubjson(vec) - assert(j1 == j2) - vec2 = to_ubjson(j1, use_size = true, use_type = false) - j3 = from_ubjson(vec2) - assert(j1 == j3) - vec3 = to_ubjson(j1, use_size = true, use_type = true) - j4 = from_ubjson(vec3) - assert(j1 == j4) The provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer drivers. */ #include <iostream> #include <sstream> #include <nlohmann/json.hpp> using json = nlohmann::json; // see http://llvm.org/docs/LibFuzzer.html extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { try { // step 1: parse input std::vector<uint8_t> const vec1(data, data + size); json const j1 = json::from_ubjson(vec1); try { // step 2.1: round trip without adding size annotations to container types std::vector<uint8_t> const vec2 = json::to_ubjson(j1, false, false); // step 2.2: round trip with adding size annotations but without adding type annonations to container types std::vector<uint8_t> const vec3 = json::to_ubjson(j1, true, false); // step 2.3: round trip with adding size as well as type annotations to container types std::vector<uint8_t> const vec4 = json::to_ubjson(j1, true, true); // parse serialization json const j2 = json::from_ubjson(vec2); json const j3 = json::from_ubjson(vec3); json const j4 = json::from_ubjson(vec4); // serializations must match assert(json::to_ubjson(j2, false, false) == vec2); assert(json::to_ubjson(j3, true, false) == vec3); assert(json::to_ubjson(j4, true, true) == vec4); } catch (const json::parse_error&) { // parsing a UBJSON serialization must not fail assert(false); } } catch (const json::parse_error&) { // parse errors are ok, because input may be random bytes } catch (const json::type_error&) { // type errors can occur during parsing, too } catch (const json::out_of_range&) { // out of range errors may happen if provided sizes are excessive } // return 0 - non-zero return values are reserved for future use return 0; }
C++